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

header('Content-Type: application/json');

try {

    $body = json_decode(file_get_contents("php://input"), true);

    $site_cd = $body['site_cd'] ?? '';
    $dept_mst_dept_cod = $body['dept_mst_dept_cod'] ?? '';

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

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

    $sql_header = "
        SELECT 
            dept_par.*
        FROM dept_mst
        LEFT JOIN dept_par 
            ON dept_mst.site_cd = dept_par.site_cd
            AND dept_mst.RowID = dept_par.mst_RowID
        WHERE dept_mst.site_cd = ?
            AND dept_mst.dept_mst_disable_flag = 0
            AND dept_mst.dept_mst_linen = 1
            AND dept_mst.dept_mst_dept_cod = ?
    ";

    $params = [$site_cd, $dept_mst_dept_cod];

    $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;
    }

    sqlsrv_free_stmt($stmt_header);

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

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

} catch (Exception $e) {

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

} finally {

    if (isset($conn)) {
        sqlsrv_close($conn);
    }
}
?>