<?php
class Divisi extends MY_Controller
{
    var $db;
    function __construct()
    {
        parent::__construct();
    }

    function index()
    {
        echo "Api: Training Playground";
        echo "<br>";
    }

    function search()
    {
        try {
            //# cek token valid
            if (! $this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

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

            $all = $prm['all'];
            $limit = '';
            if ($all == 'N') {
                $limit = ' LIMIT 10';
            }

            // sort
            $sortBy = $prm['sortBy'];
            $sortStatus = $prm['sortStatus'];
            if ($sortBy) {
                $q_sort = "ORDER BY " . $sortBy . " " . $sortStatus;
            }

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

            // $number_offset = ($prm['current_page'] - 1) * $number_limit;

            // $sql_filter .= "select count(distinct ItemUnitID, ItemUnitCode,
            // ItemUnitName) 
            // as total
            // from itemunit
            // where ItemUnitIsActive = 'Y'
            // AND (
            //     ItemUnitCode like ?
            //     OR ItemUnitName like ?
            // )";


            $sql_filter .= "
            select count(*) as total from division where DivisionIsActive = 'Y' AND ( DivisionName like ? OR DivisionCode like ?)";

            $qry_filter = $this->db->query($sql_filter, [$search, $search]);
            // echo $this->db->last_query();

            $tot_count = 0;
            $tot_page = 0;
            if ($qry_filter) {
                // $tot_count = $qry_filter->result_array()[0]["total"];
                $tot_count = $qry_filter->row()->total;
                $tot_page = ceil($tot_count / $number_limit);
            } else {
                $this->sys_error_db("itemunit count", $this->db);
                exit;
            }

            $sql_data .= "select 
            distinct    
            DivisionCode as code, 
            DivisionName as name, 
            DivisionID as id,
            DivisionKodeSurat
            from division
            where DivisionIsActive = 'Y'
            AND (
                DivisionCode like ?
                OR DivisionName like ?
            )
            $q_sort
            limit ? offset ?";

            $qry_data = $this->db->query($sql_data, [
                $search,
                $search,
                $number_limit,
                $number_offset
            ]);

            // var_dump($this->db->last_query());

            if ($qry_data) {
                $rows = $qry_data->result_array();
            } else {
                $this->sys_error_db("division select");
                exit;
            }

            $result = array(
                "total" => $tot_page,
                "total_filter" => count($rows),
                "records" => $rows,
                "qry" => $sql_data
            );

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

    function add()
    {
        try {
            //# cek token valid
            if (! $this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

            //begin transaction 
            $this->db->trans_begin();

            //# ambil parameter input
            $prm = $this->sys_input;

            $userid = $this->sys_user['M_UserID'];
            // $userid = 3;
            
            $divisi_name = $prm['name'];
            $lettercode = $prm['lettercode'];

            if($divisi_name != ""){
                $sql = "SELECT COUNT(*) as exist 
                    FROM division 
                    WHERE DivisionIsActive = 'Y' 
                    AND (DivisionName = ? OR DivisionKodeSurat = ?)";
                $query_count = $this->db->query($sql,[$divisi_name, $lettercode]);
                $get_count = $query_count->row_array();
                if($get_count['exist'] != 0){
                    $this->db->trans_rollback();
                    $this->sys_error_db("division name already exist");
                    exit;
                }
                $sql = "INSERT INTO division (
                    DivisionCode, 
                    DivisionName, 
                    DivisionKodeSurat, 
                    DivisionIsActive, 
                    DivisionCreated, 
                    DivisionCreatedUserID
                ) VALUES (fn_numbering('DV'), ?, ?, 'Y', NOW(), ?)";
                $query_insert = $this->db->query($sql,[$divisi_name, $lettercode, $userid]);
                if(!$query_insert){
                    $this->db->trans_rollback();
                    $this->sys_error_db("division insert");
                    exit;
                }
                $this->db->trans_commit();
                $divisi_id = $this->db->insert_id();
                $sql = "SELECT 
                    DivisionID as id, 
                    DivisionCode as code, 
                    DivisionName as name ,
                    DivisionKodeSurat
                FROM division 
                WHERE DivisionIsActive = 'Y' AND DivisionID = ?";
                $query_select = $this->db->query($sql,[$divisi_id]);
                $result = array(
                    "total" => 1,
                    "records" => $query_select->row_array()
                );
                $this->sys_ok($result);
            }else{
                $this->db->trans_rollback();
                $this->sys_error_db("division name is required");
                exit;
            }
            
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    function edit()
    {
        try {
            //# cek token valid
            if (! $this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

            //begin transaction 
            $this->db->trans_begin();

            //# ambil parameter input
            $prm = $this->sys_input;

            $userid = $this->sys_user['M_UserID'];
            // $userid = 1;
            $id = $prm['id'];
            $divisi_name = $prm['name'];
            $lettercode = $prm['lettercode'];

            if($divisi_name != "" && $id != "" && $id != 0){
                $sql = "SELECT COUNT(*) as exist 
                FROM division 
                WHERE DivisionIsActive = 'Y' 
                AND (DivisionName = ? OR DivisionKodeSurat = ?)
                AND DivisionID != ?";
                $query_count = $this->db->query($sql,[$divisi_name, $lettercode, $id]);
                $get_count = $query_count->row_array();
                if($get_count['exist'] != 0){
                    $this->db->trans_rollback();
                    $this->sys_error_db("division name already exist");
                    exit;
                }

                $sql = "UPDATE division SET 
                    DivisionName = ?, 
                    DivisionKodeSurat = ?, 
                    DivisionLastUpdated = now(), 
                    DivisionLastUpdatedUserID = ? 
                WHERE DivisionID = ?";
                $query_update = $this->db->query($sql,[$divisi_name, $lettercode, $userid, $id]);
                if(!$query_update){
                    $this->db->trans_rollback();
                    $this->sys_error_db("division update");
                    exit;
                }
                $this->db->trans_commit();
                $sql = "SELECT 
                    DivisionID as id, 
                    DivisionCode as code, 
                    DivisionName as name,
                    DivisionKodeSurat 
                FROM division 
                WHERE DivisionIsActive = 'Y' AND DivisionID = ?";
                $query_select = $this->db->query($sql,[$id]);
                $result = array(
                    "total" => 1,
                    "records" => $query_select->row_array()
                );
                $this->sys_ok($result);
            }
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    function delete()
    {
        try {
            //# cek token valid
            if (! $this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

            //begin transaction 
            $this->db->trans_begin();

            //# ambil parameter input
            $prm = $this->sys_input;
            $id = $prm['id'];
            $userid = $this->sys_user['M_UserID'];
            // $userid = 1;
            if($id != "" && $id != 0){
                $sql = "UPDATE division SET DivisionIsActive = 'N', DivisionDeleted = now(), DivisionDeletedUserID = ? WHERE DivisionID = ?";
                $query_update = $this->db->query($sql,[$userid, $id]);
                if(!$query_update){
                    $this->db->trans_rollback();
                    $this->sys_error_db("division delete");
                    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);
        }
    }
}
