<?php
class Bankcoa extends MY_Controller
{
    var $db;
    public function index()
    {
        echo "MAPPING BANK COA API";
    }

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

    function getRegional()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
            }

            $sql = "SELECT S_RegionalID,
                S_RegionalName
                FROM s_regional
                WHERE S_RegionalIsActive = 'Y'
                ORDER BY S_RegionalName ASC";
            $qry = $this->db->query($sql, []);
            if ($qry) {
                $rows = $qry->result_array();
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select regional", $this->db);
                exit;
            }

            $result = array(
                "records" => $rows,
                "sql" => $this->db->last_query()
            );

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

    function getBranch()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
            }
            $prm = $this->sys_input;

            $regionalId = $prm["regionalId"];
            $query = "SELECT DISTINCT
                      M_BranchCode,
                      M_BranchName
                      FROM m_branch
                      WHERE M_BranchIsActive = 'Y'
                      AND M_BranchS_RegionalID = ?
                      ORDER BY M_BranchName ASC";
            $exec = $this->db->query($query, [$regionalId]);
            if ($exec) {
                $rows = $exec->result_array();
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select branch", $this->db);
                exit;
            }

            $result = array(
                "records" => $rows,
                "sql" => $this->db->last_query()
            );

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

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

            $prm = $this->sys_input;
            $userId = $this->sys_user["M_UserID"];

            $search = "";
            if (isset($prm['search'])) {
                $search = trim($prm["search"]);
                if ($search != "") {
                    $search = '%' . $prm['search'] . '%';
                } else {
                    $search = '%%';
                }
            }

            $regionalId = $prm['regionalId'];
            // $filterregional = "";
            // if (intval($regionalId) > 0) {
            //     $filterregional .= " AND S_RegionalID = {$regionalId}";
            // }

            $branchCode = $prm['branchCode'];
            $filterbranch = "";
            if ($branchCode != "") {
                $filterbranch .= " AND MapBank_BranchCode = '{$branchCode}'";
            }

            $sql = "SELECT 
                    MapBank_ID,
                    MapBank_BranchCode,
                    MapBank_NatBankID,
                    MapBank_NatBankCode,
                    MapBank_NatBankName,
                    MapBank_NatBankIsEDC,
                    MapBank_BankAccountNo,
                    MapBank_CoaID,
                    MapBank_CoaAccountNo,
                    MapBank_CoaDescription,
                    MapBank_EDC_CoaID,
                    MapBank_EDC_CoaAccountNo,
                    MapBank_EDC_CoaDescription,
                    MapBank_IsActive
                    FROM map_bank_coa
                    JOIN m_branch ON MapBank_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y'
                    JOIN s_regional ON M_BranchS_RegionalID = S_RegionalID AND S_RegionalIsActive = 'Y'
                    AND S_RegionalID = {$regionalId}
                    WHERE MapBank_IsActive = 'Y'
                    AND (MapBank_NatBankName LIKE '{$search}' OR MapBank_NatBankCode LIKE '{$search}' OR MapBank_BankAccountNo LIKE '{$search}')
                    $filterbranch
                    ";
            $sql_total = "SELECT count(*) as total FROM ($sql) as x";
            $qry_total = $this->db->query($sql_total, []);

            // print_r($this->db->last_query());
            // exit;

            $number_offset = 0;
            $number_limit = 10;

            if ($prm["current_page"] > 0) {
                $number_offset = ($prm["current_page"] - 1) * $number_limit;
            }

            $total_count = 0;
            $total_page = 0;
            if ($qry_total) {
                $total_count = $qry_total->result_array()[0]["total"];
                $total_page = ceil($total_count / $number_limit);
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select count bank coa count error", $this->db);;
                exit;
            }

            $sql_bank = $sql . " LIMIT $number_limit OFFSET $number_offset";
            $qry_bank = $this->db->query($sql_bank, []);
            if ($qry_bank) {
                $rows = $qry_bank->result_array();
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select bank coa count error", $this->db);;
                exit;
            }

            $result = array(
                "total_page" => $total_page,
                "total_filter" => $total_count,
                "records" => $rows
            );
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

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

            $prm = $this->sys_input;

            $search = $prm["search"];
            $search_name = '%' . $search . '%';
            $search_account = "$search%";

            $number_limit = 10;

            $sql = "SELECT
                    coaID,
                    coaAccountNo,
                    coaDescription,
                    coaSubDescription,
                    coaAccountType,
                    coaIsInput,
                    coaReportSchedule,
                    coaCurrencyCode,
                    coaCashFlowCategory,
                    CONCAT(coaAccountNo, ' - ', coaDescription) as accountNoDescription
                    FROM coa
                    WHERE coaIsActive = 'Y'
                    AND coaIsInput = 'Y'
                    AND (coaDescription LIKE '{$search_name}' OR coaAccountNo LIKE '{$search_account}')
                    ORDER BY coaAccountNo ASC
                    LIMIT ?";
            $qry = $this->db->query($sql, array($number_limit));
            if ($qry) {
                $rows = $qry->result_array();
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select coa error", $this->db);
                exit;
            }

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

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

            $prm = $this->sys_input;

            $search = $prm["search"];
            $search_name = '%' . $search . '%';
            $search_account = "$search%";

            $number_limit = 10;

            $sql = "SELECT
                    coaID,
                    coaAccountNo,
                    coaDescription,
                    coaSubDescription,
                    coaAccountType,
                    coaIsInput,
                    coaReportSchedule,
                    coaCurrencyCode,
                    coaCashFlowCategory,
                    CONCAT(coaAccountNo, ' - ', coaDescription) as accountNoDescription
                    FROM coa
                    WHERE coaIsActive = 'Y'
                    AND coaIsInput = 'Y'
                    AND (coaDescription LIKE '{$search_name}' OR coaAccountNo LIKE '{$search_account}')
                    ORDER BY coaAccountNo ASC
                    LIMIT ?";
            $qry = $this->db->query($sql, array($number_limit));
            if ($qry) {
                $rows = $qry->result_array();
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select coa error", $this->db);
                exit;
            }

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

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

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

            $isEdc = $prm["isEdc"];
            $coaBankId = $prm["coaBankId"];
            $coaBankAccountNo = $prm["coaBankAccountNo"];
            $coaBankDescription = $prm["coaBankDescription"];
            $edcCoaId = $prm["edcCoaId"];
            $edcCoaAccountNo = $prm["edcCoaAccountNo"];
            $edcCoaDescription = $prm["edcCoaDescription"];
            $mapBankId = $prm["mapBankId"];

            $sql = "UPDATE map_bank_coa SET 
                MapBank_NatBankIsEDC = ?,
                MapBank_CoaID = ?,
                MapBank_CoaAccountNo = ?,
                MapBank_CoaDescription = ?,
                MapBank_EDC_CoaID = ?,
                MapBank_EDC_CoaAccountNo = ?,
                MapBank_EDC_CoaDescription = ?,
                MapBank_LastUpdatedAt = NOW()
                WHERE MapBank_ID = ?";
            $qry = $this->db->query($sql, array(
                $isEdc,
                $coaBankId,
                $coaBankAccountNo,
                $coaBankDescription,
                $edcCoaId,
                $edcCoaAccountNo,
                $edcCoaDescription,
                $mapBankId
            ));

            if (!$qry) {
                $this->db->trans_rollback();
                $this->sys_error_db("update map bank coa error", $this->db);
                exit;
            }

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

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

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

            $mapBankId = $prm["mapBankId"];

            $sql = "UPDATE map_bank_coa SET 
                MapBank_IsActive = 'N',
                MapBank_LastUpdatedAt = NOW()
                WHERE MapBank_ID = ?";
            $qry = $this->db->query($sql, array(
                $mapBankId
            ));

            if (!$qry) {
                $this->db->trans_rollback();
                $this->sys_error_db("delete map bank coa error", $this->db);
                exit;
            }

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