<?php

class Journalfixedassetv2 extends MY_Controller
{
    var $db;
    public function index()
    {
        echo "PAYMENT VOUCHER API";
    }
    public function __construct()
    {
        parent::__construct();
    }

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

            $prm = $this->sys_input;

            $search = "";
            $number_limit = 10;
            $tot_count = 0;

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

            $sql = "SELECT
                periodeID AS id,
                periodeYear,
                periodeMonth,
                CONCAT(periodeYear, ' - ',periodeMonth) as yearandmonth,
                periodeName,
                CONCAT(DATE_FORMAT(periodeStartDate, '%d %M %Y'), ' - ', DATE_FORMAT(periodeEndDate, '%d %M %Y')) as periode
                FROM periode
                WHERE periodeIsActive = 'Y'
                AND periodeIsClosed = 'N'
                ORDER BY periodeMonth DESC";
            $qry = $this->db->query($sql, []);
            if (!$qry) {
                $this->sys_error_db("select period", $this->db);
                exit;
            }
            $rst = $qry->result_array();
            $this->sys_ok($rst);
        } 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;

            $periodeid = $prm["periodeid"];
            $xdate = $prm["xdate"];

            $user = $this->sys_user;
        $regionalID = $user['S_RegionalID'];
        $branchCode = $user['M_BranchCode'];

       /* if (isset($branchCode)) {
            $join_branch = " JOIN m_branch ON M_BranchCode = '{$branchCode}'
            JOIN s_regional ON S_RegionalID = '{$regionalID}'";
            $filter_branch = " AND Fa_ItemS_RegionalID = '{$regionalID}' AND Fa_ItemM_BranchCode = '{$branchCode}'";
        }else{
            $join_branch = " JOIN s_regional ON S_RegionalID = '{$regionalID}'
            LEFT JOIN m_branch ON M_BranchS_RegionalID = '{$regionalID}' AND Fa_ItemM_BranchCode = '{$branchCode}'";
            $filter_branch = " AND Fa_ItemS_RegionalID = '{$regionalID}'";
        }
            */
            $join_branch = " JOIN s_regional ON S_RegionalID = '{$regionalID}'";
        $filter_branch = " AND Fa_ItemS_RegionalID = '{$regionalID}'";

        $sql_confirm = "SELECT COUNT(*) as total
                        FROM (SELECT periodeID
                        FROM periode
                        WHERE periodeEndDate < (
                        SELECT periodeStartDate
                        FROM periode
                        WHERE periodeID = '{$periodeid}')
                        ORDER BY periodeEndDate DESC
                        LIMIT 1) a
                        JOIN fa_item_detail ON Fa_ItemDetailperiodeID = a.periodeID AND Fa_ItemDetailIsActive = 'Y'
                        ";
        $qry_confirm = $this->db->query($sql_confirm);
        //echo $this->db->last_query();
        if ($qry_confirm) {
            $totalConfirm = $qry_confirm->result_array()[0]["total"];
            if ($totalConfirm == 0){
                $hide = 'Y';
            } else {
                $hide = 'N';
            }
        }

            $sql = "SELECT
'{$hide}' as ishide,
Fa_ItemID,
Fa_ItemNote,
Fa_ItemNumber CodeFixedAsset,
M_ItemDesc NameFixedAsset,
Fa_ItemAcquisitionPrice AcquisitionPrice,
Fa_ItemDeprePerMonth,
CASE
        WHEN Fa_ItemDate BETWEEN periodeStartDate AND periodeEndDate THEN 1
        ELSE 0
    END AS pMonth,
