<?php

use phpDocumentor\Reflection\Types\This;

class Itemusagev3 extends MY_Controller
{
    var $db;
    public function index()
    {
        echo "Item Usage API";
    }

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

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

            // $userId = $this->sys_user["M_UserID"];
            $prm = $this->sys_input;
            $userId = $prm["userId"];

            $rows = [];

            $query = "SELECT DISTINCT
                      DivisionID,
                      DivisionCode,
                      DivisionName
                      FROM division
                      WHERE DivisionIsActive = 'Y'
                      ORDER BY DivisionID ASC
                      
                      ";
            $exec = $this->db->query($query);
            if ($exec) {
                $rows = $exec->result_array();
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("select division", $this->db);
                exit;
            }

            $sql = "SELECT DISTINCT
                      DivisionID,
                      DivisionCode,
                      DivisionName
                    FROM division 
                    JOIN m_userdivision ON M_UserDivisionDivisionID = DivisionID AND M_UserDivisionM_UserID = ?
                    WHERE DivisionIsActive = 'Y'
                    ORDER BY M_UserDivisionID DESC
                    LIMIT 1";
            $exec = $this->db->query($sql, [$userId]);
            if ($exec) {
                $row = $exec->result_array();
            } else {
                $this->sys_error_db("select division by user", $this->db);
                exit;
            }
            $result = array(
                "records" => $rows,
                "selected" => $row
            );

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

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

            // $userId = $this->sys_user["M_UserID"];
            $prm = $this->sys_input;
            $divisionID = $prm["divisionID"];

            $search = $prm["search"];
            if (empty($search)) {
                $search = "%";
            } else {
                $search = "%" . $search . "%";
            }

            // $filter = "";
            // if ($divisionID != "0") {
            //     $filter = " AND ItemUsageDivisionID = {$divisionID}";
            // }

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

            $sql_total = "SELECT COUNT(*) AS total
                    FROM item_usage
                    JOIN division ON ItemUsageDivisionID = DivisionID
                    AND DivisionIsActive = 'Y'
                    JOIN m_item ON ItemUsageM_ItemID = M_ItemID
                    AND M_ItemIsActive = 'Y'
                    JOIN itemunit ON ItemUsageItemUnitID = ItemUnitID
                    AND ItemUnitIsActive = 'Y'
                    JOIN s_regional ON ItemUsageS_RegionalID= S_RegionalID AND S_RegionalIsActive = 'Y'
                    LEFT JOIN m_branch ON ItemUsageM_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y'
                    WHERE ItemUsageIsActive = 'Y'
                    AND ItemUsageDivisionID = ?
                    AND (M_ItemDesc LIKE ?)";
            $qry_total = $this->db->query($sql_total, [$divisionID, $search]);

            $tot_count = 0;
            $tot_page = 0;
            if ($qry_total) {
                $tot_count = $qry_total->result_array()[0]["total"];
                $tot_page = ceil($tot_count / $number_limit);
            } else {
                $this->sys_error_db("Failed select item usage total", $this->db);
                exit;
            }

            $sql = "SELECT ItemUsageID,
                    ItemUsageQty,
                    ItemUsagePrice,
                    DivisionID,
                    DivisionCode,
                    DivisionName,
                    DivisionKodeSurat,
                    M_ItemID,
                    M_ItemCode,
                    M_ItemDesc,
                    ItemUnitID,
                    ItemUnitCode,
                    ItemUnitName,
                    S_RegionalID,
                    S_RegionalName,
                    M_BranchID,
                    M_BranchName,
                    '' as listItemUsed
                    FROM item_usage
                    JOIN division ON ItemUsageDivisionID = DivisionID
                    AND DivisionIsActive = 'Y'
                    JOIN m_item ON ItemUsageM_ItemID = M_ItemID
                    AND M_ItemIsActive = 'Y'
                    JOIN itemunit ON ItemUsageItemUnitID = ItemUnitID
                    AND ItemUnitIsActive = 'Y'
                    JOIN s_regional ON ItemUsageS_RegionalID= S_RegionalID AND S_RegionalIsActive = 'Y'
                    LEFT JOIN m_branch ON ItemUsageM_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y'
                    WHERE ItemUsageIsActive = 'Y'
                    AND ItemUsageDivisionID = ?
                    AND (M_ItemDesc LIKE ?)
                    ORDER BY ItemUsageID DESC
                    LIMIT ? OFFSET ?";
            $qry = $this->db->query($sql, [$divisionID, $search, $number_limit, $number_offset]);
            if ($qry) {
                $rows = $qry->result_array();
            } else {
                $this->sys_error_db("Failed select item usage", $this->db);
                exit;
            }



