<?php
class Itemregional extends MY_Controller{

    var $db_onedev;
    public function index()
    {
        echo "AUTH API";
    }

    public function __construct()
    {
        parent::__construct();
        $this->db_onedev = $this->load->database("onedev", true);
    }

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

        $prm = $this->sys_input;
        $search = isset($prm["search"]) ? trim($prm["search"]) : '';
        $search = ($search !== '') ? "%$search%" : "%%";

        $number_limit = 10;
        $number_offset = ($prm["current_page"] > 0) ? ($prm["current_page"] - 1) * $number_limit : 0;

        $sql = "SELECT 
    M_ItemID,
    M_ItemCode,    
    M_ItemDesc,    
    M_ItemItem_CategoryID,
    M_ItemInventoryCode,
    M_ItemNat_GroupID,    
    M_ItemNat_SubGroupID,    
    M_ItemFa_ClassID,

    -- Data item regional
    M_ItemRegionalID,
    M_ItemRegionalS_RegionalID,
    M_ItemRegionalMinQty,
    M_ItemRegionalItemUnitID,
    
    -- Data Satuan
    ItemUnitID,	
    ItemUnitCode,	
    ItemUnitName,

    -- Regional
    S_RegionalID,
    S_RegionalName


FROM m_itemregional
JOIN m_item ON M_ItemID = M_ItemRegionalM_ItemID
JOIN s_regional ON S_RegionalID = M_ItemRegionalS_RegionalID
JOIN itemunit ON ItemUnitID = M_ItemRegionalItemUnitID


WHERE M_ItemRegionalIsActive = 'Y'
  AND (
      M_ItemDesc LIKE CONCAT('%', '$search', '%')
      OR S_RegionalName LIKE CONCAT('%', '$search', '%')
  )
ORDER BY M_ItemRegionalID DESC";

        $sql_total = "SELECT count(*) as total FROM ($sql) as x";
        $qry_total = $this->db_onedev->query($sql_total);

        $totalCount = 0;
        $totalPage = 0;
        if ($qry_total) {
            $totalCount = $qry_total->result_array()[0]["total"];
            $totalPage = ceil($totalCount / $number_limit);
        } else {
            $this->sys_error_db("select m_itemregional count error", $this->db_onedev);;
            exit;
        }

        $sql_select = $sql . " LIMIT $number_limit OFFSET $number_offset";
        
        $qry = $this->db_onedev->query($sql_select);
        if ($qry) {
            $rows = $qry->result_array();
        } else {
            $this->db_onedev->trans_rollback();
            $this->sys_error_db("select m_itemregional error", $this->db_onedev);
            exit;
        }

        $response = [
            "total" => $totalPage,
            "totalFilter" => $totalCount,
            "records" => $rows,
            "sql" => $this->db_onedev->last_query()
        ];
        
