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

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

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

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

    // ---------------------------
    // Read header / details
    // ---------------------------
    if (isset($result->header)) {
        $Header = $result->header;
    } elseif (isset($result->Header) && is_array($result->Header) && count($result->Header) > 0) {
        $Header = $result->Header[0];
    } else {
        throw new Exception("Missing header (header/Header)");
    }

    if (isset($result->details) && is_array($result->details)) {
        $details = $result->details;
    } elseif (isset($result->Details) && is_array($result->Details)) {
        $details = $result->Details;
    } else {
        throw new Exception("Missing details (details/Details)");
    }

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

    // ---------------------------
    // Header values
    // ---------------------------
    $site_cd   				= trim($Header->site_cd ?? '');
    $lrj_no   				= trim($Header->lrj_no ?? ($Header->lrj_mst_lrj_no ?? ''));
    $period    				= trim($Header->period ?? ($Header->lrj_mst_lrj_period ?? ''));
    $lrj_date 				= trim($Header->lrj_date ?? ($Header->lrj_mst_lrj_date ?? ''));
    $desc      				= trim($Header->desc ?? ($Header->lrj_mst_desc ?? ''));
    $lrj_mst_department    	= trim($Header->lrj_mst_department ?? ($Header->lrj_mst_department ?? ''));
    $remark    = trim($Header->remark ?? ($Header->lrj_mst_remark ?? ''));
    $LOGINID   = trim($Header->LoginID ?? ($Header->loginid ?? ''));
    $status    = trim($Header->status ?? ($Header->lrj_mst_status ?? 'OPN'));

    if ($site_cd === '' || $lrj_no === '' || $period === '' || $lrj_date === '') {
        throw new Exception("Required header fields missing: site_cd / lrj_no / period / lrj_date");
    }


    // ---------------------------
    // Totals from details
    // ---------------------------
    $ttl_item = 0;
    $ttl_qty  = 0;

    foreach ($details as $d) {
        $linen = is_object($d) ? ($d->linen ?? ($d->lrj_ls1_linen ?? '')) : ($d['linen'] ?? ($d['lrj_ls1_linen'] ?? ''));
        $qty   = is_object($d) ? ($d->qty ?? ($d->lrj_ls1_qty ?? null)) : ($d['qty'] ?? ($d['lrj_ls1_qty'] ?? null));

        $linen = trim((string)$linen);
        if ($linen === '') continue;

        $ttl_item++;

        $qty = trim((string)$qty);
        $qty = ($qty === '') ? 0 : (float)$qty;
        $ttl_qty += $qty;
    }

    if ($ttl_item == 0) {
        throw new Exception("No valid linen items found in details");
    }

    // Begin transaction
    if (!sqlsrv_begin_transaction($conn)) {
        throw new Exception("Failed to begin transaction: " . print_r(sqlsrv_errors(), true));
    }

    // ---------------------------------------------------------------------
    // 1) Find existing master RowID
    // ---------------------------------------------------------------------
    $sql_get = "
        SELECT TOP 1 RowID, lrj_mst_status
        FROM lrj_mst
        WHERE site_cd = ?
          AND lrj_mst_lrj_no = ?
        ORDER BY RowID DESC
    ";

    $stmt = sqlsrv_query($conn, $sql_get, [$site_cd, $lrj_no]);
    if ($stmt === false) {
        throw new Exception("Select lrj_mst RowID error: " . print_r(sqlsrv_errors(), true));
    }

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

    $mst_RowID = $row['RowID'] ?? null;
    if (!$mst_RowID) {
        throw new Exception("Checklist not found for lrj_no: " . $lrj_no);
    }

    // ---------------------------------------------------------------------
    // 2) Update lrj_mst
    // ---------------------------------------------------------------------
    $sql_update_mst = "
        UPDATE lrj_mst
        SET lrj_mst_lrj_period  = ?,
            lrj_mst_lrj_date    = ?,
            lrj_mst_status      = ?,
            lrj_mst_ttl_item    = ?,
            lrj_mst_ttl_qty     = ?,
            lrj_mst_desc        = ?,
            lrj_mst_department  = ?,
            lrj_mst_remark      = ?,
            audit_user           = ?,
            audit_date           = GETDATE(),
            mbl_audit_user       = ?,
            mbl_audit_date       = GETDATE()
        WHERE site_cd = ?
          AND RowID   = ?
    ";

    $params_update_mst = [
        $period,
        $lrj_date,
        $status,
        $ttl_item,
        $ttl_qty,
        $desc,
		$lrj_mst_department,
        $remark,
        $LOGINID,
        $LOGINID,
        $site_cd,
        $mst_RowID
    ];

    $stmt = sqlsrv_query($conn, $sql_update_mst, $params_update_mst);
    if ($stmt === false) {
        throw new Exception("Update lrj_mst error: " . print_r(sqlsrv_errors(), true));
    }
    sqlsrv_free_stmt($stmt);

    // ---------------------------------------------------------------------
    // 3) Ensure lrj_det record exists
    // ---------------------------------------------------------------------
    $sql_chk_det = "
        SELECT TOP 1 RowID
        FROM lrj_det
        WHERE site_cd = ?
          AND mst_RowID = ?
        ORDER BY RowID DESC
    ";

    $stmt = sqlsrv_query($conn, $sql_chk_det, [$site_cd, $mst_RowID]);
    if ($stmt === false) {
        throw new Exception("Select lrj_det error: " . print_r(sqlsrv_errors(), true));
    }

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

    if (!$detRow) {
        $sql_insert_det = "
            INSERT INTO lrj_det (
                site_cd,
                mst_RowID,
                lrj_det_sign_by,
                lrj_det_sign_by_id,
                lrj_det_sign_by_contact,
                lrj_det_sign_by_title,
                lrj_det_sign_date,
                lrj_det_varchar1,
                lrj_det_varchar2,
                lrj_det_varchar3,
                lrj_det_varchar4,
                lrj_det_varchar5,
                lrj_det_varchar6,
                lrj_det_varchar7,
                lrj_det_varchar8,
                lrj_det_varchar9,
                lrj_det_varchar10,
                lrj_det_numeric1,
                lrj_det_numeric2,
                lrj_det_numeric3,
                lrj_det_numeric4,
                lrj_det_numeric5,
                lrj_det_datetime1,
                lrj_det_datetime2,
                lrj_det_datetime3,
                lrj_det_datetime4,
                lrj_det_datetime5,
                lrj_det_note1,
                audit_user,
                audit_date,
                mbl_audit_user,
                mbl_audit_date,
                column1,
                column2,
                column3,
                column4,
                column5
            )
            VALUES (
                ?, ?,
                NULL, NULL, NULL, NULL, NULL,
                NULL, NULL, NULL, NULL, NULL,
                NULL, NULL, NULL, NULL, NULL,
                NULL, NULL, NULL, NULL, NULL,
                NULL, NULL, NULL, NULL, NULL,
                NULL,
                ?, GETDATE(),
                ?, GETDATE(),
                NULL, NULL, NULL, NULL, NULL
            )
        ";

        $params_insert_det = [$site_cd, $mst_RowID, $LOGINID, $LOGINID];

        $stmt = sqlsrv_query($conn, $sql_insert_det, $params_insert_det);
        if ($stmt === false) {
            throw new Exception("Insert lrj_det error: " . print_r(sqlsrv_errors(), true));
        }
        sqlsrv_free_stmt($stmt);
    }

    // ---------------------------------------------------------------------
    // 4) Update existing lrj_ls1 if found, else insert
    //    Match logic: site_cd + mst_RowID + lrj_ls1_linen
    // ---------------------------------------------------------------------
    $sql_chk_ls1 = "
        SELECT TOP 1 RowID
        FROM lrj_ls1
        WHERE site_cd = ?
          AND mst_RowID = ?
          AND lrj_ls1_linen = ?
        ORDER BY RowID DESC
    ";

    $sql_update_ls1 = "
        UPDATE lrj_ls1
        SET lrj_ls1_qty      = ?,
            lrj_ls1_remark   = ?,
            audit_user        = ?,
            audit_date        = GETDATE(),
            mbl_audit_user    = ?,
            mbl_audit_date    = GETDATE()
        WHERE site_cd = ?
          AND RowID   = ?
    ";

    $sql_insert_ls1 = "
        INSERT INTO lrj_ls1 (
            site_cd,
            mst_RowID,
            lrj_ls1_linen,
            lrj_ls1_qty,
            lrj_ls1_remark,
            lrj_ls1_varchar1,
            lrj_ls1_varchar2,
            lrj_ls1_varchar3,
            lrj_ls1_varchar4,
            lrj_ls1_varchar5,
            lrj_ls1_numeric1,
            lrj_ls1_numeric2,
            lrj_ls1_numeric3,
            lrj_ls1_numeric4,
            lrj_ls1_numeric5,
            lrj_ls1_datetime1,
            lrj_ls1_datetime2,
            lrj_ls1_datetime3,
            lrj_ls1_datetime4,
            lrj_ls1_datetime5,
            audit_user,
            audit_date,
            mbl_audit_user,
            mbl_audit_date,
            column1,
            column2,
            column3,
            column4,
            column5
        )
        VALUES (
            ?, ?, ?, ?, ?,
            NULL, NULL, NULL, NULL, NULL,
            NULL, NULL, NULL, NULL, NULL,
            NULL, NULL, NULL, NULL, NULL,
            ?, GETDATE(),
            ?, GETDATE(),
            NULL, NULL, NULL, NULL, NULL
        )
    ";

    foreach ($details as $d) {
        $linen = is_object($d) ? ($d->linen ?? ($d->lrj_ls1_linen ?? '')) : ($d['linen'] ?? ($d['lrj_ls1_linen'] ?? ''));
        $qty   = is_object($d) ? ($d->qty ?? ($d->lrj_ls1_qty ?? null)) : ($d['qty'] ?? ($d['lrj_ls1_qty'] ?? null));
        $remark_ls1 = is_object($d) ? ($d->remark ?? ($d->lrj_ls1_remark ?? '')) : ($d['remark'] ?? ($d['lrj_ls1_remark'] ?? ''));

        $linen = trim((string)$linen);
        if ($linen === '') continue;

        $qty = trim((string)$qty);
        $qty = ($qty === '') ? null : (float)$qty;

        $remark_ls1 = trim((string)$remark_ls1);
        $remark_ls1 = ($remark_ls1 === '') ? null : $remark_ls1;

        $stmt = sqlsrv_query($conn, $sql_chk_ls1, [$site_cd, $mst_RowID, $linen]);
        if ($stmt === false) {
            throw new Exception("Select lrj_ls1 error: " . print_r(sqlsrv_errors(), true));
        }

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

        if ($ls1Row) {
            $stmt = sqlsrv_query($conn, $sql_update_ls1, [
                $qty,
                $remark_ls1,
                $LOGINID,
                $LOGINID,
                $site_cd,
                $ls1Row['RowID']
            ]);

            if ($stmt === false) {
                throw new Exception("Update lrj_ls1 error: " . print_r(sqlsrv_errors(), true));
            }
            sqlsrv_free_stmt($stmt);
        } else {
            $stmt = sqlsrv_query($conn, $sql_insert_ls1, [
                $site_cd,
                $mst_RowID,
                $linen,
                $qty,
                $remark_ls1,
                $LOGINID,
                $LOGINID
            ]);

            if ($stmt === false) {
                throw new Exception("Insert lrj_ls1 error: " . print_r(sqlsrv_errors(), true));
            }
            sqlsrv_free_stmt($stmt);
        }
    }

    // ---------------------------------------------------------------------
    // 5) Insert lrj_ls2 only if status changed / not exists
    // ---------------------------------------------------------------------
    $sql_chk_ls2 = "
        SELECT TOP 1 lrj_ls2_varchar2
        FROM lrj_ls2 WITH (NOLOCK)
        WHERE site_cd = ? AND mst_RowID = ?
        ORDER BY lrj_ls2_datetime1 DESC, RowID DESC
    ";

    $stmt = sqlsrv_query($conn, $sql_chk_ls2, [$site_cd, $mst_RowID]);
    if ($stmt === false) {
        throw new Exception("Select lrj_ls2 latest status error: " . print_r(sqlsrv_errors(), true));
    }

    $lastStatus = '';
    if ($r = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
        $lastStatus = trim($r['lrj_ls2_varchar2'] ?? '');
    }
    sqlsrv_free_stmt($stmt);

    $sql_chk_exists = "
        SELECT 1
        FROM lrj_ls2 WITH (NOLOCK)
        WHERE site_cd = ? AND mst_RowID = ? AND lrj_ls2_varchar2 = ?
    ";

    $stmt = sqlsrv_query($conn, $sql_chk_exists, [$site_cd, $mst_RowID, $status]);
    if ($stmt === false) {
        throw new Exception("Select lrj_ls2 exists status error: " . print_r(sqlsrv_errors(), true));
    }

    $existsSameStatus = (sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC) !== null);
    sqlsrv_free_stmt($stmt);

    if ($lastStatus !== $status && !$existsSameStatus) {
        $originator = $LOGINID;
        $name       = $LOGINID;

        $sql_lrj_ls2 = "
            INSERT INTO lrj_ls2 (
                site_cd,
                mst_RowID,
                lrj_ls2_varchar1,
                lrj_ls2_varchar2,
                lrj_ls2_varchar3,
                lrj_ls2_varchar4,
                lrj_ls2_varchar5,
                lrj_ls2_varchar6,
                lrj_ls2_varchar7,
                lrj_ls2_varchar8,
                lrj_ls2_varchar9,
                lrj_ls2_varchar10,
                lrj_ls2_numeric1,
                lrj_ls2_numeric2,
                lrj_ls2_numeric3,
                lrj_ls2_numeric4,
                lrj_ls2_numeric5,
                lrj_ls2_numeric6,
                lrj_ls2_numeric7,
                lrj_ls2_numeric8,
                lrj_ls2_numeric9,
                lrj_ls2_numeric10,
                lrj_ls2_datetime1,
                lrj_ls2_datetime2,
                lrj_ls2_datetime3,
                lrj_ls2_datetime4,
                lrj_ls2_datetime5,
                lrj_ls2_datetime6,
                lrj_ls2_datetime7,
                lrj_ls2_datetime8,
                lrj_ls2_datetime9,
                lrj_ls2_datetime10,
                audit_user,
                audit_date,
                mbl_audit_user,
                mbl_audit_date,
                column1,
                column2,
                column3,
                column4,
                column5
            )
            VALUES (
                ?, ?,
                ?, ?, ?, ?, NULL, NULL, NULL, NULL, NULL, NULL,
                NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
                GETDATE(), NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
                ?, GETDATE(),
                ?, GETDATE(),
                NULL, NULL, NULL, NULL, NULL
            )
        ";

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

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

    // Commit
    if (!sqlsrv_commit($conn)) {
        throw new Exception("Commit failed: " . print_r(sqlsrv_errors(), true));
    }

    sqlsrv_close($conn);

    echo json_encode([
        'status' => 'SUCCESS',
        'message' => 'Linen Reject count ' . $lrj_no . ' updated successfully',
        'lrj_mst_lrj_no' => $lrj_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' => "(" . $now . ") " . $e->getMessage(),
        'data' => []
    ]);
    exit();
}
?>