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


$json = file_get_contents('php://input');
$result = json_decode($json, true);

$site_cd = $result['site_cd'] ?? '';
$date = $result['date'] ?? '';
$dept_mst_dept_cod = $result['dept_mst_dept_cod'] ?? '';

try {

    $sql = "
       SELECT
			d.dept_mst_dept_cod AS dept,
			p.dept_par_lin_cd   AS linen_item,
			p.dept_par_desc AS Linen_desc,
			ls.lri_ls1_issue1_qty,
			ls.lri_ls1_issue2_qty,
			SUM(
				CASE
					WHEN (
						ISNULL(p.dept_par_qty,0)
					  - ( 
						+ ISNULL(ls.lri_ls1_issue1_qty,0)
						+ ISNULL(ls.lri_ls1_issue2_qty,0)
						)
					) > 0
					THEN (
						ISNULL(p.dept_par_qty,0)
					  - ( 
						+ ISNULL(ls.lri_ls1_issue1_qty,0)
						+ ISNULL(ls.lri_ls1_issue2_qty,0)
						)
					)
					ELSE 0
				END
			) AS par_qty
		FROM dept_mst d
		JOIN dept_par p WITH (NOLOCK)
		  ON d.site_cd = p.site_cd
		 AND d.RowID   = p.mst_RowID

		OUTER APPLY (
			SELECT TOP 1 lm.RowID , lm.lri_mst_lri_no
			FROM lri_mst lm WITH (NOLOCK)
			WHERE lm.site_cd = ?
			  AND lm.lri_mst_department = d.dept_mst_dept_cod
			  AND lm.lri_mst_lri_date >= ?
			  AND lm.lri_mst_lri_date < DATEADD(DAY,1,?)
			ORDER BY lm.lri_mst_lri_date DESC, lm.RowID DESC
		) l

		LEFT JOIN lri_ls1 ls WITH (NOLOCK)
		ON ls.site_cd = ?
		AND ls.mst_RowID = l.RowID
		AND ls.lri_ls1_linen = p.dept_par_lin_cd
		
		LEFT JOIN lri_ref img WITH (NOLOCK)
		ON img.site_cd = ?
		AND img.mst_RowID = l.RowID

		WHERE d.site_cd = ?
		  AND d.dept_mst_disable_flag = 0
		  AND d.dept_mst_linen = 1
		  AND d.dept_mst_dept_cod = ?
		  AND img.attachment is not null
		  AND l.lri_mst_lri_no IS NOT NULL
		  AND (
				ISNULL(ls.lri_ls1_issue1_qty, 0) > 0
				OR ISNULL(ls.lri_ls1_issue2_qty, 0) > 0
			)

GROUP BY
    d.dept_mst_dept_cod,
    p.dept_par_lin_cd,
    p.dept_par_desc,
    ls.lri_ls1_issue1_qty,
    ls.lri_ls1_issue2_qty,
    l.lri_mst_lri_no

ORDER BY
    d.dept_mst_dept_cod,
    p.dept_par_lin_cd,
    p.dept_par_desc,
    ls.lri_ls1_issue1_qty,
    ls.lri_ls1_issue2_qty;";

    $params = [$site_cd,$date,$date,$site_cd,$site_cd,$site_cd,$dept_mst_dept_cod];

    $stmt = sqlsrv_query($conn, $sql, $params);
    if ($stmt === false) {
        throw new Exception("SQL error: " . print_r(sqlsrv_errors(), true));
    }

    $json = [];
    while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
        $json[] = $row;
    }
    sqlsrv_free_stmt($stmt);
    sqlsrv_close($conn);

    echo json_encode([
        'status'  => 'SUCCESS',
        'message' => 'PAR linen list retrieved successfully',
        'data'    => $json
    ]);
    exit();

} catch (Exception $e) {
    if (isset($conn)) @sqlsrv_close($conn);
    echo json_encode([
        'status'  => 'ERROR',
        'message' => $e->getMessage(),
        'data'    => []
    ]);
    exit();
}
?>