<?php

class Rochecklist extends MY_Controller
{
    var $db;

    public function index()
    {
        echo "md ro checklist";
    }

    public function __construct()
    {
        parent::__construct();
    }
    public function getItemCategory()
    {
        if (!$this->isLogin) {
            $this->sys_error("Invalid Token");
        }
        $sql = "SELECT 
                itemCategoryID,
                itemCategoryName
                FROM item_category
                WHERE itemCategoryIsActive = 'Y'";
        $qry = $this->db->query($sql, []);
        if (!$qry) {
            $this->sys_error_db("Error get item category", $this->db);
            exit;
        }
        // print_r($this->db->last_query());
        $data = $qry->result_array();
        $this->sys_ok($data);
    }
    public function getItemGroup()
    {
        if (!$this->isLogin) {
            $this->sys_error("Invalid Token");
        }
        $sql = "SELECT 
                Nat_GroupID,
                Nat_GroupName
                FROM nat_group
                WHERE Nat_GroupIsActive = 'Y';";
        $qry = $this->db->query($sql, []);
        if (!$qry) {
            $this->sys_error_db("Error get item group", $this->db);
            exit;
        }
        // print_r($this->db->last_query());
        $group = $qry->result_array();
        $sql = "SELECT Nat_SubGroupID,
                Nat_SubGroupNat_GroupID,
                Nat_SubGroupName
                FROM nat_subgroup
                WHERE Nat_SubGroupIsActive = 'Y';";
        $qry = $this->db->query($sql, []);
        if (!$qry) {
            $this->sys_error_db("Error get item sub group", $this->db);
            exit;
        }
        // print_r($this->db->last_query());
        $subgGroup = $qry->result_array();
        $this->sys_ok([
            'group' => $group,
            'subGroup' => $subgGroup
        ]);
    }
    public function search()
    {
        if (!$this->isLogin) {
            $this->sys_error("Invalid Token");
        }
        $prm = $this->sys_input;
        $user = $this->sys_user;
        $search = '%' . $prm['search'] . '%';

        $page = $prm["page"];
        $type = $prm["type"];

        $ROW_PER_PAGE = 15;
        $start_offset = 0;
        // print_r($prm);

        if (isset($prm["page"])) {
            if (
                is_numeric($prm["page"]) && $prm["page"] > 0
            ) {
                $start_offset = ($page - 1) * $ROW_PER_PAGE;
            }
        }
        $sqlType = '';
        if ($type == 'G') {
            $sqlType = "AND RoChecklistType = 'G";
        }
        if ($type == 'C') {
            $sqlType = "AND RoChecklistType = 'C";
        }
        if ($type == 'P') {
            $sqlType = "AND RoChecklistType = 'P";
        }

        $sql = "SELECT COUNT(*) as total 
                FROM ro_checklist
                WHERE RoChecklistIsActive = 'Y'
                AND RoChecklistName LIKE ?
                {$sqlType}";
        $qry = $this->db->query($sql, [$search]);
        if (!$qry) {
            $this->sys_error_db("Error get total", $this->db);
            exit;
        }
        // print_r($this->db->last_query());
        $total = $qry->row_array()['total'];
        $sql = "SELECT *
                FROM ro_checklist
                WHERE RoChecklistIsActive = 'Y'
                AND RoChecklistName LIKE ?
                {$sqlType}
                LIMIT ? OFFSET ?";
        $qry = $this->db->query($sql, [$search, $ROW_PER_PAGE, $start_offset]);
        if (!$qry) {
            $this->sys_error_db("Error get total", $this->db);
            exit;
        }
        // print_r($this->db->last_query());
        $rst = array(
            "total" => ceil($total / $ROW_PER_PAGE),
            "records" => $qry->result_array()
        );
        $this->sys_ok($rst);
    }

