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

try {

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

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

    if ($site_cd === '' || $ler_no === '') {
        throw new Exception("Missing required parameters: site_cd or ler_no");
    }

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

    $sql_header = "
        SELECT 
            m.ler_mst_ler_no,
            m.ler_mst_ler_date,
            m.ler_mst_department,
            m.ler_mst_desc,
            m.ler_mst_contact,
            m.ler_mst_requester,
			d.ler_det_sign_by,
			d.ler_det_sign_by_id,
			d.ler_det_sign_by_contact,
            m.RowID
        FROM ler_mst m
        JOIN ler_det d WITH (NOLOCK)
            ON m.site_cd = d.site_cd
            AND m.RowID  = d.mst_RowID
        WHERE m.site_cd = ?
        AND m.ler_mst_ler_no = ?
    ";

    $stmt_header = sqlsrv_query($conn, $sql_header, [$site_cd, $ler_no]);

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

    $header = sqlsrv_fetch_array($stmt_header, SQLSRV_FETCH_ASSOC);

    if (!$header) {
        throw new Exception("Record not found");
    }

    $mst_RowID = $header['RowID'];

    if ($header['ler_mst_ler_date'] instanceof DateTime) {
        $header['ler_mst_ler_date'] = $header['ler_mst_ler_date']->format('Y-m-d H:i:s');
    }

    sqlsrv_free_stmt($stmt_header);


    /* ================= DETAILS QUERY ================= */

    $sql_details = "
        SELECT *
        FROM ler_ls1
        WHERE site_cd = ?
        AND mst_RowID = ?
        ORDER BY RowID
    ";

    $stmt_details = sqlsrv_query($conn, $sql_details, [$site_cd, $mst_RowID]);

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

    $details = [];

    while ($row = sqlsrv_fetch_array($stmt_details, SQLSRV_FETCH_ASSOC)) {
        $details[] = $row;
    }

    sqlsrv_free_stmt($stmt_details);

    sqlsrv_close($conn);


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

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

} catch (Exception $e) {

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

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