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

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

    function getRegionalFilter()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
            }
            $prm = $this->sys_input;
            $search = "";
            if (isset($prm['search'])) {
                $search = trim($prm["search"]);
                if ($search != "") {
                    $search = '%' . $prm['search'] . '%';
                } else {
                    $search = '%%';
                }
            }

            $sql = "SELECT * FROM (
                        SELECT '0' AS S_RegionalID, 'Kantor Pusat' AS S_RegionalName
                        UNION
                        SELECT S_RegionalID, S_RegionalName
                        FROM s_regional
                        WHERE S_RegionalIsActive = 'Y'
                    ) AS x
                    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 getRegional()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
            }
            $prm = $this->sys_input;
            $search = "";
            if (isset($prm['search'])) {
                $search = trim($prm["search"]);
                if ($search != "") {
                    $search = '%' . $prm['search'] . '%';
                } else {
                    $search = '%%';
                }
            }

            $sql = "SELECT * FROM (
                        SELECT '0' AS S_RegionalID, 'Kantor Pusat' AS S_RegionalName
                        UNION
                        SELECT S_RegionalID, S_RegionalName
                        FROM s_regional
                        WHERE S_RegionalIsActive = 'Y'
                    ) AS x
                    WHERE S_RegionalName LIKE '{$search}'
                    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 getBranchFilter()
    {
        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'];
            $branchCode = $prm['branchCode'];

            $filter_regional = "";
            $join_reg_pusat = "";
            $join_regional = "";

            // jika regionalid 0 maka kantor pusat
            if ($regionalId === 0 || $regionalId === "0") {
                $filter_regional .= " AND Map_RkCabang_SRegionalID = {$regionalId}";
                $join_reg_pusat .= " LEFT JOIN s_regional ON Map_RkCabang_SRegionalID = S_RegionalID AND S_RegionalIsActive = 'Y'
                    LEFT JOIN m_branch ON Map_RkCabang_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y'";
            }

            // jika regionalid > 0 maka filter berdasarkan regional
            if (intval($regionalId) > 0) {
                $filter_regional .= " AND Map_RkCabang_SRegionalID = {$regionalId}";
                $join_regional .= " JOIN s_regional ON Map_RkCabang_SRegionalID = S_RegionalID AND S_RegionalIsActive = 'Y'
                    LEFT JOIN m_branch ON Map_RkCabang_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y'";
            }

            // untuk load listing pada saat buka master rk
            if ($regionalId === "") {
                $join_regional .= " LEFT JOIN s_regional ON Map_RkCabang_SRegionalID = S_RegionalID AND S_RegionalIsActive = 'Y'
                LEFT JOIN m_branch ON Map_RkCabang_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y'";
            }

            $filter_branch = "";
            // filter branch
            if ($branchCode != "") {
                $filter_branch .= " AND Map_RkCabang_BranchCode = '{$branchCode}'";
            }

            $sql = "SELECT 
                    Map_RkCabang_ID,
                    Map_RkCabang_Rk_TypeID,
                    Map_RkCabang_SRegionalID,
                    Map_RkCabang_BranchCode,
                    Map_RkCabang_CoaID,
                    Map_RkCabang_CoaAccountNo,
                    Map_RkCabang_CoaDescription,
                    Rk_TypeID,
                    Rk_TypeCode,
                    Rk_TypeName,
                    S_RegionalID,
                    S_RegionalName,
                    M_BranchID,
                    M_BranchCode,
                    M_BranchName
                    FROM map_rk_cabang
                    JOIN rk_type ON Map_RkCabang_Rk_TypeID = Rk_TypeID AND Rk_TypeIsActive = 'Y'
                    $join_reg_pusat
                    $join_regional
                    WHERE Map_RkCabang_IsActive = 'Y'
                    $filter_regional
                    $filter_branch
                    AND (Map_RkCabang_CoaAccountNo LIKE '{$search}' OR Map_RkCabang_CoaDescription LIKE '{$search}')
                    ORDER BY Map_RkCabang_ID DESC
                    ";
            $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;
            }

            foreach ($rows as $key => $value) {
                if (intval($value["Map_RkCabang_SRegionalID"]) === 0) {
                    $rows[$key]["S_RegionalID"] = "0";
                    $rows[$key]["S_RegionalName"] = "Kantor Pusat";
                }
            }

            $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 getType()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
            }
            $prm = $this->sys_input;

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

            $sql = "SELECT 
                    Rk_TypeID,
                    Rk_TypeCode,
                    Rk_TypeName
                    FROM rk_type
                    WHERE Rk_TypeIsActive = 'Y'
                    AND (Rk_TypeName LIKE ?)";
            $qry = $this->db->query($sql, array(
                $search
            ));
            if ($qry) {
                $rows = $qry->result_array();
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select type error", $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 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));

            // echo $this->db->last_query();
            // exit;
            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 saveRkCabang()
    {
        try {
            if (! $this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

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

            $rkCabangTypeId = $prm["rkCabangTypeId"];
            $rkCabangRegionalId = $prm["rkCabangRegionalId"];
            $rkCabangBranchCode = $prm["rkCabangBranchCode"];
            $rkCabangCoaId = $prm["rkCabangCoaId"];
            $rkCabangCoaAccountNo = $prm["rkCabangCoaAccountNo"];
            $rkCabangCoaDescription = $prm["rkCabangCoaDescription"];

            $sql = "INSERT INTO map_rk_cabang(
                    Map_RkCabang_Rk_TypeID,
                    Map_RkCabang_SRegionalID,
                    Map_RkCabang_BranchCode,
                    Map_RkCabang_CoaID,
                    Map_RkCabang_CoaAccountNo,
                    Map_RkCabang_CoaDescription,
                    Map_RkCabang_IsActive,
                    Map_RkCabang_CreatedAt) VALUES(?,?,?,?,?,?,'Y',NOW())";
            $exec = $this->db->query($sql, [
                $rkCabangTypeId,
                $rkCabangRegionalId,
                $rkCabangBranchCode,
                $rkCabangCoaId,
                $rkCabangCoaAccountNo,
                $rkCabangCoaDescription
            ]);

            if (!$exec) {
                $this->db->trans_rollback();
                $this->sys_error_db("map rk cabang insert error", $this->db);
                exit;
            }

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

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

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

            $rkCabangTypeId = $prm["rkCabangTypeId"];
            $rkCabangRegionalId = $prm["rkCabangRegionalId"];
            $rkCabangBranchCode = $prm["rkCabangBranchCode"];
            $rkCabangCoaId = $prm["rkCabangCoaId"];
            $rkCabangCoaAccountNo = $prm["rkCabangCoaAccountNo"];
            $rkCabangCoaDescription = $prm["rkCabangCoaDescription"];
            $rkCabangId = $prm["rkCabangId"];

            $sql = "UPDATE map_rk_cabang SET
                    Map_RkCabang_Rk_TypeID = ?,
                    Map_RkCabang_SRegionalID = ?,
                    Map_RkCabang_BranchCode = ?,
                    Map_RkCabang_CoaID = ?,
                    Map_RkCabang_CoaAccountNo = ?,
                    Map_RkCabang_CoaDescription = ?,
                    Map_RkCabang_LastUpdatedAt= NOW()
                    WHERE Map_RkCabang_ID = ?";
            $qry = $this->db->query($sql, array(
                $rkCabangTypeId,
                $rkCabangRegionalId,
                $rkCabangBranchCode,
                $rkCabangCoaId,
                $rkCabangCoaAccountNo,
                $rkCabangCoaDescription,
                $rkCabangId
            ));

            if (!$qry) {
                $this->db->trans_rollback();
                $this->sys_error_db("update rk cabang 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 deleteRkCabang()
    {
        try {
            if (! $this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

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

            $rkCabangId = $prm["rkCabangId"];

            $sql = "UPDATE map_rk_cabang SET 
                Map_RkCabang_IsActive = 'N',
                Map_RkCabang_LastUpdatedAt = NOW()
                WHERE Map_RkCabang_ID = ?";
            $qry = $this->db->query($sql, array(
                $rkCabangId
            ));

            if (!$qry) {
                $this->db->trans_rollback();
                $this->sys_error_db("delete rk cabang 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);
        }
    }
}