            foreach ($rows as $key => $value) {

                $sqldetail = "SELECT 
                        ItemUsageDetailID,
                        ItemUsageDetailItemUsageID,
                        ItemUsageDetailWarehouseID as WarehouseID,
                        ItemUsageDetailWarehouseName as WarehouseName,
                        ItemUsageDetailStockID as StockID,
                        ItemUsageDetailStockNumber as StockNumber,
                        ItemUsageDetailStockItemID as StockItemID,
                        ItemUsageDetailStockItemUnitID as StockItemUnitID,
                        ItemUsageDetailItemUnitCode as ItemUnitCode,
                        ItemUsageDetailItemUnitName as ItemUnitName,
                        ItemUsageDetailStockItemPrice as StockItemPrice,
                        ItemUsageDetailStockBatchNo as StockBatchNo,
                        ItemUsageDetailStockED as StockED,
                        ItemUsageDetailStockQty as StockQty,
                        ItemUsageDetailQtyReq as QtyReq,
                        0 as amountUsed
                        FROM item_usage_detail WHERE ItemUsageDetailIsActive = 'Y'
                        AND ItemUsageDetailItemUsageID = ?";
                $qrydetail = $this->db->query($sqldetail, [$value['ItemUsageID']]);
                if ($qrydetail) {
                    $batches = $qrydetail->result_array();
                } else {
                    $this->sys_error_db("Failed select item usage detail", $this->db);
                    exit;
                }

                // Hitung total StockQty
                $totalStockQtyReq = 0;
                foreach ($batches as $batch) {
                    $totalStockQtyReq += floatval($batch['QtyReq']);
                }

                $rows[$key]['TotalStockQtyReq'] = $totalStockQtyReq;

                $rows[$key]['ItemRequest'] = $batches;
            }

            $result = array(
                "toal_count" => $tot_count,
                "total_page" => $tot_page,
                "records" => $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;
            $itemUnitID = $prm["itemUnitID"];

            $sql = "SELECT 
                    uc.UnitConvertID,
                    uc.UnitConvertFromItemUnitID AS FromUnitID,
                    uf.ItemUnitName AS FromUnitName,
                    uc.UnitConvertToItemUnitID   AS ToUnitID,
                    ut.ItemUnitName AS ToUnitName,
                    uc.UnitConvertAmount
                FROM unitconvert uc
                JOIN itemunit uf ON uf.ItemUnitID = uc.UnitConvertFromItemUnitID
                JOIN itemunit ut ON ut.ItemUnitID = uc.UnitConvertToItemUnitID
                WHERE uc.UnitConvertIsActive = 'Y'
                  AND uc.UnitConvertFromItemUnitID = ?";
            $qry = $this->db->query($sql, [$itemUnitID]);

            $rows = $qry->result_array();
            // if ($qry && $qry->num_rows() > 0) {
            // } else {
            //     // fallback → ambil langsung dari itemunit kalau tidak ada konversi
            //     $sql2 = "SELECT 
            //             0 AS UnitConvertID,
            //             iu.ItemUnitID AS FromUnitID,
            //             iu.ItemUnitName AS FromUnitName,
            //             iu.ItemUnitID AS ToUnitID,
            //             iu.ItemUnitName AS ToUnitName,
            //             1 AS UnitConvertAmount
            //          FROM itemunit iu
            //          WHERE iu.ItemUnitID = ?";
            //     $qry2 = $this->db->query($sql2, [$itemUnitID]);
            //     $rows = $qry2->result_array();
            // }

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

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

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

            if ($itemId == "") {
                $this->sys_error("Invalid Item ID");
                exit;
            }

            $sql = "SELECT 
                    DISTINCT ItemUnitID as StockItemUnitID,
                    ItemUnitCode,
                    ItemUnitName
                    FROM itemunitmap 
                    JOIN itemunit ON ItemUnitID = ItemUnitMapItemUnitID AND ItemUnitIsActive = 'Y'
                    WHERE ItemUnitMapM_ItemID = ?
                    AND ItemUnitMapIsActive = 'Y'";
            $query = $this->db->query($sql, [$itemId]);

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

            $rows = $query->result_array();

            $result = array(
                "records" => $rows
            );

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

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

            $ItemUsageID = $prm["ItemUsageID"];
            $ItemRequest = $prm["ItemRequest"];
            $date = date('Y-m-d');

            $sqlnum = "SELECT `fn_numbering`('IU') as IUnumber";
            $qrynum = $this->db->query($sqlnum, []);
            $IUnumber = $qrynum->row()->IUnumber;

            foreach ($ItemRequest as $key => $value) {
                $amountUsed = intval($value['amountUsed']);

                // ambil amountUsed yang ada isinya maka lakukan insert
                if ($amountUsed > 0) {

                    // ambil data item_usage_detail dulu
                    $sqldetail = "SELECT 
                        ItemUsageDetailID,
                        ItemUsageDetailItemUsageID,
                        ItemUsageDetailWarehouseID as WarehouseID,
                        ItemUsageDetailWarehouseName as WarehouseName,
                        ItemUsageDetailStockID as StockID,
                        ItemUsageDetailStockNumber as StockNumber,
                        ItemUsageDetailStockItemID as StockItemID,
                        ItemUsageDetailStockItemUnitID as StockItemUnitID,
                        ItemUsageDetailItemUnitCode as ItemUnitCode,
                        ItemUsageDetailItemUnitName as ItemUnitName,
                        ItemUsageDetailStockItemPrice as StockItemPrice,
                        ItemUsageDetailStockBatchNo as StockBatchNo,
                        ItemUsageDetailStockED as StockED,
                        ItemUsageDetailStockQty as StockQty,
                        ItemUsageDetailQtyReq as QtyReq,
                        0 as amountUsed
                        FROM item_usage_detail WHERE ItemUsageDetailIsActive = 'Y'
                        AND ItemUsageDetailID = ?";
                    $qrydetail = $this->db->query($sqldetail, [$value['ItemUsageDetailID']]);
                    if ($qrydetail) {
                        $batches = $qrydetail->result_array();
                    } else {
                        $this->sys_error_db("Failed select item usage detail", $this->db);
                        exit;
                    }

                    foreach ($batches as $k => $batch) {
                        // cari batch yang sesuai StockID
                        if ($batch['StockID'] == $value['StockID']) {
                            $hargaBase  = doubleval($batch['StockItemPrice'] ?? 0);
                            $fromUnitID = intval($batch['StockItemUnitID']);
                            $toUnitID   = intval($value['StockItemUnitID']); // dari request

                            if ($fromUnitID == $toUnitID) {
                                // unit sama persis, tidak perlu konversi
                                $batches[$k]['QtyReq'] = floatval($batch['QtyReq']) - $amountUsed;
                                $batches[$k]['amountUsed'] = $amountUsed;
                                $batches[$k]['HargaPerUnit'] = $hargaBase;
                                $batches[$k]['TotalHarga'] = round($amountUsed * $hargaBase, 2);
                            } else if ($fromUnitID != $toUnitID) {
                                // unit beda, ambil konversi dari unitconvert
                                $resultAmountConvert = $this->getConvertAmount($fromUnitID, $toUnitID);

                                // konversi jumlah
                                $pemakaianBase = $amountUsed / $resultAmountConvert;
                                $batches[$k]['QtyReq'] = floatval($batch['QtyReq']) - $pemakaianBase;

                                // harga per unit kecil
                                $hargaPerUnit = $resultAmountConvert > 0 ? $hargaBase / $resultAmountConvert : 0;
                                $batches[$k]['amountUsed'] = $amountUsed;
                                $batches[$k]['HargaPerUnit'] = $hargaPerUnit;
                                $batches[$k]['TotalHarga'] = round($amountUsed * $hargaPerUnit, 2);
                            }
                        }
                    }

                    foreach ($batches as $k => $ub) {
                        $sql = "INSERT INTO item_used(
                                        ItemUsedDate,
                                        ItemUsedNumber,
                                        ItemUsedItemUsageID,
                                        ItemUsedBatchNo,
                                        ItemUsedM_ItemID,
                                        ItemUsedItemUnitID,
                                        ItemUsedQty,
                                        ItemUsedPrice,
                                        ItemUsedTotal,
                                        ItemUsedIsActive,
                                        ItemUsedUserID,
                                        ItemUsedCreated
                                    ) VALUES(?,?,?,?,?,?,?,?,?,'Y',?,NOW())";

                        $qry = $this->db->query($sql, [
                            $date,
                            $IUnumber,
                            $ItemUsageID,
                            $value['StockBatchNo'],
                            $value['StockItemID'],
                            $value['StockItemUnitID'],
                            $ub['amountUsed'],
                            $ub['HargaPerUnit'],
                            $ub['TotalHarga'],
                            $userId
                        ]);
                        if (!$qry) {
                            $this->db->trans_rollback();
                            $this->sys_error_db("Failed insert item used", $this->db);
                            exit;
                        }

                        $sqlUpdate = "UPDATE item_usage_detail 
                          SET ItemUsageDetailQtyReq = ?,
                              ItemUsageDetailLastUpdated = NOW()
                          WHERE ItemUsageDetailID = ?";
                        $qryUpdate =  $this->db->query($sqlUpdate, [
                            $ub['QtyReq'],
                            $ub['ItemUsageDetailID']
                        ]);
                        if (!$qryUpdate) {
                            $this->db->trans_rollback();
                            $this->sys_error_db("Failed update item usage detail", $this->db);
                            exit;
                        }
                    }
                }
            }

