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

    function index()
    {
        echo "DEPARTEMEN 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_department
                    WHERE M_DepartmentIsActive = 'Y'
                    AND (M_DepartmentCode LIKE ? OR M_DepartmentName 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("department count error", $this->db);
                exit;
            }

            $sql = "SELECT M_DepartmentID,
                    M_DepartmentCode,
                    M_DepartmentName,
                    M_DepartmentCreated,
                    M_DepartmentLastUpdated,
                    '' as rownumber
                    FROM m_department
                    WHERE M_DepartmentIsActive = 'Y'
                    AND (M_DepartmentCode LIKE ? OR M_DepartmentName LIKE ?)
                    ORDER BY M_DepartmentID 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("department 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 {
            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['nameDepartment']) || trim($prm['nameDepartment']) == "") {
                $this->sys_error("Department name is required");
                exit;
            }
            if (!isset($prm['codeDepartment']) || trim($prm['codeDepartment']) == "") {
                $this->sys_error("Code name is required");
                exit;
            }

            $nameDepartment = trim($prm['nameDepartment']);
            $codeDepartment = trim($prm['codeDepartment']);

            // Check for existing department with same name
            $sql_check = "SELECT COUNT(*) as total FROM m_department 
                         WHERE M_DepartmentName = ? AND M_DepartmentIsActive = 'Y'";
            $qry_check = $this->db->query($sql_check, [$nameDepartment]);

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

            $sql = "INSERT INTO m_department(
                    M_DepartmentCode,
                    M_DepartmentName,
                    M_DepartmentIsActive,
                    M_DepartmentUserID,
                    M_DepartmentCreated
                    ) VALUES(?,?,'Y',?,NOW())";
            $qry = $this->db->query($sql, [
                $codeDepartment,
                $nameDepartment,
                $userId
            ]);

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

            $this->db->trans_commit();

            $newInsert = "SELECT * FROM m_department WHERE M_DepartmentCode = '{$codeDepartment}' AND M_DepartmentIsActive = '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['departmentId']) || !is_numeric($prm['departmentId'])) {
                $this->sys_error("Department ID is required");
                exit;
            }
            if (!isset($prm['nameDepartment']) || trim($prm['nameDepartment']) == "") {
                $this->sys_error("Department name is required");
                exit;
            }
            if (!isset($prm['codeDepartment']) || trim($prm['codeDepartment']) == "") {
                $this->sys_error("Code name is required");
                exit;
            }

            $departmentId = $prm['departmentId'];
            $nameDepartment = trim($prm['nameDepartment']);
            $codeDepartment = trim($prm['codeDepartment']);

            // Check if department exists
            $sql_exist = "SELECT COUNT(*) as total FROM m_department 
                          WHERE M_DepartmentID = ? AND M_DepartmentIsActive = 'Y'";
            $qry_exist = $this->db->query($sql_exist, [$departmentId]);
            if ($qry_exist && $qry_exist->result_array()[0]['total'] == 0) {
                $this->sys_error("Department not found");
                exit;
            }

            // Check for existing department with same name (excluding current department)
            $sql_check = "SELECT COUNT(*) as total FROM m_department 
                          WHERE M_DepartmentName = ? AND M_DepartmentID != ? 
                          AND M_DepartmentIsActive = 'Y'";
            $qry_check = $this->db->query($sql_check, [$nameDepartment, $departmentId]);
            if ($qry_check && $qry_check->result_array()[0]['total'] > 0) {
                $this->sys_error("Nama department sudah ada");
                exit;
            }

            // Update department
            $sql = "UPDATE m_department SET 
                    M_DepartmentCode = ?,
                    M_DepartmentName = ?,
                    M_DepartmentUserID = ?,
                    M_DepartmentLastUpdated = NOW()
                    WHERE M_DepartmentID = ?";
            $qry = $this->db->query($sql, [
                $codeDepartment,
                $nameDepartment,
                $userId,
                $departmentId
            ]);

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

            $this->db->trans_commit();

            // Get updated record
            $sql_get = "SELECT * FROM m_department WHERE M_DepartmentID = ? AND M_DepartmentIsActive = 'Y'";
            $records = $this->db->query($sql_get, [$departmentId])->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['departmentId']) || !is_numeric($prm['departmentId'])) {
                $this->sys_error("Department ID is required");
                exit;
            }

            $departmentId = $prm['departmentId'];

            // Check if department exists and is active
            $sql_exist = "SELECT COUNT(*) as total FROM m_department 
                         WHERE M_DepartmentID = ? AND M_DepartmentIsActive = 'Y'";
            $qry_exist = $this->db->query($sql_exist, [$departmentId]);
            if ($qry_exist && $qry_exist->result_array()[0]['total'] == 0) {
                $this->sys_error("Department not found");
                exit;
            }

            // Soft delete by updating IsActive to 'N'
            $sql = "UPDATE m_department SET 
                    M_DepartmentIsActive = 'N',
                    M_DepartmentUserID = ?,
                    M_DepartmentLastUpdated = NOW()
                    WHERE M_DepartmentID = ?";
            $qry = $this->db->query($sql, [
                $userId,
                $departmentId
            ]);

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

            $this->db->trans_commit();

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