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

    function index()
    {
        echo "SUPPLIER API";
    }

    function search()
    {
        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 = '%%';
                }
            }

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

            $sql_count  = "SELECT count(*) as total
                    FROM supplier
                    WHERE SupplierIsActive = 'Y'
                    AND (SupplierCode LIKE ? OR SupplierName LIKE ?)";
            $qry_count = $this->db->query($sql_count, [$search, $search]);
            $tot_count = 0;
            $tot_page = 0;
            if ($qry_count) {
                $tot_count = $qry_count->result_array()[0]["total"];
                $tot_page = ceil($tot_count / $number_limit);
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("supplier count error", $this->db);
                exit;
            }

            $sql = "SELECT SupplierID,
                SupplierCode,
                SupplierName,
                SupplierIsPpn,
                SupplierIsPph,
                SupplierPpnPct,
                SupplierPphPct
                FROM supplier
                WHERE SupplierIsActive = 'Y'
                AND (SupplierCode LIKE ? OR SupplierName LIKE ?)
                ORDER BY SupplierID DESC
                LIMIT ? OFFSET ?";
            $qry = $this->db->query($sql, [$search, $search, $number_limit, $number_offset]);
            if ($qry) {
                $rows = $qry->result_array();
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("supplier list error", $this->db);
                exit;
            }

            $result = array(
                "total_page" => $tot_page,
                "total_filter" => $tot_count,
                "records" => $rows,
                "sql" => $this->db->last_query()
            );
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

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

            // Get supplier ID from parameters
            if (!isset($prm['supplier_id'])) {
                $this->sys_error("Supplier ID is required");
                exit;
            }
            $supplier_id = $prm['supplier_id'];

            // Handle search parameter
            $search = "";
            if (isset($prm['search'])) {
                $search = trim($prm["search"]);
                if ($search != "") {
                    $search = '%' . $prm['search'] . '%';
                } else {
                    $search = '%%';
                }
            }

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

            // Count total records
            $sql_count = "SELECT COUNT(*) as total
                    FROM supplier_price sp
                    JOIN m_item mi ON sp.SupplierPriceM_ItemID = mi.M_ItemID
                    LEFT JOIN itemunit iu ON sp.SupplierPriceItemUnitID = iu.ItemUnitID
                    WHERE sp.SupplierPriceIsActive = 'Y'
                    AND sp.SupplierPriceSupplierID = ?
                    AND (mi.M_ItemCode LIKE ? OR mi.M_ItemDesc LIKE ?)";

            $qry_count = $this->db->query($sql_count, [$supplier_id, $search, $search]);
            $tot_count = 0;
            $tot_page = 0;
            if ($qry_count) {
                $tot_count = $qry_count->result_array()[0]["total"];
                $tot_page = ceil($tot_count / $number_limit);
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("supplier price count error", $this->db);
                exit;
            }

            // Get detailed records
            $sql = "SELECT 
                    sp.SupplierPriceID,
                    sp.SupplierPriceSupplierID,
                    mi.M_ItemID,
                    mi.M_ItemCode,
                    mi.M_ItemDesc,
                    iu.ItemUnitID,
                    iu.ItemUnitCode,
                    iu.ItemUnitName,
                    sp.SupplierPricePrice,
                    sp.SupplierPriceCreated,
                    sp.SupplierPriceLastUpdated
                    FROM supplier_price sp
                    JOIN m_item mi ON sp.SupplierPriceM_ItemID = mi.M_ItemID
                    LEFT JOIN itemunit iu ON sp.SupplierPriceItemUnitID = iu.ItemUnitID
                    WHERE sp.SupplierPriceIsActive = 'Y'
                    AND sp.SupplierPriceSupplierID = ?
                    AND (mi.M_ItemCode LIKE ? OR mi.M_ItemDesc LIKE ?)
                    ORDER BY sp.SupplierPriceID DESC
                    LIMIT ? OFFSET ?";

            $qry = $this->db->query($sql, [$supplier_id, $search, $search, $number_limit, $number_offset]);
            if ($qry) {
                $rows = $qry->result_array();
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("supplier price list error", $this->db);
                exit;
            }

            $result = array(
                "total_page" => $tot_page,
                "total_filter" => $tot_count,
                "records" => $rows,
                "sql" => $this->db->last_query()
            );
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    function save()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }
            $this->db->trans_begin();
            $prm = $this->sys_input;
            $userId = $this->sys_user["M_UserID"];

            // Validate required parameters
            if (!isset($prm['nameSupplier']) || trim($prm['nameSupplier']) == "") {
                $this->sys_error("Supplier name is required");
                exit;
            }

            $nameSupplier = "";
            if (isset($prm['nameSupplier'])) {
                $nameSupplier = trim($prm['nameSupplier']);
            }
            $isPpn = "";
            if (isset($prm['isPpn'])) {
                $isPpn = trim($prm['isPpn']);
            }
            $isPph = "";
            if (isset($prm['isPph'])) {
                $isPph = trim($prm['isPph']);
            }
            $PpnPercent = "";
            if (isset($prm['PpnPercent'])) {
                $PpnPercent = trim($prm['PpnPercent']);
            }
            $PphPercent = "";
            if (isset($prm['PphPercent'])) {
                $PphPercent = trim($prm['PphPercent']);
            }

            $codeSql = "SELECT `fn_numbering`('S') as codeSp";
            $exec = $this->db->query($codeSql, []);
            $codeSupplier = "";
            if (!$exec) {
                $this->db->trans_rollback();
                $this->sys_error_db("generate code error", $this->db);
                exit;
            } else {
                $codeSupplier = $exec->result_array()[0]["codeSp"];
            }

            // Check for existing supplier with same name
            $sql_check = "SELECT COUNT(*) as total FROM supplier 
                         WHERE SupplierName = ? AND SupplierIsActive = 'Y'";
            $qry_check = $this->db->query($sql_check, [$nameSupplier]);

            if ($qry_check && $qry_check->result_array()[0]['total'] > 0) {
                $this->sys_error("Nama supplier sudah ada");
                exit;
            }

            $sql = "INSERT INTO supplier(
                    SupplierCode,
                    SupplierName,
                    SupplierIsPpn,
                    SupplierIsPph,
                    SupplierPpnPct,
                    SupplierPphPct,
                    SupplierIsActive,
                    SupplierCreatedUserID,
                    SupplierCreated
                    ) VALUES(?,?,?,?,?,?,'Y',?,NOW())";
            $qry = $this->db->query($sql, [
                $codeSupplier,
                $nameSupplier,
                $isPpn,
                $isPph,
                $PpnPercent,
                $PphPercent,
                $userId
            ]);

            if (!$qry) {
                $this->db->trans_rollback();
                $this->sys_error_db("supplier insert error", $this->db);
                exit;
            }

            $this->db->trans_commit();

            $newInsert = "SELECT * FROM supplier WHERE SupplierCode = '{$codeSupplier}' AND SupplierIsActive = 'Y'";
            $records = $this->db->query($newInsert, [])->result_array();

            $this->sys_ok(array(
                "total" => 1,
                "records" => $records
            ));
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    function update()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }
            $this->db->trans_begin();
            $prm = $this->sys_input;
            $userId = $this->sys_user["M_UserID"];

            // Validate required parameters
            if (!isset($prm['nameSupplier']) || trim($prm['nameSupplier']) == "") {
                $this->sys_error("Supplier name is required");
                exit;
            }

            $nameSupplier = "";
            if (isset($prm['nameSupplier'])) {
                $nameSupplier = trim($prm['nameSupplier']);
            }
            $isPpn = "";
            if (isset($prm['isPpn'])) {
                $isPpn = trim($prm['isPpn']);
            }
            $isPph = "";
            if (isset($prm['isPph'])) {
                $isPph = trim($prm['isPph']);
            }
            $PpnPercent = "";
            if (isset($prm['PpnPercent'])) {
                $PpnPercent = trim($prm['PpnPercent']);
            }
            $PphPercent = "";
            if (isset($prm['PphPercent'])) {
                $PphPercent = trim($prm['PphPercent']);
            }
            $supplier_id = "";
            if (isset($prm['supplier_id'])) {
                $supplier_id = trim($prm['supplier_id']);
            }

            $sql = "UPDATE supplier SET
                    SupplierName = ?,
                    SupplierIsPpn = ?,
                    SupplierIsPph = ?,
                    SupplierPpnPct = ?,
                    SupplierPphPct = ?,
                    SupplierLastUpdatedUserID = ?,
                    SupplierLastUpdated = NOW()
                    WHERE SupplierID = ?";
            $qry = $this->db->query($sql, [
                $nameSupplier,
                $isPpn,
                $isPph,
                $PpnPercent,
                $PphPercent,
                $userId,
                $supplier_id
            ]);

            if (!$qry) {
                $this->db->trans_rollback();
                $this->sys_error_db("supplier update error", $this->db);
                exit;
            }

            $this->db->trans_commit();

            $newInsert = "SELECT * FROM supplier WHERE SupplierID = {$supplier_id} AND SupplierIsActive = 'Y'";
            $records = $this->db->query($newInsert, [])->result_array();

            $this->sys_ok(array(
                "total" => 1,
                "records" => $records
            ));
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    function deletesupplier()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }
            $this->db->trans_begin();
            $prm = $this->sys_input;
            $userId = $this->sys_user["M_UserID"];

            $supplier_id = "";
            if (isset($prm['supplier_id'])) {
                $supplier_id = trim($prm['supplier_id']);
            }

            $sql = "UPDATE supplier SET
                    SupplierIsActive = 'N',
                    SupplierDeletedUserID = ?,
                    SupplierDeleted = NOW()
                    WHERE SupplierID = ?";
            $qry = $this->db->query($sql, [
                $userId,
                $supplier_id
            ]);

            if (!$qry) {
                $this->db->trans_rollback();
                $this->sys_error_db("supplier update error", $this->db);
                exit;
            }

            $sql_price = "UPDATE supplier_price SET
                    SupplierPriceIsActive = 'N',
                    SupplierPriceUserID = ?,
                    SupplierPriceLastUpdated = NOW()
                    WHERE SupplierPriceSupplierID = ?";
            $qry_price = $this->db->query($sql_price, [
                $userId,
                $supplier_id
            ]);

            if (!$qry_price) {
                $this->db->trans_rollback();
                $this->sys_error_db("supplier price update error", $this->db);
                exit;
            }

            $this->db->trans_commit();

            $this->sys_ok(array(
                "total" => 1,
                "records" => array("xId" => $prm["supplier_id"])
            ));
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

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

            $search = "";
            if (isset($payload["search"])) {
                $search = trim($payload["search"]);
                if ($search != "") {
                    $search = "%" . $payload["search"] . "%";
                } else {
                    $search = "%%";
                }
            }

            $number_limit = 10;
            $sql = "SELECT 
                    M_ItemID,
                    M_ItemCode,
                    IF(M_ItemDesc = '', '-', M_ItemDesc) AS M_ItemDesc
                    FROM m_item
                    WHERE (M_ItemCode LIKE ? OR M_ItemDesc LIKE ?)
                    ORDER BY M_ItemDesc ASC
                    LIMIT ?";
            $qry = $this->db->query($sql, array($search, $search, $number_limit));
            if ($qry) {
                $rows = $qry->result_array();
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select item error", $this->db);
                exit;
            }

            $result = array(
                "records" => $rows,
                "total_filter" => sizeof($rows)
            );
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

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

            $prm = $this->sys_input;
            $search = isset($prm["search"]) ? $prm["search"] : "";
            $itemID = $prm["itemID"];

            $sql = "SELECT 
                    ItemUnitID,
                    ItemUnitCode,
                    ItemUnitName,
                    ItemUnitCreated,
                    ItemUnitLastUpdated,
                    ItemUnitIsActive,
                    ItemUnitUserID
                FROM itemunit 
                JOIN itemunitmap ON ItemUnitMapItemUnitID = ItemUnitID
                AND ItemUnitMapM_ItemID = {$itemID}
                AND ItemUnitMapIsActive = 'Y'
                AND ItemUnitMapIsPurchase = 'Y'
                WHERE ItemUnitIsActive = 'Y'
                AND ItemUnitName LIKE '%$search%'
                ORDER BY ItemUnitName ASC";

            $query = $this->db->query($sql);

            if (!$query) {
                $this->sys_error_db("item unit list", $this->db);
                exit;
            }

            $rows = $query->result_array();

            $result = array(
                "records" => $rows,
                "sql" => $this->db->last_query()
            );

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

    function saveprice()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }
            $this->db->trans_begin();
            $prm = $this->sys_input;
            $userId = $this->sys_user["M_UserID"];

            // Validate required parameters
            if (!isset($prm['supplier_id']) || !isset($prm['item_id']) || !isset($prm['unit_id']) || !isset($prm['price'])) {
                $this->sys_error("All fields are required");
                exit;
            }

            $supplier_id = trim($prm['supplier_id']);
            $item_id = trim($prm['item_id']);
            $unit_id = trim($prm['unit_id']);
            $price = trim($prm['price']);

            // Check for existing supplier price with same item and unit
            $sql_check = "SELECT COUNT(*) as total 
                         FROM supplier_price 
                         WHERE SupplierPriceSupplierID = ? 
                         AND SupplierPriceM_ItemID = ?
                         AND SupplierPriceItemUnitID = ?
                         AND SupplierPriceIsActive = 'Y'";
            $qry_check = $this->db->query($sql_check, [$supplier_id, $item_id, $unit_id]);

            if ($qry_check && $qry_check->result_array()[0]['total'] > 0) {
                $this->sys_error("Price for this item and unit already exists");
                exit;
            }

            $sql = "INSERT INTO supplier_price(
                    SupplierPriceSupplierID,
                    SupplierPriceM_ItemID,
                    SupplierPriceItemUnitID,
                    SupplierPricePrice,
                    SupplierPriceIsActive,
                    SupplierPriceUserID,
                    SupplierPriceCreated
                    ) VALUES(?,?,?,?,'Y',?,NOW())";

            $qry = $this->db->query($sql, [
                $supplier_id,
                $item_id,
                $unit_id,
                $price,
                $userId
            ]);

            if (!$qry) {
                $this->db->trans_rollback();
                $this->sys_error_db("supplier price insert error", $this->db);
                exit;
            }

            $this->db->trans_commit();

            $newInsert = "SELECT sp.*, mi.M_ItemCode, mi.M_ItemDesc, iu.ItemUnitCode, iu.ItemUnitName 
                          FROM supplier_price sp
                          JOIN m_item mi ON sp.SupplierPriceM_ItemID = mi.M_ItemID
                          JOIN itemunit iu ON sp.SupplierPriceItemUnitID = iu.ItemUnitID
                          WHERE sp.SupplierPriceID = LAST_INSERT_ID()";
            $records = $this->db->query($newInsert)->result_array();

            $this->sys_ok(array(
                "total" => 1,
                "records" => $records
            ));
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    function updateprice()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }
            $this->db->trans_begin();
            $prm = $this->sys_input;
            $userId = $this->sys_user["M_UserID"];

            // Validate required parameters
            if (!isset($prm['supplier_price_id']) || !isset($prm['item_id']) || !isset($prm['unit_id']) || !isset($prm['price'])) {
                $this->sys_error("All fields are required");
                exit;
            }

            $supplier_id = trim($prm['supplier_id']);
            $supplier_price_id = trim($prm['supplier_price_id']);
            $item_id = trim($prm['item_id']);
            $unit_id = trim($prm['unit_id']);
            $price = trim($prm['price']);

            // Check for existing supplier price with same item and unit
            $sql_check = "SELECT COUNT(*) as total 
                         FROM supplier_price 
                         WHERE SupplierPriceSupplierID = ? 
                         AND SupplierPriceM_ItemID = ?
                         AND SupplierPriceItemUnitID = ?
                         AND SupplierPriceIsActive = 'Y'
                         AND SupplierPriceID != ?";
            $qry_check = $this->db->query($sql_check, [$supplier_id, $item_id, $unit_id, $supplier_price_id]);

            if ($qry_check && $qry_check->result_array()[0]['total'] > 0) {
                $this->sys_error("Price for this item and unit already exists");
                exit;
            }

            $sql = "UPDATE supplier_price SET
                    SupplierPriceM_ItemID = ?,
                    SupplierPriceItemUnitID = ?,
                    SupplierPricePrice = ?,
                    SupplierPriceUserID = ?,
                    SupplierPriceLastUpdated = NOW()
                    WHERE SupplierPriceID = ?";

            $qry = $this->db->query($sql, [
                $item_id,
                $unit_id,
                $price,
                $userId,
                $supplier_price_id
            ]);

            if (!$qry) {
                $this->db->trans_rollback();
                $this->sys_error_db("supplier price insert error", $this->db);
                exit;
            }

            $this->db->trans_commit();

            $newInsert = "SELECT sp.*, mi.M_ItemCode, mi.M_ItemDesc, iu.ItemUnitCode, iu.ItemUnitName 
                          FROM supplier_price sp
                          JOIN m_item mi ON sp.SupplierPriceM_ItemID = mi.M_ItemID
                          JOIN itemunit iu ON sp.SupplierPriceItemUnitID = iu.ItemUnitID
                          WHERE sp.SupplierPriceID = {$supplier_price_id}";
            $records = $this->db->query($newInsert)->result_array();

            $this->sys_ok(array(
                "total" => 1,
                "records" => $records
            ));
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    function deleteprice()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }
            $this->db->trans_begin();
            $prm = $this->sys_input;
            $userId = $this->sys_user["M_UserID"];

            // Validate required parameters
            if (!isset($prm['supplier_price_id'])) {
                $this->sys_error("All fields are required");
                exit;
            }

            $supplier_id = trim($prm['supplier_id']);
            $supplier_price_id = trim($prm['supplier_price_id']);
            $item_id = trim($prm['item_id']);
            $unit_id = trim($prm['unit_id']);
            $price = trim($prm['price']);

            $sql = "UPDATE supplier_price SET
                    SupplierPriceIsActive = 'N',
                    SupplierPriceUserID = ?,
                    SupplierPriceLastUpdated = NOW()
                    WHERE SupplierPriceID = ?";

            $qry = $this->db->query($sql, [
                $userId,
                $supplier_price_id
            ]);

            if (!$qry) {
                $this->db->trans_rollback();
                $this->sys_error_db("supplier price delete error", $this->db);
                exit;
            }

            $this->db->trans_commit();
            $this->sys_ok(array(
                "total" => 1,
                "qry" => $this->db->last_query()
            ));
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }
}