            $this->insertUserActivityUsage($ItemUsageID, $userId, 'UPDATE', 'Pemakaian item pada tanggal ' . date('d-m-Y'));
            $this->insertUserActivityUsed($ItemUsageID, $userId, 'SAVE', 'Pemakaian item dengan kode ' . $IUnumber . ' telah dibuat');

            $this->db->trans_commit();

            $result = array(
                "records" => "0",
                "message" => "Item usage saved successfully",
            );
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    function getConvertAmount($fromUnitID, $toUnitID)
    {
        $sql = "SELECT UnitConvertAmount
                FROM unitconvert
                WHERE UnitConvertFromItemUnitID = ? 
                  AND UnitConvertToItemUnitID = ?
                  AND UnitConvertIsActive = 'Y'";
        $convert = $this->db->query($sql, [$fromUnitID, $toUnitID])->row();

        if (!$convert) {
            $this->sys_error("Konversi unit tidak ditemukan.");
            exit;
        }
        return intval($convert->UnitConvertAmount);
    }

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

            $itemUsageID = $prm["itemUsageID"];
            $startdate = $prm["startdate"];
            $enddate = $prm["enddate"];
            $search = $prm["search"];
            if (empty($search)) {
                $search = "%";
            } else {
                $search = "%" . $search . "%";
            }

            $statusConfirm = $prm["statusConfirm"];
            if ($statusConfirm == "Y") {
                $statusConfirm = "AND ItemUsedIsConfirm = 'Y'";
            } elseif ($statusConfirm == "N") {
                $statusConfirm = "AND ItemUsedIsConfirm = 'N'";
            } else {
                $statusConfirm = "";
            }

