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

$now = date("YmdHis");
$file_name = __DIR__ . "\\mobile_log\\_update_summary_linen_master.log";

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

try {
    if (!$result) {
        throw new Exception("Invalid JSON payload");
    }

    if (!isset($result->header) || !isset($result->details)) {
        throw new Exception("Missing header or details");
    }

    $Header  = $result->header;
    $details = $result->details;

    if (count($details) == 0) {
        throw new Exception("Details empty");
    }

    // Begin transaction
    if (!sqlsrv_begin_transaction($conn)) {
        throw new Exception("Transaction start failed: " . print_r(sqlsrv_errors(), true));
    }

    // -----------------------------
    // HEADER DATA
    // -----------------------------
    $site_cd            = trim($Header->site_cd ?? '');
    $lri_mst_lri_no     = trim($Header->lri_mst_lri_no ?? '');
    $dept_cd            = trim($Header->dept_mst_dept_cod ?? '');
    $dept_desc          = trim($Header->dept_mst_description ?? '');
    $lri_mst_lri_date   = trim($Header->lri_mst_lri_date ?? '');
    $LOGINID            = trim($Header->login_id ?? '');
    $rawStatus 			= $Header->status ?? false;
	$status 			= filter_var($rawStatus, FILTER_VALIDATE_BOOLEAN) ? 'CNT' : 'OPN';

    if ($site_cd === '' || $lri_mst_lri_no === '') {
        throw new Exception("site_cd and lri_mst_lri_no required for update");
    }

    // Date convert
    $dt = DateTime::createFromFormat('d-m-Y', $lri_mst_lri_date);
    if (!$dt) $dt = DateTime::createFromFormat('Y-m-d', $lri_mst_lri_date);
    if (!$dt) throw new Exception("Invalid date format");
    $sqlDate = $dt->format('Y-m-d');

    // -----------------------------
    // GET mst_RowID
    // -----------------------------
    $sql_get = "SELECT RowID FROM lri_mst (NOLOCK) WHERE site_cd = ? AND lri_mst_lri_no = ?  AND lri_mst_lri_date >= ? AND lri_mst_lri_date < DATEADD(DAY,1,?)";
    $stmt = sqlsrv_query($conn, $sql_get, [$site_cd, $lri_mst_lri_no, $sqlDate,$sqlDate]);
    if (!$stmt) throw new Exception("Get RowID error: " . print_r(sqlsrv_errors(), true));

    $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
    sqlsrv_free_stmt($stmt);

    if (!$row) throw new Exception("LRI not found");

    $mst_RowID = $row['RowID'];

    // -----------------------------
    // UPDATE lri_mst
    // -----------------------------
    $sql_upd_mst = "
        UPDATE lri_mst
        SET
            lri_mst_lri_date   = ?,
            lri_mst_status     = ?,
            lri_mst_desc       = ?,
            lri_mst_department = ?,
            audit_user         = ?,
            audit_date         = GETDATE(),
            mbl_audit_user     = ?,
            mbl_audit_date     = GETDATE()
        WHERE site_cd = ?
          AND RowID = ?
    ";

    $params_mst = [
        $sqlDate,
        $status,
        $dept_desc,
        $dept_cd,
        $LOGINID,
        $LOGINID,
        $site_cd,
        $mst_RowID
    ];

    $stmt = sqlsrv_query($conn, $sql_upd_mst, $params_mst);
    if (!$stmt) throw new Exception("Update lri_mst error: " . print_r(sqlsrv_errors(), true));
    sqlsrv_free_stmt($stmt);

    // -----------------------------
    // UPDATE lri_det
    // -----------------------------
    $sql_upd_det = "
        UPDATE lri_det
        SET
            audit_user     = ?,
            audit_date     = GETDATE(),
            mbl_audit_user = ?,
            mbl_audit_date = GETDATE()
        WHERE site_cd = ?
          AND mst_RowID = ?
    ";

    $stmt = sqlsrv_query($conn, $sql_upd_det, [$LOGINID, $LOGINID, $site_cd, $mst_RowID]);
    if (!$stmt) throw new Exception("Update lri_det error: " . print_r(sqlsrv_errors(), true));
    sqlsrv_free_stmt($stmt);

    // -----------------------------
    // UPDATE lri_ls1
    // Must have rowid
    // -----------------------------
    $sql_upd_ls1 = "
        UPDATE lri_ls1
        SET
            lri_ls1_linen   = ?,
            lri_ls1_par_qty = ?,
            lri_ls1_bal_qty = ?,
            audit_user      = ?,
            audit_date      = GETDATE(),
            mbl_audit_user  = ?,
            mbl_audit_date  = GETDATE()
        WHERE site_cd = ?
          AND mst_RowID = ?
          AND RowID = ?
    ";

    foreach ($details as $d) {

        $linen  = trim((string)($d->linen ?? ''));
        $parQty = trim((string)($d->par_qty ?? ''));
        $balQty = trim((string)($d->qty_entered ?? ($d->bal_qty ?? '')));
        $rowid  = trim((string)($d->source_rowid ?? ($d->source_rowid ?? '')));

        if ($rowid === '') {
            throw new Exception("RowID required for update in lri_ls1");
        }

        $parQty = ($parQty === '') ? null : (float)$parQty;
        $balQty = ($balQty === '') ? null : (float)$balQty;

        $params_ls1 = [
            $linen,
            $parQty,
            $balQty,
            $LOGINID,
            $LOGINID,
            $site_cd,
            $mst_RowID,
            $rowid
        ];

        $stmt = sqlsrv_query($conn, $sql_upd_ls1, $params_ls1);
        if (!$stmt) {
            throw new Exception("Update lri_ls1 error: " . print_r(sqlsrv_errors(), true));
        }
        sqlsrv_free_stmt($stmt);
    }
	
	    // ---------------------------------------------------------------------
        // 5) Insert STATUS AUDIT into lri_ls2 (avoid inserting same status multiple times)
        //    Rule: if latest status == new status -> SKIP
        // ---------------------------------------------------------------------

        // Get latest status for this mst_RowID
        $sql_chk_ls2 = "
            SELECT TOP 1 lri_ls2_varchar2
            FROM lri_ls2 WITH (NOLOCK)
            WHERE site_cd = ? AND mst_RowID = ?
            ORDER BY lri_ls2_datetime1 DESC, RowID DESC
        ";
        $stmt = sqlsrv_query($conn, $sql_chk_ls2, [$site_cd, $mst_RowID]);
        if ($stmt === false) {
            throw new Exception("Select lri_ls2 latest status error: " . print_r(sqlsrv_errors(), true));
        }

        $lastStatus = '';
        if ($r = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
            $lastStatus = trim($r['lri_ls2_varchar1'] ?? '');
        }
        sqlsrv_free_stmt($stmt);
		
		// B) Check if same status already exists anywhere for this mst_RowID
		$sql_chk_exists = "
			SELECT 1
			FROM lri_ls2 WITH (NOLOCK)
			WHERE site_cd = ? AND mst_RowID = ? AND lri_ls2_varchar2 = ?
		";
		$stmt = sqlsrv_query($conn, $sql_chk_exists, [$site_cd, $mst_RowID, $status]);
		if ($stmt === false) {
			throw new Exception("Select lri_ls2 exists status error: " . print_r(sqlsrv_errors(), true));
		}
		$existsSameStatus = (sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC) !== null);
		sqlsrv_free_stmt($stmt);

        // Insert only if status changed
        if ($lastStatus !== $status && !$existsSameStatus) {

            
            $originator = $LOGINID; // you can change if you have separate originator
            $name       = $LOGINID; // replace with actual name if you have it
			
			
			$sql_upd_det = "
				UPDATE lri_ls2
				SET
					lri_ls2_datetime2 	= GETDATE(),
					audit_user     		= ?,
					audit_date     		= GETDATE(),
					mbl_audit_user 		= ?,
					mbl_audit_date 		= GETDATE()
				WHERE site_cd = ?
				  AND mst_RowID = ?
				  AND lri_ls2_datetime2 IS NULL
			";

			$stmt = sqlsrv_query($conn, $sql_upd_det, [$LOGINID, $LOGINID, $site_cd, $mst_RowID]);
			if (!$stmt) throw new Exception("Update lri_ls2 error: " . print_r(sqlsrv_errors(), true));
			sqlsrv_free_stmt($stmt);


            $sql_lri_ls2 = "
                INSERT INTO lri_ls2 (
                    site_cd, mst_RowID,
                    lri_ls2_varchar1,   -- status cd
                    lri_ls2_varchar2,   -- status desc
                    lri_ls2_varchar3,   -- originator
                    lri_ls2_varchar4,   -- name
                    lri_ls2_datetime1,  -- start date
                    audit_user, audit_date,
                    mbl_audit_user, mbl_audit_date,
                    column1, column2, column3, column4, column5
                )
                VALUES (
                    ?, ?,
                    ?, ?,
                    ?, ?,
                    GETDATE(),
                    ?, GETDATE(),
                    ?, GETDATE(),
                    NULL, NULL, NULL, NULL, NULL
                )
            ";

            $params_ls2 = [
                $site_cd,
                $mst_RowID,
                $lri_mst_lri_no,
                $status,
                $originator,
                $name,
                $LOGINID,
                $LOGINID
            ];

            $stmt = sqlsrv_query($conn, $sql_lri_ls2, $params_ls2);
            if ($stmt === false) {
                throw new Exception("Insert lri_ls2 (status audit) error: " . print_r(sqlsrv_errors(), true));
            }
            sqlsrv_free_stmt($stmt);
        }

    // Commit
    if (!sqlsrv_commit($conn)) {
        throw new Exception("Commit failed");
    }

    sqlsrv_close($conn);

    echo json_encode([
        "status" => "SUCCESS",
        "message" => 'Daily Linen Routine ' . $lri_mst_lri_no . ' updated successfully',
        "lri_mst_lri_no" => $lri_mst_lri_no,
        "mst_RowID" => $mst_RowID
    ]);

} catch (Exception $e) {

    if (isset($conn)) @sqlsrv_rollback($conn);

    file_put_contents($file_name, $now . "\r\n" . $e->getMessage() . "\r\n\r\n", FILE_APPEND);

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

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