<?php

class JournalVerifEdit extends MY_Controller
{
    var $db;
    public function index() {
        echo "Verifikasi Edit Journal";
    }
    public function __construct()
    {
        parent::__construct();
    }

    # QUERY #
    public function getListPeriode() {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

            $sql = "SELECT 
                periodeID,
                periodeName,
                DATE_FORMAT(periodeStartDate, '%d %M %Y') AS periodeStartDate,
                DATE_FORMAT(periodeEndDate, '%d %M %Y') AS periodeEndDate
            FROM periode
            WHERE periodeIsActive = 'Y'
                AND periodeIsClosed = 'N'
            ORDER BY periodeID DESC";
            $que = $this->db->query($sql, []);
            if (!$que) {
                $this->sys_error_db("[Error] get daftar periode");
                exit;
            }

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

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

            $param = $this->sys_input;
            $sql = "SELECT
                JurnalTypeID,
                JurnalTypeCode,
                JurnalTypeName 
            FROM jurnal_type 
            WHERE JurnalTypeIsActive = 'Y'";
            $que = $this->db->query($sql, []);
            if (!$que) {
                $this->sys_error_db("[Error] get daftar tipe jurnal");
                exit;
            }

            $data = $que->result_array();
            $all = [
                'JurnalTypeID' => 0,
                'JurnalTypeCode' => "X",
                'JurnalTypeName' => "SEMUA"
            ];
            array_unshift($data, $all);

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

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

            $param = $this->sys_input;
            $user = $this->sys_user;

            $isBranch = " ";
            if ($user['M_BranchID'] != '0') {
                $isBranch .= " AND jurnalM_BranchCode = '{$user['M_BranchCode']}'";
            }

            $keyword = "%";
            if ($param['search'] != '') {
                $keyword = $param['search'] . "%";
            }

            $row_limit = 10;
            $curr_page = (int)($param['page'] ?? 1);
            $row_ofset = max(0, ($curr_page - 1) * $row_limit);

            $sql_base = "SELECT
                jurnalID,
                jurnalperiodeID,
                jurnalNo,
                jurnalTitle,
                jurnalDescription,
                jurnalEditStatus,
                jurnalDate,
                JurnalTypeID,
                JurnalTypeCode,
                JurnalTypeName,
                JurnalRequestEditID,
                JurnalRequestEditStaffID,
                JurnalRequestEditStaffName,
                JurnalRequestEditStatusRequest,
                apr.M_UserUsername AS RequestApprovedBy,
                JurnalRequestEditStatusEdit,
                ape.M_UserUsername AS EditApprovedBy,
                S_RegionalName,
                M_BranchName,
                M_BranchCompanyName
            FROM jurnal
            JOIN jurnal_request_edit ON JurnalRequestEditJurnalID = jurnalID
                AND JurnalRequestEditIsActive = 'Y'
            JOIN jurnal_type ON JurnalTypeID = jurnalJurnalTypeID
                AND JurnalTypeIsActive = 'Y'
            JOIN m_branch_company ON M_BranchCompanyID = jurnalM_BranchCompanyID
            JOIN s_regional ON S_RegionalID = JurnalS_RegionalID
            LEFT JOIN m_branch ON M_BranchCode = jurnalM_BranchCode
            LEFT JOIN m_user apr ON apr.M_UserID = JurnalRequestEditApproveRequestBy
            LEFT JOIN m_user ape ON ape.M_UserID = JurnalRequestEditApproveEditBy
            WHERE jurnalperiodeID = ?
                AND JurnalS_RegionalID = ?
                AND (jurnalJurnalTypeID = ? OR 0 = ?)
                AND jurnalDate BETWEEN DATE(?) AND DATE(?)
                AND jurnalNo LIKE ?
                AND jurnalIsActive = 'Y'
            " . $isBranch;
            
            $sql_data = $sql_base . " LIMIT ? OFFSET ?";
            $que_data = $this->db->query($sql_data, [
                $param['periodeID'], $user['S_RegionalID'],
                $param['typeJournalID'], $param['typeJournalID'],
                $param['startdate'], $param['enddate'],
                $keyword, $row_limit, $row_ofset
            ]);
            if (!$que_data) {
                $this->sys_error_db("[Error] get daftar journal edit");
                exit;
            }

            // get total all journal edit 
            $sql_total = "SELECT COUNT(*) AS total FROM ($sql_base) as x";
            $que_total = $this->db->query($sql_total, [
                $param['periodeID'], $user['S_RegionalID'],
                $param['typeJournalID'], $param['typeJournalID'], 
                $param['startdate'], $param['enddate'], $keyword
            ]);
            if (!$que_total) {
                $this->sys_error_db("[Error] get total all journal edit");
                exit;
            }

            $data = [
                "records" => $que_data->result_array(),
                "total" => $que_total->row_array()['total']
            ];
            $this->sys_ok($data);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

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

            $param = $this->sys_input;

            ## get latest edit change log data ##
            $sql_data = "SELECT 
                JurnalEditLogID,
                JurnalEditLogIDJurnalID,
                JurnalEditLogIDJsonBefore,
                JurnalEditLogIDJsonAfter,
                JurnalEditLogUserID AS StaffUserID,
                IFNULL(NULLIF(M_UserFullName, ''), M_UserUsername) AS StaffName
            FROM acc_one_log.jurnal_edit_log
            JOIN m_user ON M_UserID = JurnalEditLogUserID
            WHERE JurnalEditLogIDJurnalID = ?
                AND JurnalEditLogIsActive = 'Y'
            ORDER BY JurnalEditLogID DESC
            LIMIT 1";
            $que_data = $this->db->query($sql_data, [$param['jurnalID']]);
            if (!$que_data) {
                $this->sys_error_db("[Error] get data change jurnal");
                exit;
            }
            $data = $que_data->result_array()[0];
            
            $before = json_decode($data['JurnalEditLogIDJsonBefore'], true);
            $after = json_decode($data['JurnalEditLogIDJsonAfter'], true);
            
            unset($data['JurnalEditLogIDJsonBefore']);
            unset($data['JurnalEditLogIDJsonAfter']);

            $data['changeBefore'] = $before;
            $data['changeAfter'] = $after;

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

    # MUTATION #
    public function requestEditJurnal() {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

            $this->db->trans_begin();
            $param = $this->sys_input;
            $user = $this->sys_user;

            # insert into request jurnal edit #
            $sqlreq = "INSERT INTO jurnal_request_edit (
                JurnalRequestEditJurnalID,
                JurnalRequestEditStaffID,
                JurnalRequestEditStaffName,
                JurnalRequestEditUserID,
                JurnalRequestEditCreated
            ) VALUES (?,?,?,?,NOW())";
            $quereq = $this->db->query($sqlreq, [
                $param['jurnalID'], $param['staffID'],
                $param['staffName'], $user['M_UserID']
            ]);
            if (!$quereq) {
                $this->db->trans_rollback();
                $this->sys_error_db("[Error] insert request edit into table jurnal request edit");
                exit;
            }

            $this->db->trans_commit();
            $this->sys_ok("Request edit jurnal berhasil dibuat");
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

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

            $this->db->trans_begin();
            $param = $this->sys_input;
            $user = $this->sys_user;

            # update request jurnal edit status #
            $sqlreq = "UPDATE jurnal_request_edit SET
                JurnalRequestEditStatusRequest = ?,
                JurnalRequestEditApproveRequestBy = ?,
                JurnalRequestEditUpdated = NOW()
            WHERE JurnalRequestEditID = ?";
            $quereq = $this->db->query($sqlreq, [
                $param['status'], $user['M_UserID'], 
                $param['JurnalRequestEditID']
            ]);
            if (!$quereq) {
                $this->db->trans_rollback();
                $this->sys_error_db("[Error] update request edit status");
                exit;
            }

            # update data header jurnal status edit #
            $sqlheader = "UPDATE jurnal SET
                jurnalEditStatus = 'Y',
                jurnalLastUpdated = NOW()
            WHERE jurnalID = ?";
            $queheader = $this->db->query($sqlheader, [$param['jurnalID']]);
            if (!$queheader) {
                $this->db->trans_rollback();
                $this->sys_error_db("[Error] update header jurnal");
                exit;
            }

            $this->db->trans_commit();
            $this->sys_ok("[Success] update status request");
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

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

            $this->db->trans_begin();

            $param = $this->sys_input;
            $user = $this->sys_user;

            $old_jurnaltx = $param['oldjurnaltx'];
            $new_jurnaltx = $param['newjurnaltx'];

            # log the data in accone log #
            $sql_addlog = "INSERT INTO acc_one_log.jurnal_edit_log (
                JurnalEditLogIDJurnalID,
                JurnalEditLogIDJsonBefore,
                JurnalEditLogIDJsonAfter,
                JurnalEditLogUserID,
                JurnalEditLogCreated
            ) VALUES (?,?,?,?,NOW())";
            $que_addlog = $this->db->query($sql_addlog, [
                $param['jurnalID'], json_encode($old_jurnaltx), 
                json_encode($new_jurnaltx), $user['M_UserID']
            ]);
            if (!$que_addlog) {
                $this->db->trans_rollback();
                $this->sys_error_db("[Error] insert into acc one jurnal log");
                exit;
            }
            $jurnalEditLogID = $this->db->insert_id();