            $number_offset = 0;
            $number_limit = 10;
            if ($prm["current_page"] > 0) {
                $number_offset = ($prm["current_page"] - 1) * $number_limit;
            }
            $sql_total = "SELECT COUNT(*) AS total
                    FROM item_used
                    JOIN m_item ON ItemUsedM_ItemID = M_ItemID
                    AND M_ItemIsActive = 'Y'
                    JOIN itemunit ON ItemUsedItemUnitID = ItemUnitID
                    AND ItemUnitIsActive = 'Y'
                    LEFT JOIN m_user ON ItemUsedUserID = M_UserID
                    AND M_UserIsActive = 'Y'
                    WHERE ItemUsedIsActive = 'Y'
                    AND ItemUsedItemUsageID = ?
                    AND (M_ItemDesc LIKE ?)
                    AND ItemUsedDate BETWEEN ? AND ?
                    $statusConfirm";
            $qry_total = $this->db->query($sql_total, [$itemUsageID, $search, $startdate, $enddate]);
            $tot_count = 0;
            $tot_page = 0;
            if ($qry_total) {
                $tot_count = $qry_total->result_array()[0]["total"];
                $tot_page = ceil($tot_count / $number_limit);
            } else {
                $this->sys_error_db("Failed select item used total", $this->db);
                exit;
            }

            $sql = "SELECT ItemUsedID,
                    ItemUsedNumber,
                    ItemUsedBatchNo,
                    ItemUsedDate,
                    ItemUsedQty,
                    ItemUsedPrice,
                    ItemUsedTotal,
                    ItemUsedIsConfirm,
                    ItemUnitID,
                    ItemUnitName,
                    M_ItemID,
                    M_ItemCode,
                    M_ItemDesc,
                    M_UserUsername
                    FROM item_used
                    JOIN m_item ON ItemUsedM_ItemID = M_ItemID
                    AND M_ItemIsActive = 'Y'
                    JOIN itemunit ON ItemUsedItemUnitID = ItemUnitID
                    AND ItemUnitIsActive = 'Y'
                    LEFT JOIN m_user ON ItemUsedUserID = M_UserID
                    AND M_UserIsActive = 'Y'
                    WHERE ItemUsedIsActive = 'Y'
                    AND ItemUsedItemUsageID = ?
                    AND (M_ItemDesc LIKE ?)
                    AND ItemUsedDate BETWEEN ? AND ?
                    $statusConfirm
                    ORDER BY ItemUsedID DESC
                    LIMIT ? OFFSET ?";

            $qry = $this->db->query($sql, [$itemUsageID, $search, $startdate, $enddate, $number_limit, $number_offset]);
            if ($qry) {
                $rows = $qry->result_array();
            } else {
                $this->sys_error_db("Failed select item used", $this->db);
                exit;
            }
            $result = array(
                "total_count" => $tot_count,
                "total_page" => $tot_page,
                "records" => $rows
            );
            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    public function updateItemUsed()
    {
        try {
            $payload = $this->sys_input;
            $userId = $this->sys_user["M_UserID"];

            $itemUsedID   = (int)$payload['itemUsedID'];
            $newUsedQty   = (float)$payload['ItemUsedQty']; // qty baru

            $this->db->trans_begin();

            // ambil data lama dari item_used
            $sql_used = "SELECT ItemUsedQty, ItemUsedItemUsageID, ItemUsedItemUnitID
                 FROM item_used WHERE ItemUsedID = ?";
            $oldData = $this->db->query($sql_used, [$itemUsedID])->row();

            if (!$oldData) {
                $this->db->trans_rollback();
                $this->sys_error("Data pemakaian tidak ditemukan.");
                return;
            }

            $oldQty = (float)$oldData->ItemUsedQty;
            $itemUsageID = $oldData->ItemUsedItemUsageID;
            $fromUnitID = $oldData->ItemUsedItemUnitID;

            // ambil item_usage untuk tahu unit besar
            $sql_usage = "SELECT ItemUsageQty, ItemUsageItemUnitID
                  FROM item_usage WHERE ItemUsageID = ?";
            $usageData = $this->db->query($sql_usage, [$itemUsageID])->row();

            if (!$usageData) {
                $this->db->trans_rollback();
                $this->sys_error("Data usage tidak ditemukan.");
                return;
            }

            $currentUsageQty = (float)$usageData->ItemUsageQty;
            $toUnitID = $usageData->ItemUsageItemUnitID; // unit besar

            // ambil konversi unit kecil -> unit besar
            $sql_convert = "SELECT UnitConvertAmount
                    FROM unitconvert
                    WHERE UnitConvertFromItemUnitID = ? 
                      AND UnitConvertToItemUnitID = ?";
            $convert = $this->db->query($sql_convert, [$toUnitID, $fromUnitID])->row();

            if (!$convert) {
                $this->db->trans_rollback();
                $this->sys_error("Konversi unit tidak ditemukan.");
                return;
            }

            $convertAmount = (float)$convert->UnitConvertAmount;

            // hitung perubahan qty dalam unit besar
            $oldQtyInBig = $oldQty / $convertAmount;
            $newQtyInBig = $newUsedQty / $convertAmount;
            $diffInBig   = $newQtyInBig - $oldQtyInBig;

            // jika diff positif (pemakaian bertambah) → stok dikurangi
            if ($diffInBig > 0) {
                if ($currentUsageQty < $diffInBig) {
                    $this->db->trans_rollback();
                    $this->sys_error("Stok tidak mencukupi. Stok tersedia: {$currentUsageQty}.");
                    return;
                }
                $newUsageQty = $currentUsageQty - $diffInBig;
            }
            // jika diff negatif (pemakaian berkurang) → stok dikembalikan
            else {
                $newUsageQty = $currentUsageQty + abs($diffInBig);
            }

            // update item_usage
            $sql_update_usage = "UPDATE item_usage SET 
                            ItemUsageQty = ?, 
                            ItemUsageLastUpdated = NOW(),
                            ItemUsageUserID = ?
                         WHERE ItemUsageID = ?";
            $this->db->query($sql_update_usage, [
                $newUsageQty,
                $userId,
                $itemUsageID
            ]);

            // update item_used
            $sql_update_used = "UPDATE item_used SET 
                            ItemUsedQty = ?,
                            ItemUsedLastUpdated = NOW(),
                            ItemUsedUserID = ?
                        WHERE ItemUsedID = ?";
            $this->db->query($sql_update_used, [
                $newUsedQty,
                $userId,
                $itemUsedID
            ]);

            $sqlu = "SELECT ItemUsedID, ItemUsedNumber FROM item_used WHERE ItemUsedIsActive = 'Y' AND ItemUsedID = ?";
            $qryu = $this->db->query($sqlu, [$itemUsedID]);
            if (!$qryu) {
                $this->db->trans_rollback();
                $this->sys_error_db("Failed get item", $this->db);
                exit;
            }
            $rowitem = $qryu->row_array();

            $this->insertUserActivityUsage($itemUsageID, $userId, 'UPDATE', 'Pemakaian item pada tanggal ' . date('d-m-Y'));
            $this->insertUserActivityUsed($itemUsageID, $userId, 'UPDATE', 'Pemakaian item dengan kode ' . $rowitem['ItemUsedNumber'] . ' telah diupdate');

            $this->db->trans_commit();

            $this->sys_ok("Item used berhasil diupdate.");
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }
    public function deleteItemUsed()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
            }

