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

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

    function listingRegional()
    {
        try {
            if (!$this->isLogin) {
                throw new Exception('Invalid token');
            }

            $sql = "SELECT
                    S_RegionalID,
                    S_RegionalName
                FROM s_regional
                WHERE S_RegionalIsActive = 'Y'";
            $que = $this->db->query($sql);
            if (!$que) {
                throw new Exception('failed to query list regional', 1);
            }
            $data = $que->result_array();

            $this->sys_ok([
                "records" => $data,
                "total" => count($data)
            ]);
        } catch (Exception $e) {
            $msg = '[Error] ' . $e->getMessage();
            $code = $e->getCode();
            if ($code == 0) {
                $this->sys_error($msg);
            } else {
                $this->sys_error_db($msg);
            }
            exit;
        }
    }

    function listingCabang()
    {
        try {
            if (!$this->isLogin) {
                throw new Exception('Invalid token');
            }

            $para = $this->sys_input;

            $sql = "SELECT
                    M_BranchID,
                    M_BranchName
                FROM m_branch
                WHERE M_BranchS_RegionalID = ?
                    AND M_BranchIsActive = 'Y'";
            $que = $this->db->query($sql, [$para['regionalID']]);
            if (!$que) {
                throw new Exception('failed to query list cabang', 1);
            }
            $data = $que->result_array();

            $this->sys_ok([
                "records" => $data,
                "total" => count($data)
            ]);
        } catch (Exception $e) {
            $msg = '[Error] ' . $e->getMessage();
            $code = $e->getCode();
            if ($code == 0) {
                $this->sys_error($msg);
            } else {
                $this->sys_error_db($msg);
            }
            exit;
        }
    }

    function lookupRuangan()
    {
        try {
            if (!$this->isLogin) {
                throw new Exception('Invalid token');
            }

            $para = $this->sys_input;

            $keyword = "%";
            if (isset($para['keyword'])) {
                $keyword .= $para['keyword'] . "%";
            }

            $limit = 10;
            $offset = 0;
            if ($para['latestPage'] > 0) {
                $offset = ($para['latestPage'] - 1) * $limit;
            }

            $sql = "SELECT
                    r.M_RuanganID AS id,
                    r.M_RuanganM_BranchID AS branch_id,
                    b.M_BranchName AS branch_name,
                    b.M_BranchCode AS branch_code,
                    r.M_RuanganCode AS code,
                    r.M_RuanganName AS name,
                    s.S_RegionalID AS regional_id,
                    s.S_RegionalName AS regional_name
                FROM m_ruangan r
                JOIN m_branch b
                    ON b.M_BranchID = r.M_RuanganM_BranchID
                    AND b.M_BranchIsActive = 'Y'
                JOIN s_regional s
                    ON s.S_RegionalID = b.M_BranchS_RegionalID
                WHERE r.M_RuanganIsActive = 'Y'
                    AND s.S_RegionalID = ?
                    AND (? = 0 OR r.M_RuanganM_BranchID = ?)
                    AND ( r.M_RuanganName LIKE ? OR r.M_RuanganCode LIKE ?)";

            $sql_data = $sql . " ORDER BY r.M_RuanganName ASC LIMIT ? OFFSET ? ";
            $que_data = $this->db->query($sql_data, [
                $para['regionalID'],
                $para['branchID'],
                $para['branchID'],
                $keyword,
                $keyword,
                $limit,
                $offset
            ]);
            if (!$que_data) {
                throw new Exception('failed to query data ruangan', 1);
            }
            $data = $que_data->result_array();

            $sql_total = "SELECT COUNT(*) AS total FROM ($sql) AS x";
            $que_total = $this->db->query($sql_total, [
                $para['regionalID'],
                $para['branchID'],
                $para['branchID'],
                $keyword,
                $keyword,
            ]);
            if (!$que_total) {
                throw new Exception('failed to query total data ruangan', 1);
            }
            $total = $que_total->row_array()['total'];

            $this->sys_ok([
                "records" => $data,
                "total" => $total
            ]);
        } catch (Exception $e) {
            $msg = '[Error] ' . $e->getMessage();
            $code = $e->getCode();
            if ($code == 0) {
                $this->sys_error($msg);
            } else {
                $this->sys_error_db($msg);
            }
            exit;
        }
    }

    function insertRuangan()
    {
        try {
            if (!$this->isLogin) {
                throw new Exception('Invalid token');
            }

            $para = $this->sys_input;
            $userid = $this->sys_user['M_UserID'];

            $this->db->trans_begin();

            $sql_check = "SELECT COUNT(*) AS exist
                FROM m_ruangan
                WHERE M_RuanganIsActive = 'Y'
                    AND M_RuanganM_BranchID = ?
                    AND M_RuanganCode = ?";

            $que_check = $this->db->query($sql_check, [
                $para['branchID'],
                $para['ruanganCode']
            ]);
            if (!$que_check) {
                throw new Exception('failed to check duplicate ruangan', 1);
            }

            if ($que_check->row_array()['exist'] > 0) {
                throw new Exception('ruangan already exists');
            }

            $sql = "INSERT INTO m_ruangan (
                    M_RuanganM_BranchID,
                    M_RuanganName,
                    M_RuanganCode,
                    M_RuanganUserID,
                    M_RuanganIsActive,
                    M_RuanganCreated,
                    M_RuanganLastUpdated
                ) VALUES (?,?,?,?,'Y',NOW(),NOW())";

            $que = $this->db->query($sql, [
                $para['branchID'],
                $para['ruanganName'],
                $para['ruanganCode'],
                $userid
            ]);
            if (!$que) {
                throw new Exception('failed to insert ruangan', 1);
            }

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

            $this->db->trans_commit();

            $this->sys_ok([
                "records" => [
                    "id" => $insert_id,
                    "name" => $para['ruanganName'],
                    "msg" => "Success Insert Ruangan"
                ]
            ]);
        } catch (Exception $e) {
            $this->db->trans_rollback();

            $msg = '[Error] ' . $e->getMessage();
            $code = $e->getCode();
            if ($code == 0) {
                $this->sys_error($msg);
            } else {
                $this->sys_error_db($msg);
            }
            exit;
        }
    }

    function updateRuangan()
    {
        try {
            if (!$this->isLogin) {
                throw new Exception('Invalid token');
            }

            $para = $this->sys_input;
            $userid = $this->sys_user['M_UserID'];

            $this->db->trans_begin();

            $sql_check = "SELECT COUNT(*) AS exist
                FROM m_ruangan
                WHERE M_RuanganIsActive = 'Y'
                    AND M_RuanganM_BranchID = ?
                    AND M_RuanganCode = ?
                    AND M_RuanganID != ?";

            $que_check = $this->db->query($sql_check, [
                $para['branchID'],
                $para['ruanganCode'],
                $para['ruanganID']
            ]);
            if (!$que_check) {
                throw new Exception('failed to check duplicate ruangan', 1);
            }

            if ($que_check->row_array()['exist'] > 0) {
                throw new Exception('ruangan already exists');
            }

            $sql = "UPDATE m_ruangan
                SET
                    M_RuanganM_BranchID = ?,
                    M_RuanganName = ?,
                    M_RuanganCode = ?,
                    M_RuanganUserID = ?,
                    M_RuanganLastUpdated = NOW()
                WHERE M_RuanganID = ?
                    AND M_RuanganIsActive = 'Y'";

            $que = $this->db->query($sql, [
                $para['branchID'],
                $para['ruanganName'],
                $para['ruanganCode'],
                $userid,
                $para['ruanganID']
            ]);
            if (!$que) {
                throw new Exception('failed to update ruangan', 1);
            }

            $this->db->trans_commit();

            $this->sys_ok([
                "records" => [
                    "id" => $para['ruanganID'],
                    "name" => $para['ruanganName'],
                    "msg" => "Success Update Ruangan"
                ]
            ]);
        } catch (Exception $e) {
            $this->db->trans_rollback();

            $msg = '[Error] ' . $e->getMessage();
            $code = $e->getCode();
            if ($code == 0) {
                $this->sys_error($msg);
            } else {
                $this->sys_error_db($msg);
            }
            exit;
        }
    }

    function deleteRuangan()
    {
        try {
            if (!$this->isLogin) {
                throw new Exception('Invalid token');
            }

            $para = $this->sys_input;
            $userid = $this->sys_user['M_UserID'];

            $this->db->trans_begin();

            $sql = "UPDATE m_ruangan
                SET
                    M_RuanganIsActive = 'N',
                    M_RuanganUserID = ?,
                    M_RuanganDeleted = NOW(),
                    M_RuanganLastUpdated = NOW()
                WHERE M_RuanganID = ?
                    AND M_RuanganIsActive = 'Y'";

            $que = $this->db->query($sql, [
                $userid,
                $para['ruanganID']
            ]);
            if (!$que) {
                throw new Exception('failed to delete ruangan', 1);
            }

            $this->db->trans_commit();

            $this->sys_ok([
                "records" => [
                    "id" => $para['ruanganID'],
                    "msg" => "Success Update Ruangan"
                ]
            ]);
        } catch (Exception $e) {
            $this->db->trans_rollback();

            $msg = '[Error] ' . $e->getMessage();
            $code = $e->getCode();
            if ($code == 0) {
                $this->sys_error($msg);
            } else {
                $this->sys_error_db($msg);
            }
            exit;
        }
    }
}
