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

    function index()
    {
        echo "APPROVE LEVEL 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 m_approve_level
                    WHERE M_ApproveLevelIsActive = 'Y'
                    AND (M_ApproveLevelName LIKE ?)";
            $qry_count = $this->db->query($sql_count, [$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("approve count error", $this->db);
                exit;
            }

            $sql = "SELECT M_ApproveLevelID,
                    M_ApproveLevelName,
                    M_ApproveLevelStartTotal,
                    M_ApproveLevelEndTotal
                    FROM m_approve_level
                    WHERE M_ApproveLevelIsActive = 'Y'
                    AND (M_ApproveLevelName LIKE ?)
                    ORDER BY M_ApproveLevelID DESC
                    LIMIT ? OFFSET ?";
            $qry = $this->db->query($sql, [$search, $number_limit, $number_offset]);
            if ($qry) {
                $rows = $qry->result_array();
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("approve list error", $this->db);
                exit;
            }

            foreach ($rows as $key => $value) {
                $rows[$key]['rownumber'] = $key + 1;
            }

            $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 {
            $this->db->trans_begin();
            $prm = $this->sys_input;
            $userId = $this->sys_user["M_UserID"];

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

            $name = trim($prm['name']);
            $startTotal = trim($prm['startTotal']);
            $endTotal = trim($prm['endTotal']);

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

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

            $sql = "INSERT INTO m_approve_level(
                    M_ApproveLevelName,
                    M_ApproveLevelStartTotal,
                    M_ApproveLevelEndTotal,
                    M_ApproveLevelIsActive,
                    M_ApproveLevelUserID,
                    M_ApproveLevelCreated) VALUES(?,?,?,'Y',?,NOW())";
            $qry = $this->db->query($sql, [
                $name,
                $startTotal,
                $endTotal,
                $userId
            ]);

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

            $this->db->trans_commit();

            $newInsert = "SELECT * FROM m_approve_level WHERE M_ApproveLevelName = '{$name}' AND M_ApproveLevelIsActive = '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['approveId']) || !is_numeric($prm['approveId'])) {
                $this->sys_error("Approve level ID is required");
                exit;
            }
            if (!isset($prm['name']) || trim($prm['name']) == "") {
                $this->sys_error("Approve level name is required");
                exit;
            }

            $approveId = $prm['approveId'];
            $name = trim($prm['name']);
            $startTotal = trim($prm['startTotal']);
            $endTotal = trim($prm['endTotal']);

            // Check if department exists
            $sql_exist = "SELECT COUNT(*) as total FROM m_approve_level 
                          WHERE M_ApproveLevelID = ? AND M_ApproveLevelIsActive = 'Y'";
            $qry_exist = $this->db->query($sql_exist, [$approveId]);
            if ($qry_exist && $qry_exist->result_array()[0]['total'] == 0) {
                $this->sys_error("Approve level not found");
                exit;
            }

            // Check for existing department with same name (excluding current department)
            $sql_check = "SELECT COUNT(*) as total FROM m_approve_level 
                          WHERE M_ApproveLevelName = ? AND M_ApproveLevelID != ? 
                          AND M_ApproveLevelIsActive = 'Y'";
            $qry_check = $this->db->query($sql_check, [$name, $approveId]);
            if ($qry_check && $qry_check->result_array()[0]['total'] > 0) {
                $this->sys_error("Nama Approve level sudah ada");
                exit;
            }

            // Update department
            $sql = "UPDATE m_approve_level SET 
                    M_ApproveLevelName = ?,
                    M_ApproveLevelStartTotal = ?,
                    M_ApproveLevelEndTotal = ?,
                    M_ApproveLevelUserID = ?,
                    M_ApproveLevelLastUpdated = NOW()
                    WHERE M_ApproveLevelID = ?";
            $qry = $this->db->query($sql, [
                $name,
                $startTotal,
                $endTotal,
                $userId,
                $approveId
            ]);

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

            $this->db->trans_commit();

            // Get updated record
            $sql_get = "SELECT * FROM m_approve_level WHERE M_ApproveLevelID = ? AND M_ApproveLevelIsActive = 'Y'";
            $records = $this->db->query($sql_get, [$approveId])->result_array();

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

    function delete()
    {
        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['approveId']) || !is_numeric($prm['approveId'])) {
                $this->sys_error("Approve level ID is required");
                exit;
            }

            $approveId = $prm['approveId'];

            // Check if approve exists and is active
            $sql_exist = "SELECT COUNT(*) as total FROM m_approve_level 
                         WHERE M_ApproveLevelID = ? AND M_ApproveLevelIsActive = 'Y'";
            $qry_exist = $this->db->query($sql_exist, [$approveId]);
            if ($qry_exist && $qry_exist->result_array()[0]['total'] == 0) {
                $this->sys_error("Approve level not found");
                exit;
            }

            // Soft delete by updating IsActive to 'N'
            $sql = "UPDATE m_approve_level SET 
                    M_ApproveLevelIsActive = 'N',
                    M_ApproveLevelUserID = ?,
                    M_ApproveLevelLastUpdated = NOW()
                    WHERE M_ApproveLevelID = ?";
            $qry = $this->db->query($sql, [
                $userId,
                $approveId
            ]);

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

            $this->db->trans_commit();

            $this->sys_ok(array(
                "message" => "Approve level deleted successfully",
                "approveId" => $approveId
            ));
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

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

            $approveId = $prm["approveId"];

            $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 m_user
                    JOIN m_staff ON M_UserM_StaffID = M_StaffID AND M_StaffIsActive = 'Y'
                    WHERE M_UserIsActive = 'Y'
                    AND M_UserM_ApproveLevelID = ?
                    AND (M_UserFullName LIKE ? OR M_StaffName LIKE ?)";
            $qry_count = $this->db->query($sql_count, [$approveId, $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("m_user count error", $this->db);
                exit;
            }

            $sql = "SELECT 
                    M_UserID,
                    M_UserM_BranchID,
                    M_UserS_RegionalID,
                    M_UserM_UserGroupID,
                    M_UserR_ReportGroupID,
                    M_UserM_StaffID,
                    M_UserUsername,
                    M_UserFullName,
                    M_UserIsCoordinator,
                    M_StaffName,
                    M_StaffPhone
                    FROM m_user
                    JOIN m_staff ON M_UserM_StaffID = M_StaffID AND M_StaffIsActive = 'Y'
                    WHERE M_UserIsActive = 'Y'
                    AND M_UserM_ApproveLevelID = ?
                    AND (M_UserFullName LIKE ? OR M_StaffName LIKE ?)
                    LIMIT ? OFFSET ?";
            $qry = $this->db->query($sql, [$approveId, $search, $search, $number_limit, $number_offset]);
            if ($qry) {
                $rows = $qry->result_array();
            } else {
                $this->db->trans_rollback();
                $this->sys_error_db("m_user 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);
        }
    }
}