            $payload = $this->sys_input;
            $userId = $this->sys_user["M_UserID"];

            $itemUsedID = $payload["itemUsedID"];

            // ambil data item_used
            $sql = "SELECT * FROM item_used WHERE ItemUsedID = ? AND ItemUsedIsActive = 'Y'";
            $itemUsed = $this->db->query($sql, [$itemUsedID])->row();

            if (!$itemUsed) {
                $this->sys_error("Data item_used tidak ditemukan atau sudah tidak aktif");
                return;
            }

            // ambil item_usage
            $sql_usage = "SELECT * FROM item_usage WHERE ItemUsageID = ?";
            $itemUsage = $this->db->query($sql_usage, [$itemUsed->ItemUsedItemUsageID])->row();

            if (!$itemUsage) {
                $this->sys_error("Data item_usage tidak ditemukan");
                return;
            }

            $restoreQty = (float)$itemUsed->ItemUsedQty;

            // cek apakah unit sama atau perlu konversi
            if ($itemUsed->ItemUsedItemUnitID != $itemUsage->ItemUsageItemUnitID) {
                $sql_convert = "SELECT UnitConvertAmount 
                            FROM unitconvert 
                            WHERE UnitConvertFromItemUnitID = ? 
                              AND UnitConvertToItemUnitID = ?";
                $convert = $this->db->query($sql_convert, [
                    $itemUsage->ItemUsageItemUnitID,
                    $itemUsed->ItemUsedItemUnitID
                ])->row();

                if (!$convert) {
                    $this->sys_error("Konversi unit tidak ditemukan, tidak bisa restore qty");
                    return;
                }

                // ubah qty ke unit besar
                $restoreQty = $restoreQty / $convert->UnitConvertAmount;
            }

            $this->db->trans_begin();

            // 1. update item_used menjadi tidak aktif
            $sql_update_used = "UPDATE item_used SET 
                                ItemUsedIsActive = 'N',
                                ItemUsedLastUpdated = NOW(),
                                ItemUsedUserID = ?
                            WHERE ItemUsedID = ?";
            $this->db->query($sql_update_used, [$userId, $itemUsedID]);

            // 2. kembalikan qty ke item_usage
            $sql_update_usage = "UPDATE item_usage SET 
                                ItemUsageQty = ItemUsageQty + ?,
                                ItemUsageLastUpdated = NOW(),
                                ItemUsageUserID = ?
                            WHERE ItemUsageID = ?";
            $this->db->query($sql_update_usage, [
                $restoreQty,
                $userId,
                $itemUsage->ItemUsageID
            ]);

            $sqlu = "SELECT ItemUsedID, ItemUsedNumber FROM item_used WHERE ItemUsedIsActive = 'Y' AND ItemUsedID = ?";
            $qryu = $this->db->query($sqlu, [$itemUsedID]);
            if (!$qryu) {
                $this->db->trans_rollback();
                $this->sys_error_db("Failed get item", $this->db);
                exit;
            }
            $rowitem = $qryu->row_array();

            $this->insertUserActivityUsage($itemUsage->ItemUsageID, $userId, 'UPDATE', 'Pemakaian item pada tanggal ' . date('d-m-Y'));
            $this->insertUserActivityUsed($itemUsedID, $userId, 'DELETE', 'Pemakaian item dengan kode ' . $rowitem['ItemUsedNumber'] . ' telah dihapus');
            $this->db->trans_commit();