IFNULL(Fa_ClassDepreCorp,0) DepreRateFixedAsset,
IFNULL(Fa_ClassDepreGov,0) DepreGovPercent,
0 depresiasi,
0 akumulasi,
0 nilai_saat_ini,
0 depresiasi_text,
0 akumulasi_text,
0 nilai_saat_ini_text,
Fa_ItemNetBookValue BookValue,
0 BookValue_text,
'' as ErrStatus,
'' as ErrMsg,
'' as detailtx,
Fa_ItemDetailID,
IFNULL(Fa_ItemDetailIsConfirm,'N') as Fa_ItemIsConfirm,
DATE_FORMAT(Fa_ItemDate, '%c') month_fa,
0 AcquisitionPrice_text,
1 total_month,
Fa_ItemBranchFaPercentID,
'' branchlists
FROM fa_item
JOIN m_item ON M_ItemID = Fa_ItemM_ItemID
JOIN fa_class ON Fa_ClassID = M_ItemFa_ClassID
LEFT JOIN fa_item_detail ON Fa_ItemDetailFa_ItemID = Fa_ItemID AND Fa_ItemDetailIsActive = 'Y' AND Fa_ItemDetailperiodeID = $periodeid
JOIN periode ON periodeID = $periodeid AND periodeIsActive = 'Y'
$join_branch
WHERE Fa_ItemIsActive = 'Y'
$filter_branch
AND (date(Fa_ItemDate) <= periodeStartDate OR date(Fa_ItemDate) <= periodeEndDate)
ORDER BY Fa_ItemID DESC";


            $sql_total = "SELECT count(*) as total FROM ($sql) as x";
            $qry_total = $this->db->query($sql_total);

            $number_offset = 0;
            $number_limit = 10;

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

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

            $sql_select = $sql . " LIMIT $number_limit OFFSET $number_offset";
            $qry = $this->db->query($sql_select);

            if ($qry) {
                $rows = $qry->result_array();
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select jurnal error", $this->db);
                exit;
            }

            foreach ($rows as $key => $value) {

                $sql = "SELECT periodeYear, periodeMonth FROM periode WHERE periodeID = ?";
                $date_now = $this->db->query($sql, [$periodeid])->row();

                $month = $date_now->periodeMonth;
                if($month == 1){
                    $year = $date_now->periodeYear - 1;
                    $month_before = 12 ;
                }else{
                    $year = $date_now->periodeYear;
                    $month_before = $month - 1 ;
                }

                $sql = "SELECT periodeID FROM periode WHERE periodeYear = '{$year}' AND periodeMonth = '{$month_before}'";
                $periode_before = $this->db->query($sql)->row()->periodeID;

                $total_month = $month - $value['month_fa']  + 1;
                $rows[$key]["total_month"] = $total_month;

                $sql = "SELECT Fa_ItemDetailFa_ItemID,
                Fa_ItemDetailperiodeID,
                Fa_ItemDetailDepre,
                Fa_ItemDetailAccum,
                Fa_ItemDetailCurrentValue,
                Fa_ItemDetailCurrentValue as Fa_ItemDetailBookValue
                FROM fa_item_detail
                JOIN fa_item ON Fa_ItemID = Fa_ItemDetailFa_ItemID
                WHERE Fa_ItemDetailFa_ItemID = {$value['Fa_ItemID']} AND
                Fa_ItemDetailperiodeID = $periode_before
                AND Fa_ItemDetailIsActive = 'Y'";
                $fa_detail = $this->db->query($sql)->row();


                $depre_amount = $value['Fa_ItemDeprePerMonth'];
                $rows[$key]["depresiasi"] = $depre_amount;
                $rows[$key]["depresiasi_text"] = number_format($depre_amount, 0, ',', '.');
                $sum_depre_before = $depre_amount;

                $akumulasi = $total_month * $sum_depre_before;
                $rows[$key]["akumulasi"] = $akumulasi;
                $rows[$key]["akumulasi_text"] = number_format($akumulasi, 0, ',', '.');
                $nilai_saat_ini = $value['AcquisitionPrice'] - $akumulasi;
                $rows[$key]["nilai_saat_ini"] = $nilai_saat_ini;
                $rows[$key]["nilai_saat_ini_text"] = number_format($nilai_saat_ini, 0, ',', '.');
                $rows[$key]["AcquisitionPrice_text"] = number_format($value['AcquisitionPrice'], 0, ',', '.');

                if (isset($fa_detail->Fa_ItemDetailBookValue)){
                    $Fa_ItemDetailBookValue = $fa_detail->Fa_ItemDetailBookValue;
                    $rows[$key]["BookValue"] = $Fa_ItemDetailBookValue;
                    $rows[$key]["BookValue_text"] = number_format($Fa_ItemDetailBookValue, 0, ',', '.');
                    }else{
                    $Fa_ItemDetailBookValue = $nilai_saat_ini + $depre_amount;
                    $rows[$key]["BookValue"] = $Fa_ItemDetailBookValue;
                    $rows[$key]["BookValue_text"] = number_format($Fa_ItemDetailBookValue, 0, ',', '.');
                    }
                    $rows[$key]['branchlists'] = $this->getdetail($value['Fa_ItemBranchFaPercentID'],$depre_amount);

            }

            $result = array(
                'total' => $totalPage,
                'totalfilter' => $totalCount,
                "records" => $rows
            );
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }
    function getdetail($Fa_ItemBranchFaPercentID,$depre_amount)
    {
            $sql = "SELECT BranchFaPercentDetailID,
            BranchFaPercentDetailBranchFaPercentID,
            BranchFaPercentDetailS_RegionalID,
            BranchFaPercentDetailAccountNumber,
            BranchFaPercentDetailM_BranchID,
            BranchFaPercentDetailValue,
            coaID,
            coaAccountNo,
            coaDescription,
            M_BranchName,
            (BranchFaPercentDetailValue / 100) * $depre_amount as totaldepre,
            0 totaldepretext
                FROM branch_fa_percent
                JOIN branch_fa_percent_detail ON BranchFaPercentID = BranchFaPercentDetailBranchFaPercentID AND BranchFaPercentIsActive = 'Y'
                    AND BranchFaPercentDetailIsActive = 'Y'
                    AND BranchFaPercentDetailBranchFaPercentID = ?
                JOIN coa
                ON BranchFaPercentDetailAccountNumber = coaAccountNo
                AND coaIsActive = 'Y'
                JOIN m_branch
                ON M_BranchID = BranchFaPercentDetailM_BranchID
                ";
        $query = $this->db->query($sql, [$Fa_ItemBranchFaPercentID]);
        if ($query) {
            $rows = $query->result_array();
            if($rows){
                foreach ($rows as $key => $value) {
                    $rows[$key]["totaldepretext"] = number_format($value['totaldepre'], 0, ',', '.');
                }
            }
            return $rows;

        } else {
            $this->sys_error_db("get branchlist", $this->db_onedev);
            exit;
        }

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

        $this->db_onedev->trans_begin();
        $userid = $this->sys_user['M_UserID'];

        $periodeid = $prm['periodeid'];

        foreach ($prm['details'] as $k => $v) {
            // Pastikan hanya proses yang belum dikonfirmasi
            if ($v['Fa_ItemIsConfirm'] == 'N') {
                // Masukkan data ke fa_item_detail
                $query = "INSERT INTO fa_item_detail
                    (Fa_ItemDetailFa_ItemID,
                    Fa_ItemDetailperiodeID,
                    Fa_ItemDetailBookValue,
                    Fa_ItemDetailDeprePerMonth,
                    Fa_ItemDetailDepre,
                    Fa_ItemDetailAccum,
                    Fa_ItemDetailCurrentValue,
                    Fa_ItemDetailIsConfirm,
                    Fa_ItemDetailConfirmDate,
                    Fa_ItemDetailConfirmUserID)
                    VALUES(?,?,?,?,?,?,?,?,now(),?)";
                $qry = $this->db_onedev->query($query, array(
                    $v['Fa_ItemID'],
                    $periodeid,
                    $v['BookValue'],
                    $v['Fa_ItemDeprePerMonth'],
                    $v['depresiasi'],
                    $v['akumulasi'],
                    $v['nilai_saat_ini'],
                    'Y',
                    $userid
                ));
                $last_qry = $this->db_onedev->last_query();
                if (!$qry) {
                    $this->db_onedev->trans_rollback();
                    $error = array(
                        "message" => $this->db_onedev->error()["message"],
                        "sql" => $last_qry
                    );
                    $this->sys_error_db($error, $this->db_onedev);
                    exit;
                }
                $last_id = $this->db_onedev->insert_id();

                // Insert jurnal pembelian
                $newData = [];
                $sqlData = "SELECT fa_item.*,
                    fa_item_detail.*,
                    M_BranchID,
                    M_BranchCode,
                    M_BranchName,
                    M_BranchS_RegionalID,
                    M_BranchCompanyID,
                    M_BranchCompanyName,
                    CONCAT('Jurnal Pembelian Fix Asset ', DATE_FORMAT(now(), '%d-%m-%Y')) xdescription,
                    '{$periodeid}' periodeid,
                    CONCAT('Jurnal Pembelian Fix Asset ', DATE_FORMAT(now(), '%d-%m-%Y'), ' cabang ',M_BranchName) title,
                    21 typeid,
                    '' detailjurnal,
                    ca.coaDescription as CoaBiayaDepresiasi,
                    cb.coaDescription as CoaAkumulasiDepresiasi,
                    Fa_ClassAccumDepreCostCoaID,
                    Fa_ItemFa_ClassAccumDepreCoaID,
                    bd.coaID as CoaBeliDebetID,
                    bd.coaDescription as CoaBeliDebetName,
                    bc.coaID as CoaBeliCreditID,
                    bc.coaDescription as CoaBeliCreditName
                    FROM fa_item_detail
                    JOIN fa_item ON Fa_ItemID = Fa_ItemDetailFa_ItemID
                    JOIN m_item ON M_ItemID = Fa_ItemM_ItemID
                    JOIN fa_class ON Fa_ClassID = M_ItemFa_ClassID
                    LEFT JOIN m_branch ON M_BranchCode = Fa_ItemM_BranchCode
                    LEFT JOIN m_branch_companydetail ON M_BranchCompanyDetailM_BranchCode = M_BranchCode AND M_BranchCompanyDetailIsActive = 'Y'
                    LEFT JOIN m_branch_company ON M_BranchCompanyID = M_BranchCompanyDetailM_BranchCompanyID AND M_BranchCompanyIsActive = 'Y'
                    JOIN coa ca ON ca.coaID = Fa_ClassAccumDepreCostCoaID
                    JOIN coa cb ON cb.coaID = Fa_ItemFa_ClassAccumDepreCoaID
                    LEFT JOIN coa bd ON bd.coaID = Fa_ItemFa_ClassCoaID
                    LEFT JOIN coa bc ON bc.coaID = Fa_ItemAcquisitionCoaID
                    WHERE Fa_ItemDetailID = {$last_id} AND Fa_ItemDetailIsActive = 'Y'";
                $qryData = $this->db_onedev->query($sqlData);
                $last_qry = $this->db_onedev->last_query();
                if (!$qryData) {
                    $this->db_onedev->trans_rollback();
                    $error = array(
                        "message" => $this->db_onedev->error()["message"],
                        "sql" => $last_qry
                    );
                    $this->sys_error_db($error, $this->db_onedev);
                    exit;
                }
                $newData = $qryData->result_array();
                
                if ($newData) {
                    foreach ($newData as $k_jurnal => $v_jurnal) {
                        $branchid = $v_jurnal["M_BranchID"];
                        $branchcompanyid = $v_jurnal["M_BranchCompanyID"];
                        $date = date('Y-m-d');
                        $description = $v_jurnal["xdescription"];
                        $regionalid = $v_jurnal["M_BranchS_RegionalID"];
                        $title = $v_jurnal["title"];
                        $typeid = $v_jurnal["typeid"];
                        $pvno = $v_jurnal["Fa_ItemNumber"];
                        $detailjurnal = $this->db_onedev->query("SELECT {$v_jurnal["CoaBeliDebetID"]} coaid,
                            '{$v_jurnal["CoaBeliDebetName"]}' xdescription,
                            {$v_jurnal["Fa_ItemDetailBookValue"]} debit,
                            0 credit
                            UNION
                            SELECT
                            {$v_jurnal["CoaBeliCreditID"]} coaid,
                            '{$v_jurnal["CoaBeliCreditName"]}' xdescription,
                            0 debit,
                            {$v_jurnal["Fa_ItemDetailBookValue"]} credit")->result_array();
                        $this->savejurnalbeli($branchid, $date, $description, $periodeid, $regionalid, $title, $typeid, $detailjurnal, $pvno, $branchcompanyid);
                    }
                }

                // Loop untuk branchlists
                // Data branchlists sudah ada di $v dari hasil fungsi search()
                foreach ($v['branchlists'] as $key => $value) {
                    $branchlistid = $value["BranchFaPercentDetailM_BranchID"];
                    $querybranchlist = "INSERT INTO fa_item_branch
                        (Fa_ItemBranchFa_ItemID,
                        Fa_ItemBranchFa_ItemDetailID,
                        Fa_ItemBranchM_BranchID,
                        Fa_ItemBranchperiodeID,
                        Fa_ItemBranchDeprePerMonth,
                        Fa_ItemBranchIsConfirm,
                        Fa_ItemBranchConfirmDate,
                        Fa_ItemBranchConfirmUserID,
                        Fa_ItemBranchUserID)
                        VALUES(?,?,?,?,?,?,now(),?,?)";
                    $qrybranchlist = $this->db_onedev->query($querybranchlist, array(
                        $v['Fa_ItemID'],
                        $last_id,
                        $branchlistid,
                        $periodeid,
                        $value['totaldepre'],
                        'Y',
                        $userid,
                        $userid
                    ));
                    $last_qry = $this->db_onedev->last_query();

                    if (!$qrybranchlist) {
                        $this->db_onedev->trans_rollback();
                        $error = array(
                            "message" => $this->db_onedev->error()["message"],
                            "sql" => $last_qry
                        );
                        $this->sys_error_db($error, $this->db_onedev);
                        exit;
                    }
                    $last_branchid = $this->db_onedev->insert_id();

                    // Jurnal untuk branch regional
                    $sqlDatabranchlist = "SELECT fa_item.*,
                        fa_item_detail.*,
                        fa_item_branch.*,
                        M_BranchID,
                        M_BranchCode,
                        M_BranchName,
                        M_BranchS_RegionalID,
                        M_BranchCompanyID,
                        M_BranchCompanyName,
                        CONCAT('Jurnal Depresiasi Fix Asset Cabang', DATE_FORMAT(now(), '%d-%m-%Y')) xdescription,
                        '{$periodeid}' periodeid,
                        CONCAT('Jurnal Depresiasi Fix Asset Cabang', DATE_FORMAT(now(), '%d-%m-%Y'), ' cabang ', M_BranchName) title,
                        21 typeid,
                        '' detailjurnal,
                        cb.coaID as CoaDebetID,
                        cb.coaDescription as CoaDebetName,
                        ca.coaID as CoaCreditID,
                        ca.coaDescription as CoaCreditName
                        FROM fa_item_branch
                        JOIN fa_item_detail ON Fa_ItemDetailID = Fa_ItemBranchFa_ItemDetailID AND Fa_ItemBranchIsActive = 'Y'
                        JOIN fa_item ON Fa_ItemID = Fa_ItemDetailFa_ItemID
                        JOIN m_item ON M_ItemID = Fa_ItemM_ItemID
                        JOIN fa_class ON Fa_ClassID = M_ItemFa_ClassID
                        LEFT JOIN m_branch ON M_BranchID = Fa_ItemBranchM_BranchID
                        LEFT JOIN m_branch_companydetail ON M_BranchCompanyDetailM_BranchCode = M_BranchCode AND M_BranchCompanyDetailIsActive = 'Y'
                        LEFT JOIN m_branch_company ON M_BranchCompanyID = M_BranchCompanyDetailM_BranchCompanyID AND M_BranchCompanyIsActive = 'Y'
                        JOIN branch_fa_percent ON BranchFaPercentID = Fa_ItemBranchFaPercentID
                        JOIN branch_fa_percent_detail ON BranchFaPercentDetailBranchFaPercentID = BranchFaPercentID AND BranchFaPercentDetailM_BranchID = Fa_ItemBranchM_BranchID AND BranchFaPercentDetailIsActive = 'Y'
                        JOIN coa ca ON ca.coaAccountNo = BranchFaPercentDetailAccountNumber
                        JOIN coa cb ON cb.coaID = Fa_ItemFa_ClassAccumDepreCoaID
                        WHERE Fa_ItemBranchFa_ItemDetailID = {$last_id} AND Fa_ItemBranchIsActive = 'Y' AND Fa_ItemBranchID = {$last_branchid}";

                    $qryDatabranchlist = $this->db_onedev->query($sqlDatabranchlist);
                    $last_qry = $this->db_onedev->last_query();

                    if (!$qryDatabranchlist) {
                        $this->db_onedev->trans_rollback();
                        $error = array(
                            "message" => $this->db_onedev->error()["message"],
                            "sql" => $last_qry
                        );
                        $this->sys_error_db($error, $this->db_onedev);
                        exit;
                    }
                    $newDatabranchlist = $qryDatabranchlist->result_array();

                    if ($newDatabranchlist) {
                        foreach ($newDatabranchlist as $key_jurnal_regional => $value_jurnal_regional) {
                            $branchid = $value_jurnal_regional["M_BranchID"];
                            $branchcompanyid = $value_jurnal_regional["M_BranchCompanyID"];
                            $date = date('Y-m-d');
                            $description = $value_jurnal_regional["xdescription"];
                            $regionalid = $value_jurnal_regional["M_BranchS_RegionalID"];
                            $title = $value_jurnal_regional["title"];
                            $typeid = $value_jurnal_regional["typeid"];
                            $pvno = $value_jurnal_regional["Fa_ItemNumber"];
                            $creditid = $value_jurnal_regional["CoaCreditID"];
                            $creditname = $value_jurnal_regional["CoaCreditName"];
                            $credittotal = $value_jurnal_regional["Fa_ItemDetailDeprePerMonth"];

                            $detailjurnal = $this->db_onedev->query("SELECT {$value_jurnal_regional["CoaDebetID"]} coaid,
                                '{$value_jurnal_regional["CoaDebetName"]}' xdescription,
                                {$value_jurnal_regional["Fa_ItemBranchDeprePerMonth"]} debit,
                                0 credit
                                
                                UNION SELECT {$value_jurnal_regional["CoaCreditID"]} coaid,
                                '{$value_jurnal_regional["CoaCreditName"]}' xdescription,
                                0 debit,
                                {$value_jurnal_regional["Fa_ItemBranchDeprePerMonth"]} credit
                                ")->result_array();
                            

                            $this->savejurnalbranch($branchid, $date, $description, $periodeid, $regionalid, $title, $typeid, $detailjurnal, $pvno, $branchcompanyid, $creditid, $creditname, $credittotal);
                        }
                    }
                }
                $newDataRegional = [];
                $sqlDataRegional = "SELECT fa_item.*,
                    fa_item_detail.*,
                    M_BranchID,
                    M_BranchCode,
                    M_BranchName,
                    M_BranchS_RegionalID,
                    M_BranchCompanyID,
                    M_BranchCompanyName,
                    CONCAT('Jurnal Depresiasi Fix Asset Regional', DATE_FORMAT(now(), '%d-%m-%Y')) xdescription,
                    '{$periodeid}' periodeid,
                    CONCAT('Jurnal Depresiasi Fix Asset Regional', DATE_FORMAT(now(), '%d-%m-%Y'), '  ',S_RegionalName) title,
                    21 typeid,
                    '' detailjurnal,
                    ca.coaDescription as CoaBiayaDepresiasi,
                    cb.coaDescription as CoaAkumulasiDepresiasi,
                    Fa_ClassAccumDepreCostCoaID,
                    Fa_ItemFa_ClassAccumDepreCoaID,
                    bd.coaID as CoaDebetID,
                    bd.coaDescription as CoaDebetName,
                    cb.coaID as CoaCreditID,
                    cb.coaDescription as CoaCreditName
                    FROM fa_item_detail
                    JOIN fa_item ON Fa_ItemID = Fa_ItemDetailFa_ItemID
                    JOIN m_item ON M_ItemID = Fa_ItemM_ItemID
                    JOIN fa_class ON Fa_ClassID = M_ItemFa_ClassID
                    LEFT JOIN m_branch ON M_BranchCode = Fa_ItemM_BranchCode
                    LEFT JOIN s_regional ON S_RegionalID = M_BranchS_RegionalID
                    LEFT JOIN m_branch_companydetail ON M_BranchCompanyDetailM_BranchCode = M_BranchCode AND M_BranchCompanyDetailIsActive = 'Y'
                    LEFT JOIN m_branch_company ON M_BranchCompanyID = M_BranchCompanyDetailM_BranchCompanyID AND M_BranchCompanyIsActive = 'Y'
                    JOIN coa ca ON ca.coaID = Fa_ClassAccumDepreCostCoaID
                    JOIN coa cb ON cb.coaID = Fa_ItemFa_ClassAccumDepreCoaID
                    LEFT JOIN coa bd ON bd.coaID = Fa_ItemFa_ClassCoaID
                    LEFT JOIN coa bc ON bc.coaID = Fa_ItemAcquisitionCoaID
                    WHERE Fa_ItemDetailID = {$last_id} AND Fa_ItemDetailIsActive = 'Y'";
                $qryDataRegional = $this->db_onedev->query($sqlDataRegional);
                $last_qry = $this->db_onedev->last_query();
                if (!$qryDataRegional) {
                    $this->db_onedev->trans_rollback();
                    $error = array(
                        "message" => $this->db_onedev->error()["message"],
                        "sql" => $last_qry
                    );
                    $this->sys_error_db($error, $this->db_onedev);
                    exit;
                }
                $newDataRegional = $qryDataRegional->result_array();
                
                if ($newDataRegional) {
                    foreach ($newDataRegional as $k_jurnal => $v_jurnal) {
                        $branchid = $v_jurnal["M_BranchID"];
                        $branchcompanyid = $v_jurnal["M_BranchCompanyID"];
                        $date = date('Y-m-d');
                        $description = $v_jurnal["xdescription"];
                        $regionalid = $v_jurnal["M_BranchS_RegionalID"];
                        $title = $v_jurnal["title"];
                        $typeid = $v_jurnal["typeid"];
                        $pvno = $v_jurnal["Fa_ItemNumber"];
                        $detailjurnal = $this->db_onedev->query("SELECT coaID coaid,
                            coaDescription xdescription,
                            Fa_ItemBranchDeprePerMonth debit,
                            0 credit
                            FROM fa_item_branch
                            JOIN fa_item_detail ON Fa_ItemDetailID = Fa_ItemBranchFa_ItemDetailID AND Fa_ItemBranchIsActive = 'Y'
                            JOIN fa_item ON Fa_ItemID = Fa_ItemDetailFa_ItemID
                            JOIN branch_fa_percent ON BranchFaPercentID = Fa_ItemBranchFaPercentID
                            JOIN branch_fa_percent_detail ON BranchFaPercentDetailBranchFaPercentID = BranchFaPercentID AND BranchFaPercentDetailM_BranchID = Fa_ItemBranchM_BranchID AND BranchFaPercentDetailIsActive = 'Y'
                            JOIN coa ON coaAccountNo = BranchFaPercentDetailAccountNumber
                            WHERE Fa_ItemBranchFa_ItemDetailID = {$last_id} AND Fa_ItemBranchIsActive = 'Y'
                            UNION ALL
                            SELECT
                            {$v_jurnal["CoaCreditID"]} coaid,
                            '{$v_jurnal["CoaCreditName"]}' xdescription,
                            0 debit,
                            {$v_jurnal["Fa_ItemDetailDeprePerMonth"]} credit")->result_array();
                        $this->savejurnalregional($branchid, $date, $description, $periodeid, $regionalid, $title, $typeid, $detailjurnal, $pvno, $branchcompanyid);
                    }
                }

            }
        }

        $this->db_onedev->trans_commit();
        $result = array("total" => 1);
        $this->sys_ok($result);
    } catch (Exception $exc) {
        $message = $exc->getMessage();
        $this->sys_error($message);
    }
}
    function savejurnalbeli($branchid, $date, $description, $periodeid, $regionalid, $title, $typeid, $detailjurnal, $pvno, $branchcompanyid)
    {
        try {
            if (! $this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

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

            $sql_branch = "SELECT
                    M_BranchID,
                    M_BranchCode,
                    M_BranchName
                    FROM m_branch
                    WHERE M_BranchIsActive = 'Y'
                    AND M_BranchID = ?";
            $qry_branch = $this->db->query($sql_branch, array($branchid));
            if ($qry_branch) {
                $branchcodex = $qry_branch->row()->M_BranchCode;
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select branch error", $this->db);
                exit;
            }

            $sql = "INSERT INTO jurnal(
                    jurnalM_BranchCompanyID,
                    JurnalS_RegionalID,
                    jurnalperiodeID,
                    jurnalNo,
                    jurnalTitle,
                    jurnalDescription,
                    jurnalDate,
                    jurnalJurnalTypeID,
                    jurnalIsActive,
                    jurnalCreated,
                    jurnalM_UserID
                    ) VALUES(?,?,?,`fn_numbering`('J'),?,?,?,?,'Y',NOW(),?)";
            $qry = $this->db->query($sql, array(
                $branchcompanyid,
                $regionalid,
                $periodeid,
                $title,
                $description,
                $date,
                $typeid,
                $userid
            ));
            $last_qry = $this->db->last_query();
            if (!$qry) {
                $this->db->trans_rollback();
                $error = array(
                    "message" => $this->db->error()["message"],
                    "sql" => $last_qry
                );
                $this->sys_error_db($error, $this->db);
                exit;
            }

            $last_id = $this->db->insert_id();

            foreach ($detailjurnal as $key => $value) {
                $sql_detail = "INSERT INTO jurnal_tx(
                                jurnalTxJurnalID,
                                jurnalTxCoaID,
                                jurnalTxDescription,
                                jurnalTxDebit,
                                jurnalTxCredit,
                                jurnalTxIsActive,
                                jurnalTxCreated,
                                jurnalTxM_UserID) VALUES(?,?,?,?,?,'Y',NOW(),?)";
                $qry_detail = $this->db->query($sql_detail, array(
                    $last_id,
                    $value["coaid"],
                    $value["xdescription"],
                    $value["debit"],
                    $value["credit"],
                    $userid
                ));
                $last_qry = $this->db->last_query();
                if (!$qry_detail) {
                    $this->db->trans_rollback();
                    $error = array(
                        "message" => $this->db->error()["message"],
                        "sql" => $last_qry
                    );
                    $this->sys_error_db($error, $this->db);
                    exit;
                }

                $tx_id = $this->db->insert_id();

                $sql = "INSERT INTO jurnal_addon
                (jurnalAddOnJurnalID,
                jurnalAddOnJurnalTxID,
                jurnalAddOnCode,
                jurnalAddOnValue,
                jurnalAddOnCreated,
                jurnalAddOnCreatedUserID,
                jurnalAddOnLastUpdatedUserID,
                jurnalAddOnLastUpdated)
                VALUES
                (?,
                ?,
                'JFA',
                ?,
                now(),
                ?,
                ?,
                now())";
                $qry = $this->db->query($sql, array(
                    $last_id,
                    $tx_id,
                    $pvno,
                    $userid,
                    $userid
                ));
                $last_qry = $this->db->last_query();
                if (!$qry) {
                    $this->db->trans_rollback();
                    $error = array(
                        "message" => $this->db->error()["message"],
                        "sql" => $last_qry
                    );
                    $this->sys_error_db($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 savejurnalregional($branchid, $date, $description, $periodeid, $regionalid, $title, $typeid, $detailjurnal, $pvno, $branchcompanyid)
    {
        try {
            if (! $this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

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

            $sql_branch = "SELECT
                    M_BranchID,
                    M_BranchCode,
                    M_BranchName
                    FROM m_branch
                    WHERE M_BranchIsActive = 'Y'
                    AND M_BranchID = ?";
            $qry_branch = $this->db->query($sql_branch, array($branchid));
            if ($qry_branch) {
                $branchcodex = $qry_branch->row()->M_BranchCode;
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select branch error", $this->db);
                exit;
            }

            $sql = "INSERT INTO jurnal(
                    jurnalM_BranchCompanyID,
                    JurnalS_RegionalID,
                    jurnalperiodeID,
                    jurnalNo,
                    jurnalTitle,
                    jurnalDescription,
                    jurnalDate,
                    jurnalJurnalTypeID,
                    jurnalIsActive,
                    jurnalCreated,
                    jurnalM_UserID
                    ) VALUES(?,?,?,`fn_numbering`('J'),?,?,?,?,'Y',NOW(),?)";
            $qry = $this->db->query($sql, array(
                $branchcompanyid,
                $regionalid,
                $periodeid,
                $title,
                $description,
                $date,
                $typeid,
                $userid
            ));
            $last_qry = $this->db->last_query();
            if (!$qry) {
                $this->db->trans_rollback();
                $error = array(
                    "message" => $this->db->error()["message"],
                    "sql" => $last_qry
                );
                $this->sys_error_db($error, $this->db);
                exit;
            }

            $last_id = $this->db->insert_id();
            
            foreach ($detailjurnal as $key => $value) {
                $sql_detail = "INSERT INTO jurnal_tx(
                                jurnalTxJurnalID,
                                jurnalTxCoaID,
                                jurnalTxDescription,
                                jurnalTxDebit,
                                jurnalTxCredit,
                                jurnalTxIsActive,
                                jurnalTxCreated,
                                jurnalTxM_UserID) VALUES(?,?,?,?,?,'Y',NOW(),?)";
                $qry_detail = $this->db->query($sql_detail, array(
                    $last_id,
                    $value["coaid"],
                    $value["xdescription"],
                    $value["debit"],
                    $value["credit"],
                    $userid
                ));
                $last_qry = $this->db->last_query();
                if (!$qry_detail) {
                    $this->db->trans_rollback();
                    $error = array(
                        "message" => $this->db->error()["message"],
                        "sql" => $last_qry
                    );
                    $this->sys_error_db($error, $this->db);
                    exit;
                }

                $tx_id = $this->db->insert_id();

                $sql = "INSERT INTO jurnal_addon
                (jurnalAddOnJurnalID,
                jurnalAddOnJurnalTxID,
                jurnalAddOnCode,
                jurnalAddOnValue,
                jurnalAddOnCreated,
                jurnalAddOnCreatedUserID,
                jurnalAddOnLastUpdatedUserID,
                jurnalAddOnLastUpdated)
                VALUES
                (?,
                ?,
                'JFA',
                ?,
                now(),
                ?,
                ?,
                now())";
                $qry = $this->db->query($sql, array(
                    $last_id,
                    $tx_id,
                    $pvno,
                    $userid,
                    $userid
                ));
                $last_qry = $this->db->last_query();
                if (!$qry) {
                    $this->db->trans_rollback();
                    $error = array(
                        "message" => $this->db->error()["message"],
                        "sql" => $last_qry
                    );
                    $this->sys_error_db($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 savejurnalbranch($branchid, $date, $description, $periodeid, $regionalid, $title, $typeid, $detailjurnal, $pvno, $branchcompanyid,$creditid,$creditname,$credittotal)
    {
        try {
            if (! $this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

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

            $sql_branch = "SELECT
                    M_BranchID,
                    M_BranchCode,
                    M_BranchName
                    FROM m_branch
                    WHERE M_BranchIsActive = 'Y'
                    AND M_BranchID = ?";
            $qry_branch = $this->db->query($sql_branch, array($branchid));
            if ($qry_branch) {
                $branchcodex = $qry_branch->row()->M_BranchCode;
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select branch error", $this->db);
                exit;
            }

            $sql = "INSERT INTO jurnal(
                    jurnalM_BranchCompanyID,
                    JurnalS_RegionalID,
                    jurnalM_BranchCode,
                    jurnalperiodeID,
                    jurnalNo,
                    jurnalTitle,
                    jurnalDescription,
                    jurnalDate,
                    jurnalJurnalTypeID,
                    jurnalIsActive,
                    jurnalCreated,
                    jurnalM_UserID
                    ) VALUES(?,?,?,?,`fn_numbering`('J'),?,?,?,?,'Y',NOW(),?)";
            $qry = $this->db->query($sql, array(
                $branchcompanyid,
                $regionalid,
                $branchcodex,
                $periodeid,
                $title,
                $description,
                $date,
                $typeid,
                $userid
            ));
            $last_qry = $this->db->last_query();
            if (!$qry) {
                $this->db->trans_rollback();
                $error = array(
                    "message" => $this->db->error()["message"],
                    "sql" => $last_qry
                );
                $this->sys_error_db($error, $this->db);
                exit;
            }

            $last_id = $this->db->insert_id();
            
            foreach ($detailjurnal as $key => $value) {
                $sql_detail = "INSERT INTO jurnal_tx(
                                jurnalTxJurnalID,
                                jurnalTxCoaID,
                                jurnalTxDescription,
                                jurnalTxDebit,
                                jurnalTxCredit,
                                jurnalTxIsActive,
                                jurnalTxCreated,
                                jurnalTxM_UserID) VALUES(?,?,?,?,?,'Y',NOW(),?)";
                $qry_detail = $this->db->query($sql_detail, array(
                    $last_id,
                    $value["coaid"],
                    $value["xdescription"],
                    $value["debit"],
                    $value["credit"],
                    $userid
                ));
                $last_qry = $this->db->last_query();
                if (!$qry_detail) {
                    $this->db->trans_rollback();
                    $error = array(
                        "message" => $this->db->error()["message"],
                        "sql" => $last_qry
                    );
                    $this->sys_error_db($error, $this->db);
                    exit;
                }

                $tx_id = $this->db->insert_id();

                $sql = "INSERT INTO jurnal_addon
                (jurnalAddOnJurnalID,
                jurnalAddOnJurnalTxID,
                jurnalAddOnCode,
                jurnalAddOnValue,
                jurnalAddOnCreated,
                jurnalAddOnCreatedUserID,
                jurnalAddOnLastUpdatedUserID,
                jurnalAddOnLastUpdated)
                VALUES
                (?,
                ?,
                'JFA',
                ?,
                now(),
                ?,
                ?,
                now())";
                $qry = $this->db->query($sql, array(
                    $last_id,
                    $tx_id,
                    $pvno,
                    $userid,
                    $userid
                ));
                $last_qry = $this->db->last_query();
                if (!$qry) {
                    $this->db->trans_rollback();
                    $error = array(
                        "message" => $this->db->error()["message"],
                        "sql" => $last_qry
                    );
                    $this->sys_error_db($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);
        }
    }
}