<?php
class Presentasecabang extends MY_Controller
{
    var $db;
    public function index()
    {
        echo "Presentase Cabang";
    }

    public function __construct()
    {
        parent::__construct();
    }

    function listpresentasecabang()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("invalid token");
                exit;
            }

            $prm = $this->sys_input;
            $limit = 10;
            $pages = 0;

            if ($prm['currpages'] > 0) {
                $pages = ($prm['currpages'] - 1) * $limit;
            }

            $total = "SELECT COUNT(*) as total FROM branch_percent WHERE BranchPercentIsActive = 'Y'";
            $qtotal = $this->db->query($total);
            $rtotal = $qtotal->result_array()[0]['total'];

            $sql = "SELECT 
                BranchPercentID,
                BranchPercentType,
                BranchPercentIsActive
                from branch_percent
                where BranchPercentIsActive = 'Y' 
                limit ? offset ?
            ";
            $query = $this->db->query($sql, [$limit, $pages]);
            if (! $query) {
                $this->sys_error_db("get listing presentase cabang");
                exit;
            }
            $rows = $query->result_array();

            $result = array(
                "total" => (int)$rtotal,
                "records" => $rows
            );
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    function inserttypepresentase()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("invalid token");
                exit;
            }

            $this->db->trans_begin();
            $prm = $this->sys_input;
            $typename = $prm['typename'];
            $userid = $this->sys_user["M_UserID"];

            $sql = "INSERT INTO `branch_percent` (
                BranchPercentType,
                BranchPercentCreated,
                BranchPercentCreatedUserID
            ) VALUES (?, NOW(), ?)";

            $query = $this->db->query($sql, [$typename, $userid]);
            if (!$query) {
                $this->db->trans_rollback();
                $this->sys_error_db("type presentase error", $this->db);
                exit;
            }

            $this->db->trans_commit();
            $result = array(
                "total" => 1,
                "records" => 0
            );
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    function edittypepresentase()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("invalid token");
                exit;
            }

            $this->db->trans_begin();
            $prm = $this->sys_input;
            $typeid = $prm['typeid'];
            $typename = $prm['typename'];
            $userid = $this->sys_user["M_UserID"];

            $sql = "UPDATE branch_percent SET
            BranchPercentType = ?,
            BranchPercentLastUpdated = now(),
            BranchPercentLastUpdatedUserID = ?
            WHERE BranchPercentID = ?";

            $query = $this->db->query($sql, [
                $typename,
                $userid,
                $typeid
            ]);

            if (!$query) {
                $this->db->trans_rollback();
                $this->sys_error_db("update type presentase cabang", $this->db);
                exit;
            }

            $this->db->trans_commit();
            $result = array("total" => 1, "records" => array("BranchPercentID" => $typeid));
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    function deletetypepresentase()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("invalid token");
                exit;
            }

            $this->db->trans_begin();
            $prm = $this->sys_input;
            $typeid = $prm['typeid'];
            $userid = $this->sys_user["M_UserID"];

            $sql = "UPDATE branch_percent SET 
            BranchPercentIsActive = 'N',
            BranchPercentDeleted = now(),
            BranchPercentDeletedUserID = ?
            WHERE BranchPercentID = ?";

            $query = $this->db->query($sql, [
                $userid,
                $typeid
            ]);

            if (!$query) {
                $this->db->trans_rollback();
                $this->sys_error_db("delete type presentase", $this->db);
                exit;
            }

            $this->db->trans_commit();
            $result = array("total" => 1, "records" => array("BranchPercentID" => $typeid));
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $msg = $exc->getMessage();
            $this->sys_error($msg);
        }
    }

    function detailpresentasecabang()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("invalid token");
                exit;
            }

            $prm = $this->sys_input;
            $branchPercentID = $prm['presentasecabangid'];
            $currPages = $prm['currpages'];

            $total = "SELECT 
                COUNT(DISTINCT S_RegionalID) as total
                FROM branch_percent_detail
                JOIN m_branch ON BranchPercentDetailM_BranchID = M_BranchID
                JOIN s_regional ON BranchPercentDetailS_RegionalID = S_RegionalID
                WHERE BranchPercentDetailBranchPercentID = ? AND BranchPercentDetailIsActive = 'Y'
            ";

            $que_to = $this->db->query($total, array($branchPercentID));
            if (!$que_to) {
                $this->sys_error_db("error get total data detail");
                exit;
            }
            $row_to = $que_to->result_array()[0]["total"];

            $pages = 0;
            $limit = 10;

            if ($currPages > 0) {
                $pages = ($currPages - 1) * $limit;
            }

            $sql = "SELECT 
                S_RegionalID,
                S_RegionalName, 
                GROUP_CONCAT(CONCAT(M_BranchName, ' (', BranchPercentDetailValue, '%)') ORDER BY M_BranchName SEPARATOR ', ') as DetailCabang,
                GROUP_CONCAT(BranchPercentDetailID SEPARATOR ',') AS ListBranchPercentDetailID
                from branch_percent_detail
                join m_branch on BranchPercentDetailM_BranchID = M_BranchID
                join s_regional on BranchPercentDetailS_RegionalID = S_RegionalID
                where BranchPercentDetailBranchPercentID = ? and BranchPercentDetailIsActive = 'Y'
                group by S_RegionalID
                LIMIT ? OFFSET ?;
            ";
            $query = $this->db->query($sql, array($branchPercentID, $limit, $pages));
            if (!$query) {
                $this->sys_error_db("get listing detail presentase cabang");
                exit;
            }
            $rows = $query->result_array();

            $result = array(
                "total" => $row_to,
                "records" => $rows
            );

            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    function getlistregional()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("invalid token");
                exit;
            }

            $sql = "SELECT 
                S_RegionalID, 
                S_RegionalName 
                FROM s_regional 
                WHERE S_RegionalIsActive = 'Y'";

            $query = $this->db->query($sql);
            if (! $query) {
                $this->sys_error_db("get listing regional");
                exit;
            }
            $rows = $query->result_array();
            $result = array(
                "total" => sizeof($rows),
                "records" => $rows
            );
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $mssg = $exc->getMessage();
            $this->sys_error($mssg);
        }
    }

    function getregionalbranch()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("invalid token");
                exit;
            }

            $prm = $this->sys_input;
            $regionalid = $prm['regionalid'];
            $user_company = $this->sys_user["M_BranchCompanyID"];

            // $sql = "SELECT 
            //     M_BranchID,
            //     M_BranchCode,
            //     M_BranchName,
            //     0 as branchValue,
            //     '' as accountNumber,
            //     '' as searchCoa
            //     from m_branch
            //     where M_BranchIsActive = 'Y' and M_BranchS_RegionalID = ?";

            $sql = "SELECT 
                M_BranchID,
                M_BranchCode,
                M_BranchName,
                0 as branchValue,
                '' as accountNumber,
                '' as searchCoa
                from m_branch_company
                join m_branch_companydetail on M_BranchCompanyDetailM_BranchCompanyID = M_BranchCompanyID
                and M_BranchCompanyDetailIsActive = 'Y'
                join m_branch on M_BranchCode = M_BranchCompanyDetailM_BranchCode and M_BranchIsActive = 'Y'
                where M_BranchCompanyIsActive = 'Y' and M_BranchS_RegionalID = ? and M_BranchCompanyID = ?
            ";

            $query = $this->db->query($sql, array($regionalid, $user_company));
            if (! $query) {
                $this->sys_error_db("get listing regional branches");
                exit;
            }
            $rows = $query->result_array();
            $result = array(
                "total" => sizeof($rows),
                "records" => $rows
            );
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $mssg = $exc->getMessage();
            $this->sys_error($mssg);
        }
    }

    function insertdetailprecab()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("invalid token");
                exit;
            }

            $this->db->trans_begin();
            $prm = $this->sys_input;
            $input = $prm["branchvalue"];
            $userid = $this->sys_user["M_UserID"];

            foreach ($input as $item) {
                $bpid = $item['branchpercentid'];
                $rgid = $item['regionalid'];
                $brid = $item['branchid'];
                $valu = $item['value'];
                $noacc = $item['noacc'];

                $sql = "INSERT INTO `branch_percent_detail` (
                    BranchPercentDetailBranchPercentID,
                    BranchPercentDetailS_RegionalID,
                    BranchPercentDetailM_BranchID,
                    BranchPercentDetailValue,
                    BranchPercentDetailAccountNumber,
                    BranchPercentDetailCreated,
                    BranchPercentDetailCreatedUserID
                ) VALUES (?, ?, ?, ?, ?, NOW(), ?)";
                $query = $this->db->query($sql, [$bpid, $rgid, $brid, $valu, $noacc, $userid]);
                if (!$query) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("error insert precab detail");
                    exit;
                }
            }

            $this->db->trans_commit();
            $result = array(
                "total" => sizeof($input),
                "records" => 0
            );
            $this->sys_ok($result);
        } catch (Exception $ex) {
            $msg = $ex->getMessage();
            $this->sys_error($msg);
        }
    }

    function editdetailprecab()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("invalid token");
                exit;
            }

            $this->db->trans_begin();
            $prm = $this->sys_input;
            $input = $prm["branchvalue"];
            $userid = $this->sys_user["M_UserID"];

            foreach ($input as $item) {
                $detid = $item['precabdetailid'];
                $value = $item['value'];
                $noacc = $item['noacc'];

                $sql = "UPDATE branch_percent_detail SET
                BranchPercentDetailValue = ?,
                BranchPercentDetailAccountNumber = ?,
                BranchPercentDetailLastUpdated = now(),
                BranchPercentDetailLastUpdatedUserID = ?
                WHERE BranchPercentDetailID = ?";

                $query = $this->db->query($sql, [$value, $noacc, $userid, $detid]);
                if (!$query) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("error update precab detail");
                    exit;
                }
            }

            $this->db->trans_commit();
            $result = array(
                "total" => sizeof($input),
                "records" => 0
            );
            $this->sys_ok($result);
        } catch (Exception $ex) {
            $msg = $ex->getMessage();
            $this->sys_error($msg);
        }
    }

    function getvaluedetailprecab()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("invalid token");
                exit;
            }

            $prm = $this->sys_input;
            $regionalid = $prm['regionalid'];
            $branchpercentid = $prm['branchpercentid'];

            $sql = "SELECT 
                M_BranchID,
                M_BranchCode,
                M_BranchName,
                BranchPercentDetailID,
                CAST(COALESCE(BranchPercentDetailValue, 0) AS DECIMAL(10, 2)) as branchValue,
                COALESCE(BranchPercentDetailAccountNumber, 0) as accountNumber,
                '' as searchCoa
                from m_branch
                join branch_percent_detail on BranchPercentDetailM_BranchID = M_BranchID
                join branch_percent on BranchPercentID = BranchPercentDetailBranchPercentID
                where M_BranchIsActive = 'Y' and M_BranchS_RegionalID = ? 
                and BranchPercentID =  ?";
            $query = $this->db->query($sql, [$regionalid, $branchpercentid]);
            if (!$query) {
                $this->sys_error_db("error get current value detail precab");
                exit;
            }
            $rows = $query->result_array();
            $result = array(
                "total" => sizeof($rows),
                "records" => $rows
            );
            $this->sys_ok($result);
        } catch (Exception $ex) {
            $msg = $ex->getMessage();
            $this->sys_error($msg);
        }
    }

    function deletedetailprecab()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("invalid token");
                exit;
            }

            $this->db->trans_begin();
            $prm = $this->sys_input;
            $input = "(" . $prm["precabdetailid"] . ")";
            $userid = $this->sys_user["M_UserID"];

            $sql = "UPDATE branch_percent_detail SET 
            BranchPercentDetailIsActive = 'N',
            BranchPercentDetailDeleted = now(),
            BranchPercentDetailDeletedUserID = ?
            WHERE BranchPercentDetailID IN " . $input;
            $query = $this->db->query($sql, [$userid]);
            if (!$query) {
                $this->db->trans_rollback();
                $this->sys_error_db("error delete precab detail");
                exit;
            }

            $this->db->trans_commit();
            $result = array(
                "total" => 1,
                "records" => $input
            );
            $this->sys_ok($result);
        } catch (Exception $ex) {
            $msg = $ex->getMessage();
            $this->sys_error($msg);
        }
    }

    function searchcoa()
    {
        try {
            if (! $this->isLogin) {
                $this->sys_error("Invalid token");
                exit;
            }

            $prm = $this->sys_input;
            $keyword = "%" . $prm['keyword'] . "%";

            $sql = "SELECT 
            coaID as id,
            coaAccountNo as number,
            coaDescription as keterangan,
            CONCAT(coaAccountNo, ' - ' ,coaDescription) as display
            FROM coa
            WHERE coaIsActive = 'Y' AND coaIsInput = 'Y'
            AND (CONCAT(coaAccountNo, ' - ' ,coaDescription) LIKE ?)
            LIMIT 20";
            $query = $this->db->query($sql, [$keyword]);
            if (!$query) {
                $this->sys_error_db("Error get listing coa", $this->db);
                exit;
            }
            $rows = $query->result_array();
            $result = array(
                "total" => sizeof($rows),
                "records" => $rows
            );
            $this->sys_ok($result);
        } catch (Exception $ex) {
            $msg = $ex->getMessage();
            $this->sys_error($msg);
        }
    }
}
