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

header('Content-Type: application/json; charset=utf-8');

try {
    // Read JSON (POST)
    $body = json_decode(file_get_contents("php://input"), true);

    $site_cd      = $body['Site_cd'] ?? '';
    $Screenname   = $body['Screenname'] ?? '';
    $dept_cd      = $body['item']['dept_mst_dept_cod'] ?? '';
    $selectedDate = $body['selectedDate'] ?? ''; // dd-mm-yyyy (24-02-2026)

    if ($site_cd === '' || $dept_cd === '' || $selectedDate === '') {
        throw new Exception("Missing required parameters: Site_cd / item.dept_mst_dept_cod / selectedDate");
    }

    // Convert dd-mm-yyyy -> yyyy-mm-dd
    $dt = DateTime::createFromFormat('d-m-Y', $selectedDate);
    if (!$dt) {
        throw new Exception("Invalid selectedDate format. Use dd-mm-yyyy (e.g., 24-02-2026)");
    }
    $sqlDate = $dt->format('Y-m-d');

    /* -------------------------------------------------------
       1) Check LRI header (need RowID for lri_ls1.mst_RowID)
    -------------------------------------------------------- */
    $sqlHdr = "
        SELECT TOP 1
            lm.RowID AS mst_RowID,
            lm.lri_mst_lri_no,
            lm.lri_mst_lri_date,
            lm.lri_mst_status,
            status_color = CASE
                              WHEN lm.lri_mst_status = 'OPN' THEN '#F79009'
                              WHEN lm.lri_mst_status = 'CMP' THEN '#2E90FA'
                              WHEN lm.lri_mst_status = 'CLO' THEN '#12B76A'
                              ELSE '#D0D5DD'
                           END
        FROM lri_mst lm WITH (NOLOCK)
        WHERE lm.site_cd = ?
          AND lm.lri_mst_department = ?
          AND lm.lri_mst_lri_date >= ?
          AND lm.lri_mst_lri_date < DATEADD(DAY,1,?)
        ORDER BY lm.lri_mst_lri_date DESC
    ";

    $stmtHdr = sqlsrv_query($conn, $sqlHdr, [$site_cd, $dept_cd, $sqlDate, $sqlDate]);
    if ($stmtHdr === false) {
        throw new Exception("Header SQL error: " . print_r(sqlsrv_errors(), true));
    }

    $hdr = sqlsrv_fetch_array($stmtHdr, SQLSRV_FETCH_ASSOC);
    sqlsrv_free_stmt($stmtHdr);

    /* -------------------------------------------------------
       2) Line query
       - If LRI exists: read lri_ls1 and calculate sf_qty + sort shortfall first
       - If not exists: read dept_par (default list)
    -------------------------------------------------------- */
    if ($hdr && !empty($hdr['mst_RowID'])) {

        $mstRowID = $hdr['mst_RowID'];

		if($Screenname === 'EditDailylinenRoutine'){
			
			$sqlLines = "
            SELECT
                linen      = ls.lri_ls1_linen,
                par_qty    = ls.lri_ls1_par_qty,
                issue1_qty = ls.lri_ls1_issue1_qty,
                issue2_qty = ls.lri_ls1_issue2_qty,
                bal_qty    = ls.lri_ls1_bal_qty,
				sh_qty     = ls.lri_ls1_sf_qty,

                -- Shortfall qty (SF): if bal < par then par - bal else 0
                sf_qty     = CASE
                                WHEN ISNULL(ls.lri_ls1_bal_qty,0) < ISNULL(ls.lri_ls1_par_qty,0)
                                THEN ISNULL(ls.lri_ls1_par_qty,0) - ISNULL(ls.lri_ls1_bal_qty,0)
                                ELSE 0
                             END,

                remark     = ls.lri_ls1_remark,
                [desc]     = ls.lri_ls1_linen,
                site_cd    = ls.site_cd,
                mst_RowID  = ls.mst_RowID,
                source_rowid = ls.RowID
            FROM lri_ls1 ls WITH (NOLOCK)
            WHERE ls.site_cd = ?
              AND ls.mst_RowID = ?
            ORDER BY
                -- Shortfall items first (top)
                CASE
                    WHEN ISNULL(ls.lri_ls1_bal_qty,0) < ISNULL(ls.lri_ls1_par_qty,0) THEN 0
                    ELSE 1
                END,
                -- Biggest shortfall first
                (ISNULL(ls.lri_ls1_par_qty,0) - ISNULL(ls.lri_ls1_bal_qty,0)) DESC,
                -- Then linen name/code
                ls.lri_ls1_linen";
			
		}else{
			
			
			$sqlLines = "
            SELECT
                linen      = ls.lri_ls1_linen,
                par_qty    = ls.lri_ls1_par_qty,
                issue1_qty = ls.lri_ls1_issue1_qty,
                issue2_qty = ls.lri_ls1_issue2_qty,
                bal_qty    = ls.lri_ls1_bal_qty,
				sh_qty     = ls.lri_ls1_sf_qty,

                -- Shortfall qty (SF): if bal < par then par - bal else 0
                sf_qty     = CASE
                                WHEN ISNULL(ls.lri_ls1_bal_qty,0) < ISNULL(ls.lri_ls1_par_qty,0)
                                THEN ISNULL(ls.lri_ls1_par_qty,0) - ISNULL(ls.lri_ls1_bal_qty,0)
                                ELSE 0
                             END,

                remark     = ls.lri_ls1_remark,
                [desc]     = ls.lri_ls1_linen,
                site_cd    = ls.site_cd,
                mst_RowID  = ls.mst_RowID,
                source_rowid = ls.RowID
            FROM lri_ls1 ls WITH (NOLOCK)
            WHERE ls.site_cd = ?
              AND ls.mst_RowID = ?
            ORDER BY
			 -- use sh_qty if not null, else use calculated sf_qty
			CASE 
				WHEN COALESCE(ls.lri_ls1_sf_qty,
							  CASE
								  WHEN ls.lri_ls1_par_qty IS NOT NULL
								   AND ls.lri_ls1_bal_qty IS NOT NULL
								   AND ls.lri_ls1_bal_qty < ls.lri_ls1_par_qty
								  THEN (ls.lri_ls1_par_qty - ls.lri_ls1_bal_qty)
								  ELSE 0
							  END
					 ) > 0 THEN 0
				ELSE 1
			END,

			COALESCE(ls.lri_ls1_sf_qty,
					 CASE
						 WHEN ls.lri_ls1_par_qty IS NOT NULL
						  AND ls.lri_ls1_bal_qty IS NOT NULL
						  AND ls.lri_ls1_bal_qty < ls.lri_ls1_par_qty
						 THEN (ls.lri_ls1_par_qty - ls.lri_ls1_bal_qty)
						 ELSE 0
					 END
			) ASC,

			ls.lri_ls1_linen;";
			
			
			
		}
		
        

        $params = [$site_cd, $mstRowID];

    } else {

        $sqlLines = "
            SELECT
                linen         = p.dept_par_lin_cd,
                par_qty       = ISNULL(p.dept_par_qty,0),
                issue1_qty    = Null,
                issue2_qty    = Null,
                bal_qty       = Null,
                sf_qty        = Null,
                remark        = p.dept_par_remark,
                [desc]        = p.dept_par_desc,
                site_cd       = p.site_cd,
                mst_RowID     = p.mst_RowID,
                source_rowid  = p.RowID
            FROM dept_mst m WITH (NOLOCK)
            JOIN dept_par p WITH (NOLOCK)
              ON m.site_cd = p.site_cd
             AND m.RowID   = p.mst_RowID
            WHERE m.site_cd = ?
              AND m.dept_mst_dept_cod = ?
              AND m.dept_mst_disable_flag = '0'
            ORDER BY p.dept_par_lin_cd
        ";

        $params = [$site_cd, $dept_cd];
        $hdr = null;
    }

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

    $data = [];
    while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
        foreach ($row as $k => $v) {
            if ($v instanceof DateTime) {
                $row[$k] = $v->format('Y-m-d H:i:s');
            }
        }
        $data[] = $row;
    }
    sqlsrv_free_stmt($stmt);

    // Format header date
    if ($hdr && isset($hdr['lri_mst_lri_date']) && $hdr['lri_mst_lri_date'] instanceof DateTime) {
        $hdr['lri_mst_lri_date'] = $hdr['lri_mst_lri_date']->format('Y-m-d H:i:s');
    }

    sqlsrv_close($conn);

    echo json_encode([
        "status" => "SUCCESS",
        "header" => $hdr,   // null if not exists
        "data"   => $data
    ]);
    exit();

} catch (Exception $e) {

    if (isset($conn)) {
        @sqlsrv_close($conn);
    }

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