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

try {

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

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

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

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

    $sql_header = "
        SELECT 
            m.lrr_mst_lrr_no,
            m.lrr_mst_lrr_date,
            m.lrr_mst_department,
            m.lrr_mst_desc,
            m.lrr_mst_requester_id,
			m.lrr_mst_status,
            m.lrr_mst_requester,
			d.lrr_det_sign_by,
			d.lrr_det_sign_by_id,
			d.lrr_det_sign_by_contact,
            m.RowID
        FROM lrr_mst m
        JOIN lrr_det d WITH (NOLOCK)
            ON m.site_cd = d.site_cd
            AND m.RowID  = d.mst_RowID
        WHERE m.site_cd = ?
        AND m.lrr_mst_lrr_no = ?
    ";

    $stmt_header = sqlsrv_query($conn, $sql_header, [$site_cd, $lrr_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['lrr_mst_lrr_date'] instanceof DateTime) {
        $header['lrr_mst_lrr_date'] = $header['lrr_mst_lrr_date']->format('Y-m-d H:i:s');
    }

    sqlsrv_free_stmt($stmt_header);


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

    $sql_details = "
        SELECT *
        FROM lrr_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" => []
    ]);
}
?>