            $this->sys_ok("ItemUsed berhasil dihapus dan qty dikembalikan");
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

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

            $payload = $this->sys_input;
            $userId = $this->sys_user["M_UserID"];
            $this->db->trans_begin();

            $itemUsedID = $payload["itemUsedID"];

            // ambil data item_used
            $sql = "SELECT * FROM item_used WHERE ItemUsedID = ? AND ItemUsedIsActive = 'Y'";
            $itemUsed = $this->db->query($sql, [$itemUsedID])->row();

            if (!$itemUsed) {
                $this->db->trans_rollback();
                $this->sys_error("Data item_used tidak ditemukan atau sudah tidak aktif");
                exit;
            }

            // update status konfirmasi
            $sql_update = "UPDATE item_used SET 
                            ItemUsedIsConfirm = 'Y',
                            ItemUsedLastUpdated = NOW(),
                            ItemUsedUserID = ?
                        WHERE ItemUsedID = ?";
            $this->db->query($sql_update, [$userId, $itemUsedID]);

            // generate jurnal
            $this->generateJurnal($itemUsedID);

            $sqlu = "SELECT ItemUsedID, ItemUsedNumber FROM item_used WHERE ItemUsedIsActive = 'Y' AND ItemUsedID = ?";
            $qryu = $this->db->query($sqlu, [$itemUsedID]);
            if (!$qryu) {
                $this->db->trans_rollback();
                $this->sys_error_db("Failed get item", $this->db);
                exit;
            }
            $rowitem = $qryu->row_array();

            $this->insertUserActivityUsed($itemUsedID, $userId, 'KONFIRMASI', 'Pemakaian item dengan kode ' . $rowitem['ItemUsedNumber'] . ' telah dikonfirmasi');

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

