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

$now = date("YmdHis");
$file_name = __DIR__ . "\\mobile_log\\_insert_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)) {
        $headers = [$result->header]; // single header
    } elseif (isset($result->Header) && is_array($result->Header)) {
        $headers = $result->Header;   // header array
    } 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");
    }

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

    $last_lri_no = '';
    $last_rowid  = '';

    foreach ($headers as $Header) {

        $site_cd              = trim($Header->site_cd ?? '');
        $dept_mst_dept_cod    = trim($Header->dept_mst_dept_cod ?? '');
        $dept_mst_description = trim($Header->dept_mst_description ?? '');
        $lri_mst_lri_no       = trim($Header->lri_mst_lri_no ?? '');
        $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';

        // totals (optional from mobile)
        $total_line_count = (int)($Header->total_line_count ?? count($details));
        $total_par_count  = (float)($Header->total_par_count ?? 0);
        $total_qty_count  = (float)($Header->total_qty_count ?? 0);

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

        // date: accept dd-mm-yyyy OR yyyy-mm-dd
        $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 lri_mst_lri_date format. Use dd-mm-yyyy or yyyy-mm-dd");
        $sqlDate = $dt->format('Y-m-d');

        // Compute totals if not passed
        if ($total_par_count == 0 || $total_qty_count == 0) {
            $sumPar = 0;
            $sumIssue = 0;

            foreach ($details as $d) {
                $par = is_object($d) ? ($d->dept_par_qty ?? 0) : ($d['dept_par_qty'] ?? 0);
                $iss = is_object($d) ? ($d->qty_entered ?? 0)  : ($d['qty_entered'] ?? 0);
                $sumPar   += (float)$par;
                $sumIssue += (float)$iss;
            }

            if ($total_par_count == 0) $total_par_count = $sumPar;
            if ($total_qty_count == 0) $total_qty_count = $sumIssue; // you can change meaning if needed
        }

        // ---------------------------------------------------------------------
        // 1) If LRI NO empty -> generate from cnt_mst and INSERT lri_mst
        // ---------------------------------------------------------------------
        if ($lri_mst_lri_no === '') {

            $sql_cnt = "
                SELECT ls_doc_no = cnt_mst_prefix + SUBSTRING(CONVERT(VARCHAR(7), cnt_mst_counter + 1000000), 2, 6)
                FROM   cnt_mst WITH (NOLOCK)
                WHERE  site_cd = ?
                  AND  cnt_mst_module_cd = 'LDR';

                UPDATE cnt_mst WITH (UPDLOCK)
                SET    cnt_mst_counter = cnt_mst_counter + 1
                WHERE  site_cd = ?
                  AND  cnt_mst_module_cd = 'LDR';
            ";

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

            $linen_nos = '';
            do {
                while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
                    $linen_nos = $row['ls_doc_no'];
                }
            } while (sqlsrv_next_result($stmt));
            sqlsrv_free_stmt($stmt);

            if ($linen_nos === '') throw new Exception("Failed to generate doc no");

            $lri_mst_lri_no = $linen_nos;

            // Insert lri_mst (your column list)
            $sql_lri_mst = "INSERT INTO lri_mst (	site_cd, 			lri_mst_lri_no, 		lri_mst_lri_date, 	lri_mst_status,
													lri_mst_desc, 		lri_mst_department,		lri_mst_ttl_item, 	lri_mst_ttl_par, 
													lri_mst_ttl_bal,	lri_mst_ttl_issue, 		lri_mst_ttl_sf, 	lri_mst_remark,
													lri_mst_create_by, 	lri_mst_create_date,	audit_user, 		audit_date,
													mbl_audit_user, 	mbl_audit_date,			column1, 			column2, 				
													column3, 			column4, 				column5
												)
										VALUES (	?, 					?, 						?,				 	?,
													?, 					?,						?, 					?, 
													?,					NULL, 					NULL, 				NULL,
													?, 					GETDATE(),				?, 					GETDATE(),
													?, 					GETDATE(),				NULL, 				NULL, 					
													NULL, 				NULL, 					NULL
												)";

            $params_lri_mst = [$site_cd, $lri_mst_lri_no, $sqlDate, $status, $dept_mst_description, $dept_mst_dept_cod, $total_line_count, $total_par_count, $total_qty_count, $LOGINID, $LOGINID, $LOGINID];

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

        } 

        // ---------------------------------------------------------------------
        // 2) Get mst RowID from lri_mst
        // ---------------------------------------------------------------------
        $sql_get = "SELECT RowID FROM lri_mst 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 === false) {
            throw new Exception("Select lri_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("RowID not found for lri_mst_lri_no: " . $lri_mst_lri_no);
		
		
		
		// ---------------------------------------------------------------------
		// 3) Insert into lri_det
		// ---------------------------------------------------------------------
		$sql_lri_det = "
			INSERT INTO lri_det (
				site_cd, mst_RowID,
				lri_det_sign_by, lri_det_sign_by_title, lri_det_sign_date,
				lri_det_varchar1, lri_det_varchar2, lri_det_varchar3, lri_det_varchar4, lri_det_varchar5,
				lri_det_varchar6, lri_det_varchar7, lri_det_varchar8, lri_det_varchar9, lri_det_varchar10,
				lri_det_numeric1, lri_det_numeric2, lri_det_numeric3, lri_det_numeric4, lri_det_numeric5,
				lri_det_datetime1, lri_det_datetime2, lri_det_datetime3, lri_det_datetime4, lri_det_datetime5,
				lri_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,
				?, GETDATE(),
				?, GETDATE(),
				NULL, NULL, NULL, NULL, NULL
			)
		";

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

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

        // ---------------------------------------------------------------------
        // 4) Insert lri_ls1 lines (loop details)
        // Mapping:
        //   lri_ls1_linen     = dept_par_lin_cd
        //   lri_ls1_par_qty   = dept_par_qty
        //   lri_ls1_bal_qty   = qty_entered
        // ---------------------------------------------------------------------
        $sql_ins_ls1 = "
            INSERT INTO lri_ls1 (
                site_cd, mst_RowID,
                lri_ls1_linen,
                lri_ls1_par_qty,
                lri_ls1_bal_qty,
                lri_ls1_issue1_qty,
                lri_ls1_issue2_qty,
                lri_ls1_remark,
                lri_ls1_sf_qty,
                audit_user, audit_date,
				mbl_audit_user, mbl_audit_date,
                column1, column2, column3, column4, column5
            )
            VALUES (
                ?, ?,
                ?,
                ?,
                ?,
                Null,
                Null,
                Null,
                Null,
                ?, GETDATE(),
				?, GETDATE(),
                NULL, NULL, NULL, NULL, NULL
            )
        ";

        foreach ($details as $d) {
            // ✅ Read from your STANDARD JSON keys
			$linen  = is_object($d) ? ($d->linen ?? '') : ($d['linen'] ?? '');
			$parQty = is_object($d) ? ($d->par_qty ?? null) : ($d['par_qty'] ?? null);

			// Prefer qty_entered if coming from UI, else fallback to bal_qty
			$balQty = is_object($d)
				? (($d->qty_entered ?? null) ?? ($d->bal_qty ?? null))
				: (($d['qty_entered'] ?? null) ?? ($d['bal_qty'] ?? null));

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

			// ✅ parQty: empty -> NULL else float
			$parQty = trim((string)$parQty);
			$parQty = ($parQty === '') ? null : (float)$parQty;

			// ✅ balQty: empty -> NULL else float
			$balQty = trim((string)$balQty);
			$balQty = ($balQty === '') ? null : (float)$balQty;

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

			$stmt = sqlsrv_query($conn, $sql_ins_ls1, $params_ls1);
			if ($stmt === false) {
				throw new Exception("Insert 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_varchar2'] ?? '');
        }
        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_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);
        }

        $last_lri_no = $lri_mst_lri_no;
        $last_rowid  = $mst_RowID;
		
		
    }

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

    sqlsrv_close($conn);

    echo json_encode([
        'status' => 'SUCCESS',
        'message' => 'Daily Linen Routine ' . $last_lri_no . ' saved successfully',
        'lri_mst_lri_no' => $last_lri_no,
        'mst_RowID' => $last_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' => 'Alert',
        'message' => "(".$now.") ".$e->getMessage(),
        'data' => []
    ]);
    exit();
}
?>