<?php

class Branchacc extends MY_Controller
{
    var $db;
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        echo "Branch API";
    }

    public function getBranch()
    {
        $sql = "SELECT M_BranchID,
                M_BranchCode,
                M_BranchName
                FROM m_branch
                JOIN s_regional ON M_BranchS_RegionalID = S_RegionalID
                AND S_RegionalIsActive = 'Y'
                WHERE M_BranchIsActive = 'Y'
                AND S_RegionalID IN (6)";
        $query = $this->db->query($sql);
        if (!$query) {
            $this->sys_error_db("Tidak menemukan data branch", $this->db);
            exit;
        }
        $rows = $query->result_array();
        $result = array(
            "records" => $rows,
        );
        $this->sys_ok($result);
    }

    public function validateDateRange($startDate, $endDate)
    {
        // Validasi input kosong
        if (!$startDate || !$endDate) {
            $this->sys_error("Parameter startdate dan enddate wajib diisi.");
            exit;
        }

        // Konversi ke timestamp
        $startTimestamp = strtotime($startDate);
        $endTimestamp = strtotime($endDate);
        $today = date('Y-m-d');
        $hMinus2Timestamp = strtotime('-2 days'); // H-2 dari hari ini

        // Validasi startdate harus sebelum atau sama dengan H-2
        if ($startTimestamp > $hMinus2Timestamp) {
            $this->sys_error("startdate harus sebelum atau sama dengan H-2 dari hari ini (" . date('Y-m-d', $hMinus2Timestamp) . ")");
            exit;
        }

        // Validasi jika enddate sebelum startdate
        if ($endTimestamp < $startTimestamp) {
            $this->sys_error("enddate tidak boleh lebih awal dari startdate.");
            exit;
        }

        // Jika validasi lolos
        $result = array(
            "startdate" => $startDate,
            "enddate" => $endDate
        );
        $this->sys_ok($result);
    }
}