    public function add()
    {
        // $this->db->trans_commit();
        // $this->db->trans_rollback();
        $this->db->trans_begin();
        if (!$this->isLogin) {
            $this->sys_error("Invalid Token");
        }
        $prm = $this->sys_input;
        $user = $this->sys_user;
        $userId = $this->sys_user["M_UserID"];
        $search = '%' . $prm['search'] . '%';
        $page = $prm["page"];
        $type = $prm["type"];
        $detail = $prm["detail"];

        if (!in_array($type, ['G', 'C', 'P'])) {
            $this->sys_error("Type tidak sesuai");
            exit;
        }

        $sql = "INSERT INTO ro_checklist (
                    RoChecklistName, 
                    RoChecklistType,  
                    RoChecklistTypeCreatedUserID
                ) VALUES (
                    ?, 
                    ?, 
                    ?
                );";
        $qry = $this->db->query($sql, [$prm['name'], $type, $userId]);
        if (!$qry) {
            $this->sys_error_db("Error add ", $this->db);
            print_r($this->db->last_query());
            $this->db->trans_rollback();
            exit;
        }
        $checklistID = $this->db->insert_id();
        if ($type == 'C') {
            $sqlInsert = '';
            $arrCategory = [];
            foreach ($detail as $key => $value) {
                $sqlInsert = "{$sqlInsert} ({$checklistID}, {$value['itemCategoryID']}, {$userId})";
                if (($key + 1) != count($detail)) {
                    $sqlInsert = "{$sqlInsert},";
                }

                $sqlCek = "SELECT * FROM ro_checklist_map 
                        WHERE RoChecklistMapRoChecklistID = ? 
                        AND  RoChecklistMapItemCategoryID = ?
                        AND RoChecklistMapIsActive = 'Y'";
                $qry = $this->db->query($sqlCek, [$checklistID, $value['itemCategoryID']]);
                if (!$qry) {
                    $this->sys_error_db("Error cek detail mapping category", $this->db);
                    $this->db->trans_rollback();
                    exit;
                }
                $cek = $qry->row_array();
                if (!empty($cek) || in_array($value['itemCategoryID'], $arrCategory)) {
                    $this->sys_error_db("{$value['itemCategoryName']} sudah pernah di pilih ", $this->db);
                    $this->db->trans_rollback();
                    exit;
                }
                $arrCategory[] = $value['itemCategoryID'];
            }

            $sql = "INSERT INTO ro_checklist_map (
                    RoChecklistMapRoChecklistID, 
                    RoChecklistMapItemCategoryID,  
                    RoChecklistMapCreatedUserID
                ) VALUES {$sqlInsert};";
            $qry = $this->db->query($sql, []);
            if (!$qry) {
                $this->sys_error_db("Error add detail mapping category", $this->db);
                $this->db->trans_rollback();
                exit;
            }
        }
        if ($type == 'P') {
            $sqlInsert = '';
            $arrSubGroup = [];
            foreach ($detail as $key => $value) {

                $sqlCek = "SELECT * FROM ro_checklist_map 
                        WHERE RoChecklistMapRoChecklistID = ? 
                        AND  RoChecklistMapNat_GroupID = ?
                        AND RoChecklistMapNat_SubGroupID = ?
                        AND RoChecklistMapIsActive = 'Y'";
                $qry = $this->db->query($sqlCek, [$checklistID, $value['Nat_SubGroupNat_GroupID'], $value['Nat_SubGroupID']]);
                if (!$qry) {
                    $this->sys_error_db("Error cek detail mapping category", $this->db);
                    $this->db->trans_rollback();
                    exit;
                }
                $cek = $qry->row_array();
                // echo empty($cek);
                // echo $value['Nat_SubGroupID'];
                // echo "\n";
                // print_r($arrSubGroup);
                // echo "\n";
                // echo in_array($value['Nat_SubGroupID'], $arrSubGroup);
                if (!empty($cek) || in_array($value['Nat_SubGroupID'], $arrSubGroup)) {
                    $this->sys_error_db("{$value['Nat_SubGroupName']} sudah pernah di pilih", $this->db);
                    $this->db->trans_rollback();
                    exit;
                }
                $arrSubGroup[] = $value['Nat_SubGroupID'];
                $sqlInsert = "{$sqlInsert} ({$checklistID}, {$value['Nat_SubGroupNat_GroupID']}, {$value['Nat_SubGroupID']},{$userId})";
                if (($key + 1) != count($detail)) {
                    $sqlInsert = "{$sqlInsert},";
                }
            }
            $sql = "INSERT INTO ro_checklist_map (
                    RoChecklistMapRoChecklistID, 
                    RoChecklistMapNat_GroupID,  
                    RoChecklistMapNat_SubGroupID,  
                    RoChecklistMapCreatedUserID
                ) VALUES {$sqlInsert};";
            $qry = $this->db->query($sql, []);
            if (!$qry) {
                $this->sys_error_db("Error add detail mapping product", $this->db);
                $this->db->trans_rollback();
                exit;
            }
        }
        $this->db->trans_commit();
        $this->sys_ok('Success');
    }

    public function addItem()
    {
        if (!$this->isLogin) {
            $this->sys_error("Invalid Token");
        }
        $prm = $this->sys_input;
        $user = $this->sys_user;
        $userId = $this->sys_user["M_UserID"];

        $id = $prm["id"];
        $type = $prm["type"];
        $detail = $prm["detail"];
        if ($type == 'C') {
            $sqlInsert = '';
            $arrCategory = [];
            foreach ($detail as $key => $value) {
                $sqlInsert = "{$sqlInsert} ({$id}, {$value['itemCategoryID']}, {$userId})";
                if (($key + 1) != count($detail)) {
                    $sqlInsert = "{$sqlInsert},";
                }

                $sqlCek = "SELECT * FROM ro_checklist_map 
                        WHERE RoChecklistMapRoChecklistID = ? 
                        AND  RoChecklistMapItemCategoryID = ?
                        AND RoChecklistMapIsActive = 'Y'";
                $qry = $this->db->query($sqlCek, [$id, $value['itemCategoryID']]);
                if (!$qry) {
                    $this->sys_error_db("Error cek detail mapping category", $this->db);
                    $this->db->trans_rollback();
                    exit;
                }
                $cek = $qry->row_array();
                if (!empty($cek) || in_array($value['itemCategoryID'], $arrCategory)) {
                    $this->sys_error_db("{$value['itemCategoryName']} sudah pernah di pilih ", $this->db);
                    $this->db->trans_rollback();
                    exit;
                }
                $arrCategory[] = $value['itemCategoryID'];
            }

            $sql = "INSERT INTO ro_checklist_map (
                    RoChecklistMapRoChecklistID, 
                    RoChecklistMapItemCategoryID,  
                    RoChecklistMapCreatedUserID
                ) VALUES {$sqlInsert};";
            $qry = $this->db->query($sql, []);
            if (!$qry) {
                $this->sys_error_db("Error add detail mapping category", $this->db);
                $this->db->trans_rollback();
                exit;
            }
        }
        if ($type == 'P') {
            $sqlInsert = '';
            $arrSubGroup = [];
            foreach ($detail as $key => $value) {

                $sqlCek = "SELECT * FROM ro_checklist_map 
                        WHERE RoChecklistMapRoChecklistID = ? 
                        AND  RoChecklistMapNat_GroupID = ?
                        AND RoChecklistMapNat_SubGroupID = ?
                        AND RoChecklistMapIsActive = 'Y'";
                $qry = $this->db->query($sqlCek, [$id, $value['Nat_SubGroupNat_GroupID'], $value['Nat_SubGroupID']]);
                if (!$qry) {
                    $this->sys_error_db("Error cek detail mapping category", $this->db);
                    $this->db->trans_rollback();
                    exit;
                }
                $cek = $qry->row_array();
                if (!empty($cek) || in_array($value['Nat_SubGroupID'], $arrSubGroup)) {
                    $this->sys_error_db("{$value['Nat_SubGroupName']} sudah pernah di pilih", $this->db);
                    $this->db->trans_rollback();
                    exit;
                }
                $arrSubGroup[] = $value['Nat_SubGroupID'];
                $sqlInsert = "{$sqlInsert} ({$id}, {$value['Nat_SubGroupNat_GroupID']}, {$value['Nat_SubGroupID']},{$userId})";
                if (($key + 1) != count($detail)) {
                    $sqlInsert = "{$sqlInsert},";
                }
            }
            $sql = "INSERT INTO ro_checklist_map (
                    RoChecklistMapRoChecklistID, 
                    RoChecklistMapNat_GroupID,  
                    RoChecklistMapNat_SubGroupID,  
                    RoChecklistMapCreatedUserID
                ) VALUES {$sqlInsert};";
            $qry = $this->db->query($sql, []);
            if (!$qry) {
                $this->sys_error_db("Error add detail mapping product", $this->db);
                $this->db->trans_rollback();
                exit;
            }
        }
        $this->sys_ok('Success');
    }

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

        $id = $prm["id"];
        $sql = "SELECT *
                FROM ro_checklist
                WHERE RoChecklistIsActive = 'Y'
                AND RoChecklistID = ?
                LIMIT 1";
        $qry = $this->db->query($sql, [$id]);
        if (!$qry) {
            $this->sys_error_db("Error get checklist", $this->db);
            exit;
        }
        $data = $qry->row_array();
        $retval = [];
        if ($data['RoChecklistType'] == 'C') {
            $sql = "SELECT 
                    RoChecklistMapID,
                    RoChecklistMapRoChecklistID,
                    RoChecklistMapItemCategoryID itemCategoryID,
                    itemCategoryName
                    FROM 
                    ro_checklist_map
                    JOIN 
                    ro_checklist 
                    ON RoChecklistMapRoChecklistID  = RoChecklistID
                    JOIN item_category
                    ON RoChecklistMapItemCategoryID = itemCategoryID
                    WHERE 
                    RoChecklistMapRoChecklistID = ?
                    AND RoChecklistMapIsActive = 'Y'";
            $qry = $this->db->query($sql, [$id]);
            if (!$qry) {
                $this->sys_error_db("Error get checklist detail category", $this->db);
                exit;
            }
            $retval = $qry->result_array();
        }
        if ($data['RoChecklistType'] == 'P') {
            $sql = "SELECT 
                    RoChecklistMapID,
                    RoChecklistMapRoChecklistID,
                    Nat_GroupID,
                    Nat_GroupName,
                    Nat_SubGroupID,
                    Nat_SubGroupName
                    FROM 
                    ro_checklist_map
                    JOIN 
                    ro_checklist 
                    ON RoChecklistMapRoChecklistID  = RoChecklistID
                    JOIN nat_group
                    ON RoChecklistMapNat_GroupID = Nat_GroupID
                    JOIN nat_subgroup
                    ON RoChecklistMapNat_SubGroupID= Nat_SubGroupID
                    WHERE 
                    RoChecklistMapRoChecklistID = ?
                    AND RoChecklistMapIsActive = 'Y';";
            $qry = $this->db->query($sql, [$id]);
            if (!$qry) {
                $this->sys_error_db("Error get checklist detail category", $this->db);
                exit;
            }
            $retval = $qry->result_array();
        }
        $this->sys_ok($retval);
    }
    public function updateMapping()
    {
        $this->db->trans_begin();
        if (!$this->isLogin) {
            $this->sys_error("Invalid Token");
        }
        $prm = $this->sys_input;
        $user = $this->sys_user;
        $userId = $this->sys_user["M_UserID"];
        $id = $prm["id"];
        $type = $prm["type"];
        $detail = $prm["detail"];

        if (!in_array($type, ['G', 'C', 'P'])) {
            $this->sys_error("Type tidak sesuai");
            exit;
        }
        if ($type == 'C') {
            $sqlCek = "SELECT * FROM ro_checklist_map 
                        WHERE RoChecklistMapRoChecklistID = ? 
                        AND  RoChecklistMapItemCategoryID = ?
                        AND RoChecklistMapIsActive = 'Y'";
            $qry = $this->db->query($sqlCek, [$id, $detail['itemCategoryID']]);
            if (!$qry) {
                $this->sys_error_db("Error cek detail mapping category", $this->db);
                $this->db->trans_rollback();
                exit;
            }
            $cek = $qry->row_array();
            if (!empty($cek)) {
                $this->sys_error_db("{$detail['itemCategoryName']} sudah pernah di pilih ", $this->db);
                $this->db->trans_rollback();
                exit;
            }

            $sql = "UPDATE ro_checklist_map SET 
                    RoChecklistMapItemCategoryID = ?,  
                    RoChecklistMapLastUpdatedUserID = ?
                    WHERE RoChecklistMapID = ?
                ";
            $qry = $this->db->query($sql, [$detail['itemCategoryID'], $userId, $detail['RoChecklistMapID']]);
            if (!$qry) {
                $this->sys_error_db("Error add detail mapping category", $this->db);
                $this->db->trans_rollback();
                exit;
            }
        }
        if ($type == 'P') {
            $sqlCek = "SELECT * FROM ro_checklist_map 
                        WHERE RoChecklistMapRoChecklistID = ? 
                        AND  RoChecklistMapNat_GroupID = ?
                        AND RoChecklistMapNat_SubGroupID = ?
                        AND RoChecklistMapIsActive = 'Y'";
            $qry = $this->db->query($sqlCek, [$id, $detail['Nat_SubGroupNat_GroupID'], $detail['Nat_SubGroupID']]);
            if (!$qry) {
                $this->sys_error_db("Error cek detail mapping category", $this->db);
                $this->db->trans_rollback();
                exit;
            }
            $cek = $qry->row_array();
            // echo $this->db->last_query();
            // print_r($cek);
            // echo ($cek);
            // exit;
            if (!empty($cek)) {
                $this->sys_error_db("{$detail['Nat_SubGroupName']} sudah pernah di pilih", $this->db);
                $this->db->trans_rollback();
                exit;
            }

            $sql = "UPDATE ro_checklist_map SET
                    RoChecklistMapNat_GroupID = ?,  
                    RoChecklistMapNat_SubGroupID = ?,  
                    RoChecklistMapLastUpdatedUserID = ?
                    WHERE RoChecklistMapID = ?
                ";
            $qry = $this->db->query($sql, [$detail['Nat_SubGroupNat_GroupID'], $detail['Nat_SubGroupID'], $userId, $detail['RoChecklistMapID']]);
            if (!$qry) {
                $this->sys_error_db("Error add detail mapping product", $this->db);
                $this->db->trans_rollback();
                exit;
            }
        }
        $this->db->trans_commit();
        $this->sys_ok('Success');
    }
    public function updateName()
    {
        $this->db->trans_begin();
        if (!$this->isLogin) {
            $this->sys_error("Invalid Token");
        }
        $prm = $this->sys_input;
        $user = $this->sys_user;
        $userId = $this->sys_user["M_UserID"];
        $id = $prm["id"];
        // $type = $prm["type"];
        $name = $prm["name"];


        $sqlCek = "UPDATE ro_checklist SET
                RoChecklistName = ?,
                RoChecklistTypeLastUpdatedUserID = ?
                WHERE RoChecklistID = ?";
        $qry = $this->db->query($sqlCek, [$name, $userId,  $id]);
        if (!$qry) {
            $this->sys_error_db("Error update name", $this->db);
            $this->db->trans_rollback();
            exit;
        }


        $this->db->trans_commit();
        $this->sys_ok('Success');
    }
    public function updateType()
    {
        $this->db->trans_begin();
        if (!$this->isLogin) {
            $this->sys_error("Invalid Token");
        }
        $prm = $this->sys_input;
        $user = $this->sys_user;
        $userId = $this->sys_user["M_UserID"];
        $id = $prm["id"];
        // $type = $prm["type"];
        $type = $prm["type"];
        if (!in_array($type, ['G', 'C', 'P'])) {
            $this->sys_error("Type tidak sesuai");
            exit;
        }

        $sqlCek = "SELECT * FROM ro_checklist WHERE RoChecklistID = ?";
        $qry = $this->db->query($sqlCek, [$id]);
        if (!$qry) {
            $this->sys_error_db("Error cek", $this->db);
            $this->db->trans_rollback();
            exit;
        }
        $cek = $qry->row_array();
        if ($cek['RoChecklistType'] == $type) {
            $this->sys_error_db("tipe tidak berubah", $this->db);
            $this->db->trans_rollback();
            exit;
        }



        $sql = "UPDATE ro_checklist SET
                RoChecklistType = ?,
                RoChecklistTypeLastUpdatedUserID = ?
                WHERE RoChecklistID = ?";
        $qry = $this->db->query($sql, [$type, $userId,  $id]);
        if (!$qry) {
            $this->sys_error_db("Error update name", $this->db);
            $this->db->trans_rollback();
            exit;
        }

        $sql = "UPDATE ro_checklist_map SET 
                    RoChecklistMapIsActive = 'N',
                    RoChecklistMapDeletedUserID = ?, 
                    RoChecklistMapDeleted = NOW()
                    WHERE RoChecklistMapRoChecklistID = ?
                    AND RoChecklistMapIsActive = 'Y'
                   
                ";
        $qry = $this->db->query($sql, [$userId, $id]);
        if (!$qry) {
            $this->sys_error_db("Error detail detail mapping", $this->db);
            $this->db->trans_rollback();
            exit;
        }


        $this->db->trans_commit();
        $this->sys_ok('Success');
    }
    public function delete()
    {
        $this->db->trans_begin();
        if (!$this->isLogin) {
            $this->sys_error("Invalid Token");
        }
        $prm = $this->sys_input;
        $user = $this->sys_user;
        $userId = $this->sys_user["M_UserID"];
        $id = $prm["id"];
        // $type = $prm["type"];



        $sqlCek = "UPDATE ro_checklist SET
                RoChecklistIsActive = 'N',
                RoChecklistTypeDeleted = NOW(),
                RoChecklistTypeDeletedUserID = ?
                WHERE RoChecklistID = ?";
        $qry = $this->db->query($sqlCek, [$userId, $id]);
        if (!$qry) {
            $this->sys_error_db("Error update name", $this->db);
            $this->db->trans_rollback();
            exit;
        }

        $sql = "UPDATE ro_checklist_map SET 
                    RoChecklistMapIsActive = 'N',
                    RoChecklistMapDeletedUserID = ?, 
                    RoChecklistMapDeleted = NOW()
                    WHERE RoChecklistMapRoChecklistID = ?
                    AND RoChecklistMapIsActive = 'Y'
                   
                ";
        $qry = $this->db->query($sql, [$userId, $id]);
        if (!$qry) {
            $this->sys_error_db("Error detail detail mapping", $this->db);
            $this->db->trans_rollback();
            exit;
        }


        $this->db->trans_commit();
        $this->sys_ok('Success');
    }
    public function deleteItem()
    {
        if (!$this->isLogin) {
            $this->sys_error("Invalid Token");
        }
        $prm = $this->sys_input;
        $user = $this->sys_user;
        $userId = $this->sys_user["M_UserID"];
        $id = $prm["id"];
        $sql = "UPDATE ro_checklist_map SET 
                    RoChecklistMapIsActive = 'N',
                    RoChecklistMapDeletedUserID = ?, 
                    RoChecklistMapDeleted = NOW()
                    WHERE RoChecklistMapID = ?
                   
                ";
        $qry = $this->db->query($sql, [$userId, $id]);
        if (!$qry) {
            $this->sys_error_db("Error detail detail mapping", $this->db);
            $this->db->trans_rollback();
            exit;
        }
        $this->sys_ok('Success');
    }
}
