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

try {

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

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

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

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

    $sql_header = "
        SELECT 
            m.lss_mst_lss_no,
            m.lss_mst_lss_date,
            m.lss_mst_department,
            m.lss_mst_desc,
            m.lss_mst_hod,
            m.lss_mst_hod_id,
			m.lss_mst_lss_year,
			m.lss_mst_lss_month,
			m.lss_mst_status,
            d.lss_det_varchar1,
            d.lss_det_varchar2,
            d.lss_det_varchar3,
			
            m.RowID
        FROM lss_mst m
        JOIN lss_det d WITH (NOLOCK)
            ON m.site_cd = d.site_cd
            AND m.RowID  = d.mst_RowID
        WHERE m.site_cd = ?
          AND m.lss_mst_lss_no = ?
    ";

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

    sqlsrv_free_stmt($stmt_header);


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

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