    function generateJurnal($itemusedID)
    {
        try {
            $this->db->trans_begin();
            $user = $this->sys_user;

            $sqldata = "SELECT ItemUsedID,
                DATE_FORMAT(ItemUsedDate, '%d-%m-%Y') as ItemUsedDate,
                ItemUsedNumber,
                ItemUsedBatchNo,
                ItemUsedQty,
                ItemUsedPrice,
                ItemUsedTotal,
                ItemUsageID,
                ItemUsageQty,
                ItemUsagePrice,
                ItemUsedTotal,
                M_ItemID,
                CASE 
                    WHEN M_ItemCode IS NULL OR M_ItemCode = '' 
                        THEN M_ItemDesc
                    ELSE CONCAT(M_ItemCode, ' - ', M_ItemDesc)
                END AS M_ItemDesc,
                ItemUnitID,
                ItemUnitCode,
                ItemUnitName,
                M_UserUsername,
                DivisionID,
                DivisionCode,
                DivisionName
                FROM item_used
                JOIN item_usage ON ItemUsedItemUsageID = ItemUsageID
                AND ItemUsageIsActive = 'Y'
                JOIN m_item ON ItemUsedM_ItemID = M_ItemID
                AND M_ItemIsActive = 'Y'
                JOIN itemunit ON ItemUsedItemUnitID = ItemUnitID
                AND ItemUnitIsActive = 'Y'
                LEFT JOIN m_user ON ItemUsedUserID = M_UserID
                LEFT JOIN m_userdivision ON M_UserDivisionM_UserID = M_UserID
                AND M_UserDivisionIsActive = 'Y'
                LEFT JOIN division ON M_UserDivisionDivisionID = DivisionID
                AND DivisionIsActive = 'Y'
                WHERE ItemUsedIsActive = 'Y'
                AND ItemUsedID = ?";
            $qrydata = $this->db->query($sqldata, [$itemusedID]);
            if (!$qrydata) {
                $this->db->trans_rollback();
                $this->sys_error_db("get data item used error", $this->db);
                exit;
            }
            $datarow = $qrydata->row_array();

            // generate numbering jurnal
            $sql = "SELECT `fn_numbering`('J') AS numbering";
            $qry = $this->db->query($sql, []);
            if (!$qry) {
                $this->sys_error_db("get numbering error", $this->db);
                $this->db->trans_rollback();
                exit;
            }
            $numbering = $qry->row_array()["numbering"];

            // ambil data periode
            $sql = "SELECT periodeID FROM periode
                WHERE DATE_FORMAT(NOW(), '%Y-%m-%d') BETWEEN periodeStartDate AND periodeEndDate 
                AND periodeIsActive= 'Y' 
                AND periodeIsClosed = 'N'";
            $qry = $this->db->query($sql, []);
            if (!$qry) {
                $this->sys_error_db("get periode error", $this->db);
                $this->db->trans_rollback();
                exit;
            }
            $dataPeriode = $qry->row_array();
            if (empty($dataPeriode)) {
                $this->sys_error("Periode untuk generate jurnal tidak ditemukan");
                $this->db->trans_rollback();
                exit;
            }
            $periodeID = $dataPeriode["periodeID"];

            $jurnalTitle = "Jurnal pemakaian item No. {$datarow['ItemUsedNumber']} Tanggal {$datarow['ItemUsedDate']}";
            $jurnalDesc = "Jurnal pemakaian item No. {$datarow['ItemUsedNumber']} Tanggal {$datarow['ItemUsedDate']} dengan nama item {$datarow['M_ItemDesc']}, Batch No {$datarow['ItemUsedBatchNo']} oleh {$datarow['M_UserUsername']} divisi {$datarow['DivisionName']}";

            // ambil item untuk cek persediaan
            $sqlItem = "SELECT * FROM m_item WHERE M_ItemID = ?";
            $qryItem = $this->db->query($sqlItem, [
                $datarow["M_ItemID"]
            ]);
            if (!$sqlItem) {
                $this->db->trans_rollback();
                $this->sys_error_db("ERROR, qry item", $this->db);
                exit;
            }
            $cekItem = $qryItem->row_array();

            if (empty($cekItem)) {
                $this->db->trans_rollback();
                $this->sys_error_db("Item {$datarow['ItemUsedNumber']} {$datarow['M_ItemDesc']} tidak ditemukan", $this->db);
                exit;
            }
            if ($cekItem['M_ItemItem_CategoryID'] == 0 || $cekItem['M_ItemItem_CategoryID'] == null || $cekItem['M_ItemItem_CategoryID'] == '') {
                $this->db->trans_rollback();
                $this->sys_error_db("Item {$datarow['ItemUsedNumber']} {$datarow['M_ItemDesc']} belum memiliki kategori", $this->db);
                exit;
            }

            // cek persediaan
            $date = date('Y-m-d');
            $detailJurnal = [];
            if (intval($cekItem['M_ItemItem_CategoryID']) == 1) {
                if ($cekItem['M_ItemNat_SubGroupID'] == null || $cekItem['M_ItemNat_SubGroupID'] == 0 || $cekItem['M_ItemNat_SubGroupID'] == '') {
                    $this->db->trans_rollback();
                    $this->sys_error_db("Item {$datarow['ItemUsedNumber']} {$datarow['M_ItemDesc']} belum memiliki sub grup", $this->db);
                    exit;
                }
                $sqlSubGrup = "SELECT * FROM map_nat_subgroup
                        WHERE MapNatSub_NatGroupID = ?
                        AND MapNatSub_NatSubGroupID = ?
                        AND MapNatSub_IsActive = 'Y'";
                $qrySubGrup = $this->db->query($sqlSubGrup, [
                    $cekItem['M_ItemNat_GroupID'],
                    $cekItem['M_ItemNat_SubGroupID']
                ]);
                if (!$qrySubGrup) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("ERROR, get map nat subgrup", $this->db);
                    exit;
                }
                $rowMapNatSubGrup = $qrySubGrup->row_array();
                // print_r($rowMapNatSubGrup);

                if (
                    $rowMapNatSubGrup['MapNatSub_PersediaanCoaID'] == null ||
                    $rowMapNatSubGrup['MapNatSub_PersediaanCoaID'] == '' ||

                    $rowMapNatSubGrup['MapNatSub_PersediaanCoaAccountNo'] == null ||
                    $rowMapNatSubGrup['MapNatSub_PersediaanCoaAccountNo'] == '' ||

                    $rowMapNatSubGrup['MapNatSub_PersediaanCoaDescription'] == null ||
                    $rowMapNatSubGrup['MapNatSub_PersediaanCoaDescription'] == ''

                ) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("Coa persediann, item {$datarow['ItemUsedNumber']} {$datarow['M_ItemDesc']} belum termapping", $this->db);;
                    exit;
                }

                if (
                    $rowMapNatSubGrup['MapNatSub_BiayaCoaID'] == null ||
                    $rowMapNatSubGrup['MapNatSub_BiayaCoaID'] == '' ||

                    $rowMapNatSubGrup['MapNatSub_BiayaCoaAccountNo'] == null ||
                    $rowMapNatSubGrup['MapNatSub_BiayaCoaAccountNo'] == '' ||

                    $rowMapNatSubGrup['MapNatSub_BiayaCoaDescription'] == null ||
                    $rowMapNatSubGrup['MapNatSub_BiayaCoaDescription'] == ''
                ) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("Coa biaya pemakaian, item {$datarow['ItemUsedNumber']} {$datarow['M_ItemDesc']} belum termapping", $this->db);;
                    exit;
                }