        $this->sys_ok($response);
    } catch (Exception $exc) {
        $this->sys_error($exc->getMessage());
    }
}

    
    
    function getItem()
    {
        $prm = $this->sys_input;
        try {
            if (! $this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

            $search = $prm['search'];
            // $where_search = "%%";
            $where_search_desc = '%'.$search.'%';
            $where_search_acc = "$search%";

            $sql = "SELECT 
                M_ItemID,
                M_ItemCode,	
                M_ItemDesc,	
                M_ItemItem_CategoryID,
                M_ItemInventoryCode,
                M_ItemNat_GroupID,	
                M_ItemNat_SubGroupID,	
                M_ItemM_InventarisGolID,	
                M_ItemPurchaseUOM,
                M_ItemBaseUOM,
                M_ItemItem_UnitID
            FROM m_item
            WHERE M_ItemIsActive = 'Y'
            AND 
            (
                M_ItemDesc LIKE '$where_search_desc'
                OR M_ItemCode LIKE '$where_search_acc'
            )";

            // echo $sql;
            // die();
            $qry = $this->db_onedev->query($sql, array());

        if (!$qry) {
            // $this->db->trans_rollback();
            $this->sys_error_db("Error get coa pendapatan");
            exit;
        }
            $result = $qry->result_array();
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }
    
    function getRegional()
    {
        $prm = $this->sys_input;
        try {
            if (! $this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

            $search = $prm['search'];
            // $where_search = "%%";
            $where_search_desc = '%'.$search.'%';
            $where_search_acc = "$search%";

            $sql = "SELECT 
                S_RegionalID,
                S_RegionalName
            FROM s_regional
            WHERE S_RegionalIsActive = 'Y'
            AND 
            S_RegionalName LIKE '$where_search_acc'";

            // echo $sql;
            // die();
            $qry = $this->db_onedev->query($sql, array());

        if (!$qry) {
            // $this->db->trans_rollback();
            $this->sys_error_db("Error get coa pendapatan");
            exit;
        }
            $result = $qry->result_array();
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    function getUnit()
    {
        $prm = $this->sys_input;
        try {
            if (! $this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

            $search = $prm['search'];
            // $where_search = "%%";
            $where_search_desc = '%'.$search.'%';
            $where_search_acc = "$search%";

            $sql = "SELECT 
                ItemUnitID,
                ItemUnitCode,	
                ItemUnitName
            FROM itemunit
            WHERE ItemUnitIsActive = 'Y'
            AND 
            (
                ItemUnitName LIKE '$where_search_desc'
                OR ItemUnitCode LIKE '$where_search_acc'
            )";

            // echo $sql;
            // die();
            $qry = $this->db_onedev->query($sql, array());

        if (!$qry) {
            // $this->db->trans_rollback();
            $this->sys_error_db("Error get unit");
            exit;
        }
            $result = $qry->result_array();
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    // addData
    function addData()
{
    $prm = $this->sys_input;
    try {
        if (! $this->isLogin) {
            $this->sys_error("Invalid Token");
            exit;
        }

        $this->db_onedev->trans_begin();
        $userid = $this->sys_user['M_UserID'];

        

        // Extract input parameters
        $M_ItemRegionalS_RegionalID = isset($prm['M_ItemRegionalS_RegionalID']) ? $prm['M_ItemRegionalS_RegionalID'] : 0;
        $M_ItemRegionalM_ItemID = isset($prm['M_ItemRegionalM_ItemID']) ? $prm['M_ItemRegionalM_ItemID'] : 0;
        $M_ItemRegionalQty = isset($prm['M_ItemRegionalQty']) ? $prm['M_ItemRegionalQty'] : 0;
        $M_ItemRegionalItemUnitID = isset($prm['M_ItemRegionalItemUnitID']) ? $prm['M_ItemRegionalItemUnitID'] : 0;
        
        // Construct SQL query
        $sql = "INSERT INTO m_itemregional (
                    M_ItemRegionalM_ItemID,
                    M_ItemRegionalS_RegionalID,
                    M_ItemRegionalMinQty,	
                    M_ItemRegionalItemUnitID,
                    M_ItemRegionalUserID,	
                    M_ItemRegionalCreated,	
                    M_ItemRegionalLastUpdated
                ) VALUES (
                    '$M_ItemRegionalM_ItemID',
                    '$M_ItemRegionalS_RegionalID',
                    '$M_ItemRegionalQty',
                    '$M_ItemRegionalItemUnitID',
                    '$userid',
                    NOW(),
                    NOW()
                )";

        // Execute query
        $qry = $this->db_onedev->query($sql);
        if (!$qry) {
            $this->db_onedev->trans_rollback();
            $error = array(
                "message" => $this->db_onedev->error()["message"],
                "sql" => $this->db_onedev->last_query()
            );
            $this->sys_error_db($error, $this->db_onedev);
            exit;
        }

        $this->db_onedev->trans_commit();
        $result = array("total" => 1);
        $this->sys_ok($result);

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


    // get_by_id
    function get_by_id()
    {
        $prm = $this->sys_input;
        try {
            if (! $this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

            // m_itemregional
            $M_ItemRegionalID = isset($prm['M_ItemRegionalID']) ? $prm['M_ItemRegionalID'] : 0;

            $sql_m = "SELECT * FROM m_itemregional where M_ItemRegionalID = '$M_ItemRegionalID'";

            $qry_m = $this->db_onedev->query($sql_m);
            if (!$qry_m) {
                $error = array(
                    "message" => $this->db_onedev->error()["message"],
                    "sql" => $this->db_onedev->last_query()
                );
                $this->sys_error_db($error, $this->db_onedev);
                exit;
            }

            $rows_m = $qry_m->result_array();

            // coa start
            $M_ItemRegionalCoaID = isset($prm['M_ItemRegionalCoaID']) ? $prm['M_ItemRegionalCoaID'] : 0;
            $sql_u = "SELECT * FROM coa where coaID = '$M_ItemRegionalCoaID'
            AND coaIsInput = 'Y' 
            AND coaIsActive = 'Y'
            ";

            $qry_u = $this->db_onedev->query($sql_u);
            if (!$qry_u) {
                $error = array(
                    "message" => $this->db_onedev->error()["message"],
                    "sql" => $this->db_onedev->last_query()
                );
                $this->sys_error_db($error, $this->db_onedev);
                exit;
            }

            $rows_u = $qry_u->result_array();

            // empty $rows_u
            if (empty($rows_u)) {
                $rows_u = [[
                    "coaID"                  => 0,
                    "coaAccountNo"           => '',
                    "coaDescription"         => '',
                    "coaSubDescription"      => '',
                    "coaAccountType"         => '',
                    "coaSpecialAccountType"  => '',
                    "coaIsInput"             => 'N',
                    "coaReportSchedule"      => '',
                    "coaCurrencyCode"        => '',
                    "coaCashFlowCategory"    => '',
                    "coaCreated"             => '',
                    "coaLastUpdated"         => '',
                    "coaIsActive"            => 'Y',
                    "coaLevel"               => 1
                ]];
            }

            // coa end

            // accum depre start
            $M_ItemRegionalAccumDepreCoaID = $prm['M_ItemRegionalAccumDepreCoaID'];
            $sql_h = "SELECT * FROM coa where coaID = '$M_ItemRegionalAccumDepreCoaID'
            AND coaIsInput = 'Y' 
            AND coaIsActive = 'Y'";

            $qry_h = $this->db_onedev->query($sql_h);
            if (!$qry_h) {
                $error = array(
                    "message" => $this->db_onedev->error()["message"],
                    "sql" => $this->db_onedev->last_query()
                );
                $this->sys_error_db($error, $this->db_onedev);
                exit;
            }

            $rows_h = $qry_h->result_array();
            // empty $rows_h
            if (empty($rows_h)) {
                $rows_h = [[
                    "coaID"                  => 0,
                    "coaAccountNo"           => '',
                    "coaDescription"         => '',
                    "coaSubDescription"      => '',
                    "coaAccountType"         => '',
                    "coaSpecialAccountType"  => '',
                    "coaIsInput"             => 'N',
                    "coaReportSchedule"      => '',
                    "coaCurrencyCode"        => '',
                    "coaCashFlowCategory"    => '',
                    "coaCreated"             => '',
                    "coaLastUpdated"         => '',
                    "coaIsActive"            => 'Y',
                    "coaLevel"               => 1
                ]];
            }
            // accum depre end

            

            $response = [
                "record_m_itemregional" => $rows_m,
                "records_coa" => $rows_u,
                "records_accum_depre" => $rows_h,
                "sql" => $this->db_onedev->last_query()
            ];
            
            $this->sys_ok($response);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    // editData
    function editData()
    {
        $prm = $this->sys_input;
        try {
            if (! $this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }
    
            $this->db_onedev->trans_begin();
            $userid = $this->sys_user['M_UserID'];
    
            $M_ItemRegionalID = $prm['M_ItemRegionalID'];
            $M_ItemRegionalS_RegionalID = isset($prm['M_ItemRegionalS_RegionalID']) ? $prm['M_ItemRegionalS_RegionalID'] : 0;
        $M_ItemRegionalM_ItemID = isset($prm['M_ItemRegionalM_ItemID']) ? $prm['M_ItemRegionalM_ItemID'] : 0;
        $M_ItemRegionalQty = isset($prm['M_ItemRegionalQty']) ? $prm['M_ItemRegionalQty'] : 0;
        $M_ItemRegionalItemUnitID = isset($prm['M_ItemRegionalItemUnitID']) ? $prm['M_ItemRegionalItemUnitID'] : 0;
        
            $sql = "UPDATE m_itemregional SET 
                    M_ItemRegionalS_RegionalID = '{$M_ItemRegionalS_RegionalID}',
                    M_ItemRegionalM_ItemID = '{$M_ItemRegionalM_ItemID}',
                    M_ItemRegionalMinQty = '{$M_ItemRegionalQty}',
                    M_ItemRegionalItemUnitID = '{$M_ItemRegionalItemUnitID}',
                    M_ItemRegionalUserID = '{$userid}',
                    M_ItemRegionalLastUpdated = now()
                WHERE M_ItemRegionalID = '$M_ItemRegionalID'
            ";
    
    
            // echo $sql;
    
            $qry = $this->db_onedev->query($sql);
            if (!$qry) {
                $this->db_onedev->trans_rollback();
                $error = array(
                    "message" => $this->db_onedev->error()["message"],
                    // "sql" => $last_qry
                );
                $this->sys_error_db($error, $this->db_onedev);
                exit;
            }
    
            $this->db_onedev->trans_commit();
            $result = array("total" => 1);
            $this->sys_ok($result);
    
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    // deleteData
    function deleteData()
    {
        $prm = $this->sys_input;
        try {
            if (! $this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

            $this->db_onedev->trans_begin();
            $userid = $this->sys_user['M_UserID'];
    
            $M_ItemRegionalID = $prm['M_ItemRegionalID'];


            $sql = "UPDATE m_itemregional 
            SET 
                M_ItemRegionalIsActive = 'N',
                M_ItemRegionalLastUpdated = now(),
                M_ItemRegionalUserID = '$userid'
            WHERE M_ItemRegionalID = '$M_ItemRegionalID'";

            $qry = $this->db_onedev->query($sql);
            if (!$qry) {
                $this->db_onedev->trans_rollback();
                $error = array(
                    "message" => $this->db_onedev->error()["message"],
                    "sql" => $last_qry
                );
                $this->sys_error_db($error, $this->db_onedev);
                exit;
            }

            $this->db_onedev->trans_commit();
            $result = array("total" => 1);
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }
}
?>