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

$now = date("YmdHis");
$file_name = __DIR__ . "\\mobile_log\\_update_linen_request.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 ?? '');
    $ler_mst_ler_no     = trim($Header->ler_mst_ler_no ?? '');
    $dept_cd            = trim($Header->dept_mst_dept_cod ?? '');
    $dept_desc          = trim($Header->dept_mst_description ?? '');
    $ler_mst_ler_date   = trim($Header->request_date_time ?? '');
    $LOGINID            = trim($Header->LoginID ?? '');
	$status 			=  'OPN';

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

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

    // -----------------------------
    // GET mst_RowID
    // -----------------------------
    $sql_get = "SELECT RowID FROM ler_mst (NOLOCK) WHERE site_cd = ? AND ler_mst_ler_no = ?  AND ler_mst_ler_date >= ? AND ler_mst_ler_date < DATEADD(DAY,1,?)";
    $stmt = sqlsrv_query($conn, $sql_get, [$site_cd, $ler_mst_ler_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("LRQ not found");

    $mst_RowID = $row['RowID'];
	
	// -----------------------------
    // UPDATE lri_mst
    // -----------------------------
    $sql_upd_mst = "
        UPDATE ler_mst
        SET
            ler_mst_status     = ?,
            audit_user         = ?,
            audit_date         = GETDATE(),
            mbl_audit_user     = ?,
            mbl_audit_date     = GETDATE()
        WHERE site_cd = ?
          AND RowID = ?
    ";

    $params_mst = [
        $status,
        $LOGINID,
        $LOGINID,
        $site_cd,
        $mst_RowID
    ];

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


    // -----------------------------
    // UPDATE ler_det
    // -----------------------------
    $sql_upd_det = "
        UPDATE ler_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 ler_det error: " . print_r(sqlsrv_errors(), true));
    sqlsrv_free_stmt($stmt);

    // -----------------------------
    // UPDATE lri_ls1
    // Must have rowid
    // -----------------------------
    $sql_upd_ls1 = "
        UPDATE ler_ls1
        SET
            ler_ls1_linen   = ?,
			ler_ls1_issue1_qty = ?,
			ler_ls1_issue2_qty = ?,
			ler_ls1_remark = ?,
            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_item ?? ''));
        $issue1_qty = trim((string)($d->issue1_qty ?? ($d->issue1_qty ?? '')));
        $issue2_qty = trim((string)($d->issue2_qty ?? ($d->issue2_qty ?? '')));
        $remark = trim((string)($d->remark ?? ($d->remark ?? '')));
        $rowid  = trim((string)($d->RowID ?? ($d->RowID ?? '')));

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

        $issue1_qty = ($issue1_qty === '') ? null : (float)$issue1_qty;
        $issue2_qty = ($issue2_qty === '') ? null : (float)$issue2_qty;

        $params_ls1 = [
            $linen,
			$issue1_qty,
			$issue2_qty,
			$remark,
            $LOGINID,
            $LOGINID,
            $site_cd,
            $mst_RowID,
            $rowid
        ];

        $stmt = sqlsrv_query($conn, $sql_upd_ls1, $params_ls1);
        if (!$stmt) {
            throw new Exception("Update ler_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 ler_ls2_varchar2
            FROM ler_ls2 WITH (NOLOCK)
            WHERE site_cd = ? AND mst_RowID = ?
            ORDER BY ler_ls2_datetime1 DESC, RowID DESC
        ";
        $stmt = sqlsrv_query($conn, $sql_chk_ls2, [$site_cd, $mst_RowID]);
        if ($stmt === false) {
            throw new Exception("Select ler_ls2 latest status error: " . print_r(sqlsrv_errors(), true));
        }

        $lastStatus = '';
        if ($r = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
            $lastStatus = trim($r['ler_ls2_varchar2'] ?? '');
        }
        sqlsrv_free_stmt($stmt);
		
		
		// B) Check if same status already exists anywhere for this mst_RowID
		$sql_chk_exists = "
			SELECT 1
			FROM ler_ls2 WITH (NOLOCK)
			WHERE site_cd = ? AND mst_RowID = ? AND ler_ls2_varchar2 = ?
		";
		$stmt = sqlsrv_query($conn, $sql_chk_exists, [$site_cd, $mst_RowID, $status]);
		if ($stmt === false) {
			throw new Exception("Select ler_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_lri_ls2 = "
                INSERT INTO ler_ls2 (
                    site_cd, mst_RowID,
                    ler_ls2_varchar1,   -- status cd
                    ler_ls2_varchar2,   -- status desc
                    ler_ls2_varchar3,   -- originator
                    ler_ls2_varchar4,   -- name
                    ler_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,
                $ler_mst_ler_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" => 'Linen Request ' . $ler_mst_ler_no . ' updated successfully',
        "lri_mst_lri_no" => $ler_mst_ler_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();
}
?>