            # UPDATE table jurnal request edit #
            $sql_req = "UPDATE jurnal_request_edit SET 
                JurnalRequestEditJurnalEditLogID = ?
            WHERE JurnalRequestEditID = ?";
            $que_req = $this->db->query($sql_req, [
                $jurnalEditLogID, $param['jurnalRequestEditID']
            ]);
            if (!$que_req) {
                $this->db->trans_rollback();
                $this->sys_error_db("[Error] update table jurnal request edit");
                exit;
            }

            $this->db->trans_commit();
            $this->sys_ok("[Success] save edit jurnal");
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

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

            $this->db->trans_begin();
            $param = $this->sys_input;
            $user = $this->sys_user;

            # UPDATE jurnal tx #
            $newtrx = $param['newtrx'];
            $sqltrx = "UPDATE jurnal_tx SET 
                jurnalTxCoaID = ?,
                jurnalTxDescription = ?,
                jurnalTxLastUpdated = NOW(),
                jurnalTxM_UserID = ?
            WHERE jurnalTxID = ?
                AND jurnalTxJurnalID = ?
                AND jurnalTxIsActive = 'Y'";
            foreach ($newtrx as $key => $obj) {
                $quetrx = $this->db->query($sqltrx, [
                    $obj['coaID'], $obj['coaDescription'], $user['M_UserID'],
                    $obj['jurnalTxID'], $obj['jurnalTxJurnalID']
                ]);
                if (!$quetrx) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("[Error] update new jurnal tx");
                    exit;
                }
            }

            # UPDATE jurnal header edit status #
            $sql = "UPDATE jurnal 
                SET jurnalEditStatus = 'N',
                jurnalLastUpdated = NOW()
            WHERE jurnalID = ?";
            $que = $this->db->query($sql, [$param['jurnalID']]);
            if (!$que) {
                $this->db->trans_rollback();
                $this->sys_error_db("[Error] update status edit");
                exit;
            }

            # UPDATE jurnal status edit jurnal #
            $sqlreq = "UPDATE jurnal_request_edit SET
                JurnalRequestEditStatusEdit = ?,
                JurnalRequestEditApproveEditBy = ?,
                JurnalRequestEditUpdated = NOW()
            WHERE JurnalRequestEditID = ?";
            $quereq = $this->db->query($sqlreq, [
                $param['status'], $user['M_UserID'], 
                $param['JurnalRequestEditID']
            ]);
            if (!$quereq) {
                $this->db->trans_rollback();
                $this->sys_error_db("[Error] update status edit jurnal");
                exit;
            }

            $this->db->trans_commit();
            $this->sys_ok("[Success] approve edit jurnal");
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }
}