<?php
require_once('config.php');

try {

    $body = json_decode(file_get_contents("php://input"), true);
    $site_cd = $body['site_cd'] ?? '';

    if ($site_cd === '') {
        throw new Exception("Missing required parameter: site_cd");
    }

    /* ================= HEADER QUERY ================= */

    $sql_header = "
        SELECT 
            licl_mst_licl_period,  
            licl_mst_licl_date_frm, 
            licl_mst_licl_date_to,  			
            licl_mst_desc  
        FROM licl_mst  
        WHERE licl_mst_status <> 'CLO'
        AND site_cd = ?
        ORDER BY licl_mst_create_date DESC
    ";

    $params = [$site_cd];

    $stmt_header = sqlsrv_query($conn, $sql_header, $params);

    if ($stmt_header === false) {
        throw new Exception(print_r(sqlsrv_errors(), true));
    }

    $headers = [];

    while ($row = sqlsrv_fetch_array($stmt_header, SQLSRV_FETCH_ASSOC)) {

        // Optional: format date
        if ($row['licl_mst_licl_date_frm']) {
            $row['licl_mst_licl_date_frm'] = $row['licl_mst_licl_date_frm']->format('Y-m-d');
        }

        if ($row['licl_mst_licl_date_to']) {
            $row['licl_mst_licl_date_to'] = $row['licl_mst_licl_date_to']->format('Y-m-d');
        }

        $headers[] = $row;
    }

    if (empty($headers)) {
        throw new Exception("No records found");
    }

    sqlsrv_free_stmt($stmt_header);

    /* ================= RESPONSE ================= */

    echo json_encode([
        "status"  => "SUCCESS",
        "header"  => $headers
    ]);

} catch (Exception $e) {

    if (isset($conn)) sqlsrv_close($conn);

    echo json_encode([
        "status"  => "ERROR",
        "message" => $e->getMessage(),
        "header"  => [],
        "details" => []
    ]);
}
?>