<?php

class Jurnalsendreg extends MY_Controller
{
    var $db;
    public function index()
    {
        echo "COA API";
        // $cek = $this->db->query("select database() as current_db")->result();
        // print_r($cek);
    }
    public function __construct()
    {
        parent::__construct();
    }
    function searchPeriode()
    {
        if (! $this->isLogin) {
            $this->sys_error("Invalid Token");
            exit;
        }
        $prm = $this->sys_input;
        $search = '%' . $prm['search'] . '%';
        $sql = "SELECT 
                CONCAT(periodeYear, ' - ', periodeName) as display,
                periode.* 
                FROM periode
                WHERE periodeIsActive = 'Y'
                AND periodeIsClosed = 'N'
                AND CONCAT(periodeYear, ' - ', periodeName) LIKE ?
                LIMIT 70
                ";
        $qry = $this->db->query($sql, [$search]);
        if (!$qry) {
            $this->sys_error_db("Error get coa", $this->db);
            exit;
        }
        $data = $qry->result_array();
        $this->sys_ok($data);
    }
    function getBranch()
    {
        if (! $this->isLogin) {
            $this->sys_error("Invalid Token");
            exit;
        }
        $prm = $this->sys_input;
        $sql = "SELECT 
                M_BranchID as branchID,
                M_BranchS_RegionalID as branchRegionalID,
                M_BranchCode as branchCode ,
                M_BranchName as branchName,
                M_BranchCompanyDetailM_BranchCompanyID branchCompanyID
                FROM m_branch
                JOIN m_branch_companydetail
                ON M_BranchCode  = M_BranchCompanyDetailM_BranchCode
                WHERE M_BranchS_RegionalID =  ?
                AND M_BranchCompanyDetailIsActive = 'Y'
                AND M_BranchCompanyDetailM_BranchCompanyID = ?
                AND M_BranchIsActive = 'Y'";
        $qry = $this->db->query($sql, array($prm['regional'], $prm['company']));

        if (!$qry) {
            // $this->db->trans_rollback();
            $this->sys_error_db("Error get branch");
            exit;
        }
        $data = $qry->result_array();
        $this->sys_ok($data);
    }
    function getJurnalType()
    {
        if (! $this->isLogin) {
            $this->sys_error("Invalid Token");
            exit;
        }
        $prm = $this->sys_input;
        $sql = "SELECT * FROM jurnal_type WHERE JurnalTypeIsActive = 'Y'
                ";
        $qry = $this->db->query($sql, []);
        if (!$qry) {
            $this->sys_error_db("Error truncate", $this->db);
            exit;
        }
        $default = array();
        $data = $qry->result_array();
        foreach ($data as $key => $value) {
            if ($value['JurnalTypeCode'] == 'SENDGOODR') {
                $default = $value;
            }
        }
        $this->sys_ok([
            "records" => $data,
            "default" => $default
        ]);
    }
    function searchCoa()
    {
        if (! $this->isLogin) {
            $this->sys_error("Invalid Token");
            exit;
        }
        $prm = $this->sys_input;
        $search = '%' . $prm['search'] . '%';

        $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 70
                 
                ";
        $qry = $this->db->query($sql, [$search]);
        if (!$qry) {
            $this->sys_error_db("Error get coa", $this->db);
            exit;
        }
        $data = $qry->result_array();
        $this->sys_ok($data);
    }
    function saveJurnal()
    {
        $this->db->trans_begin();
        // $this->db->trans_rollback();
        // $this->db->trans_commit();

        if (! $this->isLogin) {
            $this->sys_error("Invalid Token");
            exit;
        }
        $prm = $this->sys_input;
        $detail = $prm['detail'];
        $jurnalRegional = $prm['jurnalRegional'];
        $sallary = $prm['sallary'];
        $user = $this->sys_user;
        $userid = $user["M_UserID"];
        $kreditTotal = 0;
        $debetTotal = 0;
        foreach ($detail as $i => $value) {
            if ($value['type'] == 'D') {
                $debetTotal = $debetTotal + doubleval($value['debet']);
            } else if ($value['type'] == 'K') {
                $kreditTotal = $kreditTotal + doubleval($value['kredit']);
            }
            # code...
        }
        if ($debetTotal != $kreditTotal) {
            $this->sys_error("Jumlah debet dan kredit secara total tidak balance" . ", debet " . strval($debetTotal) . " ,Kredit " . strval($kreditTotal));
            exit;
        }
        //insert jurnal regional
        $sql = "SELECT `fn_numbering`('PBR') as number";
        $qry = $this->db->query($sql, array());

        if (!$qry) {
            $this->db->trans_rollback();
            $this->sys_error_db("Error get number");
            exit;
        }
        $numberingCounter = $qry->row_array()['number'];
        $currentMonth = date('m'); // Mendapatkan bulan saat ini dalam format angka dua digit
        $currentYear = date('Y'); // Mendapatkan tahun saat ini


        $numbering = 'PBR/' . $currentYear . "/" . $currentMonth . "/" . strval($numberingCounter);

        $sql = "INSERT INTO jurnal (
                        jurnalM_BranchCompanyID,
                        JurnalS_RegionalID,
                        jurnalM_BranchCode,
                        jurnalperiodeID,
                        jurnalNo,
                        jurnalTitle,
                        jurnalDescription,
                        jurnalDate,
                        jurnalJurnalTypeID,
                        jurnalM_UserID)
                        VALUES(?,?,?,?,?,?,?,?,?,?)";
        $qry = $this->db->query($sql, array(
            $user['M_BranchCompanyID'],
            $user['S_RegionalID'],
            '',
            $prm['periodeID'],
            $numbering,
            $prm['title'],
            $prm['description'],
            $prm['date'],
            $prm['jurnalTypeID'],
            $userid
        ));
        if (!$qry) {
            $this->db->trans_rollback();
            $this->sys_error_db("Error insert jurnal");
            exit;
        }
        $insertedJurnalRegID = $this->db->insert_id();
        $sql = "INSERT INTO jurnal_addon(
                        jurnalAddOnJurnalID,
                        jurnalAddOnCode,
                        jurnalAddOnValue,
                        jurnalAddOnCreatedUserID)
                        VALUES({$insertedJurnalRegID},'SENDGOODRDST','{$prm['branchCode']}',{$userid});";
        $qry = $this->db->query($sql, []);
        if (!$qry) {
            $this->db->trans_rollback();
            $this->sys_error_db("Error insert jurnal gaji addon regional");
            exit;
        }
        foreach ($detail as $i => $value) {
            $sql = 'INSERT INTO jurnal_tx(
                        jurnalTxJurnalID,
                        jurnalTxCoaID,
                        jurnalTxDescription,
                        jurnalTxDebit,
                        jurnalTxCredit,
                        jurnalTxM_UserID)
                        VALUES(?,?,?,?,?,?)';
            $qry = $this->db->query($sql, array(
                $insertedJurnalRegID,
                $value['coaID'],
                $value['coaName'],
                $value['debet'],
                $value['kredit'],
                $userid
            ));
            if (!$qry) {
                $this->db->trans_rollback();
                $this->sys_error_db("Error insert jurnal tx regional");
                exit;
            }
        }
        $this->db->trans_commit();
        $this->sys_ok("Success");
    }


    function getDetail()
    {
        if (! $this->isLogin) {
            $this->sys_error("Invalid Token");
            exit;
        }
        $prm = $this->sys_input;
        $id =  $prm['id'];
        $user = $this->sys_user;

        $sql = "SELECT 
                    jurnal.*,
                    M_BranchID  as branchID,
                    M_BranchName as branchName,
                    M_branchCode as branchCode
                FROM jurnal
                JOIN jurnal_addon
                ON jurnalID = jurnalAddOnJurnalID
                AND jurnalAddOnCode = 'SENDGOODRDST' 
                JOIN m_branch 
                ON jurnalAddOnValue = M_BranchCode
                AND M_BranchIsActive = 'Y'
                WHERE jurnalID = ?";
        $qry = $this->db->query($sql, array(
            $id
        ));
        if (!$qry) {
            // $this->db->trans_rollback();
            $this->sys_error_db("error get jurnal");
            exit;
        }
        $jurnal = $qry->row_array();
        $isEdit = 'Y';
        if ($jurnal['jurnalIsPosted'] === 'Y') {
            $isEdit = 'N';
        }
        $destination = [
            "branchID" => $jurnal['branchID'],
            "branchName" => $jurnal['branchName'],
            "branchCode" => $jurnal['branchCode'],
        ];
        $date = $jurnal['jurnalDate'];
        $title = $jurnal['jurnalTitle'];
        $description = $jurnal['jurnalDescription'];
        $jurnalDetail = [];

        $sql = "SELECT 
                CONCAT(periodeYear, ' - ', periodeName) as display,
                periode.* 
                FROM periode
                WHERE periodeIsActive = 'Y'
                AND periodeID = ?
                LIMIT 70
                ";
        $qry = $this->db->query($sql, [$jurnal['jurnalperiodeID']]);
        if (!$qry) {
            $this->sys_error_db("Error get coa", $this->db);
            exit;
        }
        $jurnalPeriode = $qry->row_array();
        $sql = "SELECT
                    jurnalTxID as id,
                    coaDescription as description,
                    jurnalTxDebit as debet,
                    jurnalTxCredit as kredit,
                    CASE 
                        WHEN jurnalTxDebit > 0 THEN 'D'
                        WHEN jurnalTxCredit > 0 THEN 'K'
                        else ''
                    END as type,
                    'Y' as dataType,
                    coaID,
                    coaDescription as coaName,
                    coaAccountNo as coaNo,
                    CONCAT(coaAccountNo, ' - ' ,coaDescription) as display
                    FROM jurnal_tx
                    JOIN coa
                    ON jurnalTxCoaID = coaID
                    AND jurnalTxJurnalID  = ?
                    AND jurnalTxIsActive = 'Y'
                    ";
        $qry = $this->db->query($sql, [$id]);
        if (!$qry) {
            $this->sys_error_db("Error get jurnal tx");
            exit;
        }
        $jurnalDetail = $qry->result_array();
        $result = array(
            "date" => $date,
            "isEdit" => $isEdit,
            "jurnal" => $jurnal,
            "destination" => $destination,
            "periode" => $jurnalPeriode,
            "title" => $title,
            "description" => $description,
            "jurnalDetail" => $jurnalDetail,

        );
        $this->sys_ok($result);
    }

    function editJurnal()
    {
        $this->db->trans_begin();
        // $this->db->trans_rollback();
        // $this->db->trans_commit();

        if (! $this->isLogin) {
            $this->sys_error("Invalid Token");
            exit;
        }
        $prm = $this->sys_input;
        $detail = $prm['detail'];
        $id = $prm['id'];

        $user = $this->sys_user;
        $userid = $user["M_UserID"];
        $kreditTotal = 0;
        $debetTotal = 0;

        $sql = "SELECT * 
                FROM jurnal
                WHERE jurnalID = ?";
        $qry = $this->db->query($sql, array(
            $id
        ));
        if (!$qry) {
            // $this->db->trans_rollback();
            $this->sys_error_db("Error cek jurnal jurnal");
            exit;
        }
        $cekJurnal = $qry->row_array();
        if ($cekJurnal['jurnalIsPosted'] == 'Y') {
            $this->sys_error('Jurnal sudah di post tidak bisa di ubah');
            exit;
        }

        foreach ($detail as $i => $value) {
            if ($value['type'] == 'D') {
                $debetTotal = $debetTotal + doubleval($value['debet']);
            } else if ($value['type'] == 'K') {
                $kreditTotal = $kreditTotal + doubleval($value['kredit']);
            }
            # code...
        }
        if ($debetTotal != $kreditTotal) {
            $this->sys_error("Jumlah debet dan kredit secara total tidak balance" . ", debet " . strval($debetTotal) . " ,Kredit " . strval($kreditTotal));
            exit;
        }


        $sql = "UPDATE jurnal SET 
                        jurnalperiodeID = ?,
                        jurnalTitle = ?,
                        jurnalDescription = ?,
                        jurnalDate = ?,
                        jurnalM_UserID = ?,
                        jurnalLastUpdated = NOW()
                        WHERE jurnalID = ?";
        $qry = $this->db->query($sql, array(
            $prm['periodeID'],
            $prm['title'],
            $prm['description'],
            $prm['date'],
            $userid,
            $id
        ));
        if (!$qry) {
            $this->db->trans_rollback();
            $this->sys_error_db("Error insert jurnal");
            exit;
        }

        $sql = "UPDATE jurnal_addon SET 
                        jurnalAddOnValue  = ?,
                        jurnalAddOnLastUpdatedUserID = ?,
                        jurnalAddOnLastUpdated = NOW()
                        WHERE jurnalAddOnJurnalID = ?
                        AND jurnalAddOnCode = 'SENDGOODRDST'
                        ";
        $qry = $this->db->query($sql, [$prm['branchCode'], $userid, $id]);
        if (!$qry) {
            $this->db->trans_rollback();
            $this->sys_error_db("Error insert jurnal addon regional");
            exit;
        }

        $sql = " UPDATE jurnal_tx SET jurnalTxIsActive = 'N' WHERE jurnalTxJurnalID = ? ";
        $qry = $this->db->query($sql, array(
            $id
        ));
        if (!$qry) {
            $this->db->trans_rollback();
            $this->sys_error_db("Error jurnal tx regional");
            exit;
        }

        foreach ($detail as $i => $value) {
            if ($value['dataType'] == 'N') {
                $sql = 'INSERT INTO jurnal_tx(
                            jurnalTxJurnalID,
                            jurnalTxCoaID,
                            jurnalTxDescription,
                            jurnalTxDebit,
                            jurnalTxCredit,
                            jurnalTxM_UserID)
                            VALUES(?,?,?,?,?,?)';
                $qry = $this->db->query($sql, array(
                    $id,
                    $value['coaID'],
                    $value['coaName'],
                    $value['debet'],
                    $value['kredit'],
                    $userid
                ));
                if (!$qry) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("Error insert jurnal tx regional");
                    exit;
                }
            } else {
                $sql = "UPDATE jurnal_tx SET 
                            jurnalTxCoaID = ?,
                            jurnalTxDescription = ?,
                            jurnalTxDebit = ?,
                            jurnalTxCredit = ?,
                            jurnalTxM_UserID = ?,
                            jurnalTxIsActive = 'Y',
                            jurnalTxLastUpdated = NOW()
                            WHERE jurnalTxID = ?";
                $qry = $this->db->query($sql, array(
                    $value['coaID'],
                    $value['coaName'],
                    $value['debet'],
                    $value['kredit'],
                    $userid,
                    $value['id']
                ));
                if (!$qry) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("Error insert jurnal tx regional");
                    exit;
                }
            }
        }
        $this->db->trans_commit();
        $this->sys_ok("Success");
    }

    function deleteJurnal()
    {
        $this->db->trans_begin();
        if (! $this->isLogin) {
            $this->sys_error("Invalid Token");
            exit;
        }
        $prm = $this->sys_input;
        $detail = $prm['detail'];
        $id = $prm['id'];

        $sql = "SELECT * 
                FROM jurnal
                WHERE jurnalID = ?";
        $qry = $this->db->query($sql, array(
            $id
        ));
        if (!$qry) {
            // $this->db->trans_rollback();
            $this->sys_error_db("Error cek jurnal jurnal");
            exit;
        }
        $cekJurnal = $qry->row_array();
        if ($cekJurnal['jurnalIsPosted'] == 'Y') {
            $this->sys_error('Jurnal sudah di post tidak bisa di hapus');
            exit;
        }

        $user = $this->sys_user;
        $userid = $user["M_UserID"];
        $sql = "UPDATE jurnal
                SET jurnalIsActive = 'N',
                jurnalM_UserID = ?
                WHERE 
                jurnalID  =  ?";
        $qry = $this->db->query($sql, array($userid, $id));
        if (!$qry) {
            $this->sys_error_db("Error delet jurnal gaji");
            $this->db->trans_rollback();
            exit;
        }
        $sql = "UPDATE jurnal_tx
                SET jurnalTxIsActive = 'N',
                jurnalTxM_UserID = ?
                WHERE 
                jurnalTxJurnalID  =  ?";
        $qry = $this->db->query($sql, array($userid, $id));
        if (!$qry) {
            $this->sys_error_db("Error delet jurnal gaji tx");
            $this->db->trans_rollback();
            exit;
        }
        $sql = "UPDATE jurnal_addon
                SET jurnalAddOnIsActive = 'N',
                jurnalAddOnDeletedUserID = ?
                WHERE 
                jurnalAddOnJurnalID  =  ?";
        $qry = $this->db->query($sql, array($userid, $id));
        if (!$qry) {
            $this->sys_error_db("Error delet jurnal gaji tx");
            $this->db->trans_rollback();
            exit;
        }
        $this->db->trans_commit();
        $this->sys_ok("Success");
    }
}
