<?php
class Jurnalpengeluaranbarang extends MY_Controller
{
    var $db;
    public function index() {
        echo "JURNAL PENGELUARAN BARANG";
    }

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

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

            $prm = $this->sys_input;
            $search = "";
            if (isset($prm["search"])) {
                $search = trim($prm["search"]);
                if ($search != "") {
                    $search = "%" . $prm["search"] . "%";
                } else {
                    $search = "%%";
                }
            }

            $sql = "SELECT
                periodeID,
                periodeYear,
                periodeMonth,
                CONCAT(periodeYear, ' - ',periodeMonth) as yearandmonth,
                periodeName,
                periodeStartDate,
                periodeEndDate,
                CONCAT(DATE_FORMAT(periodeStartDate, '%d %M %Y'), ' - ', DATE_FORMAT(periodeEndDate, '%d %M %Y')) as periode
                FROM periode 
                WHERE periodeIsActive = 'Y'
                AND (periodeYear LIKE ? OR periodeName LIKE ?)";
            $query = $this->db->query($sql, [$search, $search]);
            if (!$query) {
                $this->sys_error_db("error get periode", $this->db);
                exit;
            }

            $rows = $query->result_array();
            $result = array(
                "records" => $rows,
                "sql" => $this->db->last_query()
            );
            
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $msg = $exc->getMessage();
            $this->sys_error($msg);
        }
    }

    function searchcoa() {
        try {
            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;
            }

            $rows = $qry->result_array();
            $result = array(
                "records" => $rows,
                "total" => sizeof($rows)
            );

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

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

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

            // get jurnal number
            $sql_no = "SELECT `fn_numbering`('PBC') as no_jurnal";
            $qry_no = $this->db->query($sql_no, []);
            if (!$qry_no) {
                $this->db->trans_rollback();
                $this->sys_error_db("Error get no jurnal");
                exit;
            }
            $numbering = $qry_no->row_array()['no_jurnal'];
            $currMonth = date('m');
            $currYear = date('Y');

            $no_jurnal = 'PBC/' . $currYear . '/' . $currMonth . '/' . strval($numbering);

            $sql_jurnal = "INSERT INTO jurnal(
                jurnalM_BranchCompanyID,
                JurnalS_RegionalID,
                jurnalM_BranchCode,
                jurnalperiodeID,
                jurnalNo,
                jurnalTitle,
                jurnalDescription,
                jurnalDate,
                jurnalJurnalTypeID,
                jurnalCreated,
                jurnalM_UserID
            ) VALUES (?,?,?,?,?,?,?,?,?,NOW(),?)";
            $qry_jurnal = $this->db->query($sql_jurnal, [
                $user['M_BranchCompanyID'],
                $user['S_RegionalID'],
                $user['M_BranchCode'],
                $prm['periodeid'],
                $no_jurnal,
                $prm['title'],
                $prm['description'],
                $prm['date'],
                $prm['jurnaltypeid'],
                $userid
            ]);
            if (!$qry_jurnal) {
               $this->db->trans_rollback();
               $this->sys_error_db("Error insert jurnal ", $this->db);
               exit;
            }
            $lastJurnalInserted = $this->db->insert_id();

            $sql_addon = "INSERT INTO jurnal_addon(
                jurnalAddOnJurnalID,
                jurnalAddOnCode,
                jurnalAddOnValue,
                jurnalAddOnCreated,
                jurnalAddOnCreatedUserID
            ) VALUES ({$lastJurnalInserted}, 'OGB', '{$user['M_BranchCode']}', NOW(),{$userid});";
            $qry_addon = $this->db->query($sql_addon, []);
            if (!$qry_addon) {
                $this->db->trans_rollback();
                $this->sys_error_db("error insert jurnal_addon ", $this->db);
                exit;
            }

            $detail = $prm["detail"];
            foreach ($detail as $key => $value) {
                $sql_tx = "INSERT INTO jurnal_tx(
                    jurnalTxJurnalID,
                    jurnalTxCoaID,
                    jurnalTxDescription,
                    jurnalTxDebit,
                    jurnalTxCredit,
                    jurnalTxCreated,
                    jurnalTxM_UserID
                ) VALUES (?,?,?,?,?,NOW(),?)";
                $qry_tx = $this->db->query($sql_tx, [
                    $lastJurnalInserted,
                    $value["coaid"],
                    $value["coadesc"],
                    $value["debet"],
                    $value["kredit"],
                    $userid
                ]);
                if (!$qry_tx) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("error insert jurnal_tx ", $this->db);
                    exit;
                }
            }
            $this->db->trans_commit();
            $this->sys_ok("success");
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

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

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

            $sql_jurnal = "UPDATE jurnal SET
            jurnalperiodeID = ?,
            jurnalTitle = ?,
            jurnalDescription = ?,
            jurnalDate = ?,
            jurnalLastUpdated = NOW(),
            jurnalM_UserID = ?
            WHERE jurnalID = ?
            ";
            $qry_jurnal = $this->db->query($sql_jurnal, [
                $prm["periodeid"],
                $prm["title"],
                $prm["description"],
                $prm["date"],
                $userid,
                $jurnalid
            ]);
            if (!$qry_jurnal) {
                $this->db->trans_rollback();
                $this->sys_error_db("error update jurnal");
                exit;
            }

            $sql_n = "UPDATE jurnal_tx SET jurnalTxIsActive = 'N' WHERE jurnalTxJurnalID = ?";
            $qry_n = $this->db->query($sql_n, [$jurnalid]);
            if (!$qry_n) {
                $this->db->trans_rollback();
                $this->sys_error_db("error update non active jurnal tx");
                exit;
            }

            $detail = $prm["detail"];
            foreach ($detail as $key => $value) {
                $sql_tx = "INSERT INTO jurnal_tx(
                    jurnalTxJurnalID,
                    jurnalTxCoaID,
                    jurnalTxDescription,
                    jurnalTxDebit,
                    jurnalTxCredit,
                    jurnalTxCreated,
                    jurnalTxM_UserID
                ) VALUES (?,?,?,?,?,NOW(),?)";
                $qry_tx = $this->db->query($sql_tx, [
                    $jurnalid,
                    $value["coaid"],
                    $value["coadesc"],
                    $value["debet"],
                    $value["kredit"],
                    $userid
                ]);
                if (!$qry_tx) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("error insert jurnal_tx ", $this->db);
                    exit;
                }
            }

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

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

            $prm = $this->sys_input;
            $jurnalid = $prm['jurnalid'];

            $sql_a = "SELECT jurnalID, jurnalperiodeID, jurnalNo, jurnalTitle, jurnalDescription, 
            DATE_FORMAT(jurnalDate, '%Y-%m-%d') as jurnalDate, jurnalIsPosted,
            M_BranchCompanyName, S_RegionalName, M_BranchName,
            M_BranchCompanyID, S_RegionalID, M_BranchID,
            JurnalTypeID,
            JurnalTypeCode,
            JurnalTypeName,
            JurnalTypeAccesRight
            FROM jurnal
            JOIN m_branch ON jurnalM_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y'
            JOIN s_regional ON JurnalS_RegionalID = S_RegionalID AND S_RegionalIsActive = 'Y'
            JOIN m_branch_company ON jurnalM_BranchCompanyID = M_BranchCompanyID AND M_BranchCompanyIsActive = 'Y'
            JOIN jurnal_type ON jurnalJurnalTypeID = JurnalTypeID AND JurnalTypeIsActive = 'Y'
            WHERE jurnalID = ? AND jurnalIsActive = 'Y'";

            $qry_a = $this->db->query($sql_a, [$jurnalid]);
            if (!$qry_a) {
                $this->sys_error_db("error get jurnal data");
                exit;
            }
            $rows = $qry_a->row_array();
            
            $sql_b = "SELECT 
            CONCAT(periodeYear, ' - ', periodeName) as displayPeriode,
            CONCAT(DATE_FORMAT(periodeStartDate, '%d %M %Y'), ' - ', DATE_FORMAT(periodeEndDate, '%d %M %Y')) as periode,
            periode.* 
            FROM jurnal
            JOIN periode ON jurnalperiodeID = periodeID AND periodeIsActive = 'Y' AND periodeIsClosed = 'N'
            WHERE jurnalID = ? AND jurnalIsActive = 'Y'";
            $qry_b = $this->db->query($sql_b, [$jurnalid]);
            if (!$qry_b) {
                $this->sys_error_db("error get data periode");
                exit;
            }
            $periode = $qry_b->row_array();

            $sql_tx = "SELECT
            jurnalTxID,
            jurnalTxCoaID as coaid,
            jurnalTxDescription as coadesc,
            jurnalTxDebit as debet,
            jurnalTxCredit as kredit,
            coaAccountNo as coano
            FROM jurnal
            JOIN jurnal_tx ON jurnalTxJurnalID = jurnalID AND jurnalTxIsActive = 'Y'
            JOIN coa ON coaID = jurnalTxCoaID AND coaIsActive = 'Y'
            WHERE jurnalID = ? AND jurnalIsActive = 'Y'";
            $qry_tx = $this->db->query($sql_tx, [$jurnalid]);
            if (!$qry_tx) {
                $this->sys_error_db("error get jurnal tx");
                exit;
            }
            $detailjurnal = $qry_tx->result_array();

            $result = array(
                "jurnal" => $rows,
                "periode" => $periode,
                "jurnaldetail" => $detailjurnal
            );
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $msg = $exc->getMessage();
            $this->sys_error($msg);
        }
    }
}