                $detailJurnal = [
                    [
                        'coaID' => $rowMapNatSubGrup['MapNatSub_BiayaCoaID'],
                        'xdescription' => $rowMapNatSubGrup['MapNatSub_BiayaCoaDescription'],
                        'debit' => $datarow['ItemUsedTotal'],
                        'credit' => 0
                    ],
                    [
                        'coaID' => $rowMapNatSubGrup['MapNatSub_PersediaanCoaID'],
                        'xdescription' => $rowMapNatSubGrup['MapNatSub_PersediaanCoaDescription'],
                        'debit' => 0,
                        'credit' => $datarow['ItemUsedTotal']
                    ]
                ];
            }

            $this->saveJurnal(
                $date,
                $jurnalDesc,
                $periodeID,
                $numbering,
                $jurnalTitle,
                $detailJurnal,
                $user['M_BranchCompanyID'],
                $user['S_RegionalID'],
                $user['M_BranchCode'],
                $datarow['ItemUsedNumber']
            );

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

    function saveJurnal(
        $date,
        $jurnalDesc,
        $periodeID,
        $numbering,
        $jurnalTitle,
        $detailJurnal,
        $branchCompanyID,
        $regionalID,
        $branchCode,
        $noIU
    ) {
        try {

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

            $sql = "INSERT INTO jurnal(
                    jurnalM_BranchCompanyID,
                    JurnalS_RegionalID,
                    jurnalM_BranchCode,
                    jurnalperiodeID,
                    jurnalNo,
                    jurnalTitle,
                    jurnalDescription,
                    jurnalDate,
                    jurnalJurnalTypeID,
                    jurnalIsActive,
                    jurnalCreated,
                    jurnalM_UserID
                    ) VALUES(?,?,?,?,?,?,?,?,?,'Y',NOW(),?)";
            $qry = $this->db->query($sql, array(
                $branchCompanyID,
                $regionalID,
                $branchCode,
                $periodeID,
                $numbering,
                $jurnalTitle,
                $jurnalDesc,
                $date,
                23,
                $userid
            ));
            $last_qry = $this->db->last_query();
            if (!$qry) {
                $this->db->trans_rollback();
                $error = array(
                    "message" => $this->db->error()["message"],
                    "sql" => $last_qry
                );
                $this->sys_error_db($error, $this->db);
                exit;
            }

            $last_id = $this->db->insert_id();

            foreach ($detailJurnal as $key => $value) {
                $sql_detail = "INSERT INTO jurnal_tx(
                                jurnalTxJurnalID,
                                jurnalTxCoaID,
                                jurnalTxDescription,
                                jurnalTxDebit,
                                jurnalTxCredit,
                                jurnalTxIsActive,
                                jurnalTxCreated,
                                jurnalTxM_UserID) VALUES(?,?,?,?,?,'Y',NOW(),?)";
                $qry_detail = $this->db->query($sql_detail, array(
                    $last_id,
                    $value["coaID"],
                    $value["xdescription"],
                    $value["debit"],
                    $value["credit"],
                    $userid
                ));
                $last_qry = $this->db->last_query();
                if (!$qry_detail) {
                    $this->db->trans_rollback();
                    $error = array(
                        "message" => $this->db->error()["message"],
                        "sql" => $last_qry
                    );
                    $this->sys_error_db($error, $this->db);
                    exit;
                }

                $tx_id = $this->db->insert_id();

                $sql = "INSERT INTO jurnal_addon 
                        (jurnalAddOnJurnalID, 
                        jurnalAddOnJurnalTxID, 
                        jurnalAddOnCode, 
                        jurnalAddOnValue, 
                        jurnalAddOnCreated, 
                        jurnalAddOnCreatedUserID, 
                        jurnalAddOnLastUpdatedUserID, 
                        jurnalAddOnLastUpdated) 
                        VALUES
                        (?,	
                        ?,	
                        'AUTOITEMUSAGE',	
                        ?,	
                        now(),	
                        ?,	
                        ?,
                        now())";
                $qry = $this->db->query($sql, array(
                    $last_id,
                    $tx_id,
                    $noIU,
                    $userid,
                    $userid
                ));
                $last_qry = $this->db->last_query();
                if (!$qry) {
                    $this->db->trans_rollback();
                    $error = array(
                        "message" => $this->db->error()["message"],
                        "sql" => $last_qry
                    );
                    $this->sys_error_db($error, $this->db);
                    exit;
                }
            }

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

    function insertUserActivityUsage($itemusageID, $userId, $status, $userdesc)
    {
        try {
            // insert log
            $sql_json = "SELECT item_usage.*
                        FROM item_usage
                        WHERE ItemUsageIsActive = 'Y'
                        AND ItemUsageID = ?";
            $qry_json = $this->db->query($sql_json, [$itemusageID]);
            if (!$qry_json) {
                $this->db->trans_rollback();
                $this->sys_error_db("select json io error");
                exit;
            }
            $row_json = $qry_json->row_array();

            $sql_log = "INSERT INTO user_activity(
                            UserActivityCode,
                            UserActivityStatus,
                            UserActivityDescription,
                            UserActivityRefID,
                            UserActivityData,
                            UserActivityUserID,
                            UserActivityCreated
                        ) VALUES('USAGE',?,?,?,?,?,NOW())";
            $qry_log = $this->db->query($sql_log, [
                $status,
                $userdesc,
                $itemusageID,
                json_encode($row_json),
                $userId
            ]);
            if (!$qry_log) {
                $this->db->trans_rollback();
                $this->sys_error_db("insert user activity error", $this->db);
                exit;
            }
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    function insertUserActivityUsed($itemusedID, $userId, $status, $userdesc)
    {
        try {
            // insert log
            $sql_json = "SELECT item_used.*
                        FROM item_used
                        WHERE ItemUsedIsActive = 'Y'
                        AND ItemUsedID = ?";
            $qry_json = $this->db->query($sql_json, [$itemusedID]);
            if (!$qry_json) {
                $this->db->trans_rollback();
                $this->sys_error_db("select json io error");
                exit;
            }
            $row_json = $qry_json->row_array();

            $sql_log = "INSERT INTO user_activity(
                            UserActivityCode,
                            UserActivityStatus,
                            UserActivityDescription,
                            UserActivityRefID,
                            UserActivityData,
                            UserActivityUserID,
                            UserActivityCreated
                        ) VALUES('USED',?,?,?,?,?,NOW())";
            $qry_log = $this->db->query($sql_log, [
                $status,
                $userdesc,
                $itemusedID,
                json_encode($row_json),
                $userId
            ]);
            if (!$qry_log) {
                $this->db->trans_rollback();
                $this->sys_error_db("insert user activity error", $this->db);
                exit;
            }
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }
}
