<?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 * 
        FROM lin_mst  
        WHERE lin_mst_disable_flag = '0' 
        AND site_cd = ?
        ORDER BY lin_mst_lin_cd ASC
    ";

    $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)) {


        $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" => []
    ]);
}
?>