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

try {

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

    $site_cd = $body['site_cd'] ?? '';
    $period  = $body['period'] ?? '';
    $date    = $body['date'] ?? ''; // optional
	

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

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

    $sql = "
        SELECT
            m.ldry_mst_ldry_no,
            m.ldry_mst_ldry_period,
            m.ldry_mst_ldry_date,
            m.ldry_mst_status,
            m.ldry_mst_desc,
            m.RowID,
            ISNULL(ls1_cnt.total_count, 0) AS total_count
        FROM ldry_mst m
        OUTER APPLY (
            SELECT COUNT(*) AS total_count
            FROM ldry_ls1 ls1
            WHERE ls1.site_cd = m.site_cd
            AND ls1.mst_rowid = m.RowID
        ) ls1_cnt
       WHERE m.site_cd = '".$site_cd."'
		" . ($date ? "AND CONVERT(date, m.ldry_mst_ldry_date) = '".$date."'" : "") . "
		" . ($period ? "AND m.ldry_mst_ldry_period = '".$period."'" : "") . "
		ORDER BY m.ldry_mst_ldry_date DESC
	";

   

    $stmt = sqlsrv_query($conn, $sql);

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

    $details = [];

    while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {

        if ($row['ldry_mst_ldry_date'] instanceof DateTime) {
            $row['ldry_mst_ldry_date'] = $row['ldry_mst_ldry_date']->format('Y-m-d');
        }

        $details[] = $row;
    }

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

    sqlsrv_free_stmt($stmt);

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

} catch (Exception $e) {

    echo json_encode([
        "status"  => "ERROR",
        "message" => $e->getMessage(),
        "details" => []
    ]);
} finally {
    if (isset($conn)) {
        sqlsrv_close($conn);
    }
}
?>