<?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];
    } elseif (isset($result->Header) && is_array($result->Header)) {
        $headers = $result->Header;
    } 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");
    }

    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 ?? '');
        $lrr_mst_lrr_no       	= trim($Header->lrr_mst_lrr_no ?? '');
        $lrr_mst_lrr_date     	= trim($Header->request_date_time ?? '');
        $lrr_mst_requester    	= trim($Header->requester ?? '');
        $lrr_mst_requester_id   = trim($Header->requester_id ?? '');
        $status               	= 'OPN';
        $status_desc          	= 'Open';
        $LOGINID              	= trim($Header->LoginID ?? '');

        $total_line_count = (int)($Header->total_line_count ?? count($details));
        $total_req_count  = (int)($Header->total_req_count ?? count($details));

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

        if ($lrr_mst_lrr_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 = 'LRR';

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

            $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");
            }

            $lrr_mst_lrr_no = $linen_nos;

            $sql_lrr_mst = "
                INSERT INTO lrr_mst (
										site_cd, 			lrr_mst_lrr_no, 	lrr_mst_lrr_date, 		lrr_mst_status,
										lrr_mst_desc, 		lrr_mst_department, lrr_mst_requester, 		lrr_mst_requester_id,
										lrr_mst_ttl_item, 	lrr_mst_ttl_rej, 	lrr_mst_ttl_issue, 		lrr_mst_ttl_sf,
										lrr_mst_remark, 	lrr_mst_create_by, 	lrr_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_lrr_mst = [
                $site_cd,
                $lrr_mst_lrr_no,
                $lrr_mst_lrr_date,
                $status,
				$dept_mst_description,
                $dept_mst_dept_cod,
                $lrr_mst_requester,
                $lrr_mst_requester_id,
                $total_line_count,
                $total_req_count,
                $LOGINID,
                $LOGINID,
                $LOGINID
            ];

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

        $sql_get = "
            SELECT RowID
            FROM lrr_mst
            WHERE site_cd = ?
              AND lrr_mst_lrr_no = ?
              AND lrr_mst_lrr_date >= ?
              AND lrr_mst_lrr_date < DATEADD(DAY, 1, ?)
        ";
        $stmt = sqlsrv_query($conn, $sql_get, [$site_cd, $lrr_mst_lrr_no, $lrr_mst_lrr_date, $lrr_mst_lrr_date]);
        if ($stmt === false) {
            throw new Exception("Select lrr_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 lrr_mst_lrr_no: " . $lrr_mst_lrr_no);
        }

        $sql_lrr_det = "
            INSERT INTO lrr_det (
                site_cd, mst_RowID,
                lrr_det_sign_by, lrr_det_sign_by_id, lrr_det_sign_by_contact, lrr_det_sign_by_title, lrr_det_sign_date,
                lrr_det_varchar1, lrr_det_varchar2, lrr_det_varchar3, lrr_det_varchar4, lrr_det_varchar5,
                lrr_det_varchar6, lrr_det_varchar7, lrr_det_varchar8, lrr_det_varchar9, lrr_det_varchar10,
                lrr_det_numeric1, lrr_det_numeric2, lrr_det_numeric3, lrr_det_numeric4, lrr_det_numeric5,
                lrr_det_datetime1, lrr_det_datetime2, lrr_det_datetime3, lrr_det_datetime4, lrr_det_datetime5,
                lrr_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_lrr_det = [$site_cd, $mst_RowID, $LOGINID, $LOGINID];

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

        $sql_ins_ls1 = "
            INSERT INTO lrr_ls1 (
                site_cd, mst_RowID,
                lrr_ls1_linen,
                lrr_ls1_rej_qty,
                lrr_ls1_issue1_qty,
                lrr_ls1_issue2_qty,
                lrr_ls1_sf_qty,
                lrr_ls1_remark,
                audit_user, audit_date,
                mbl_audit_user, mbl_audit_date,
                column1, column2, column3, column4, column5
            )
            VALUES (
                ?, ?,
                ?,
                ?,
                NULL,
                NULL,
                NULL,
                ?,
                ?, GETDATE(),
                ?, GETDATE(),
                NULL, NULL, NULL, NULL, NULL
            )
        ";

        foreach ($details as $d) {
            $linen      = is_object($d) ? ($d->linen_item ?? '') : ($d['linen_item'] ?? '');
            $reject_qty = is_object($d) ? ($d->reject_qty ?? null) : ($d['reject_qty'] ?? null);
            //$issue1Qty  = is_object($d) ? ($d->issue1_qty ?? null) : ($d['issue1_qty'] ?? null);
            //$issue2Qty  = is_object($d) ? ($d->issue2_qty ?? null) : ($d['issue2_qty'] ?? null);
            $remark     = is_object($d) ? ($d->remark ?? '') : ($d['remark'] ?? '');

            $linen  = trim((string)$linen);
            $remark = trim((string)$remark);

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

            $reject_qty = trim((string)$reject_qty);
            //$issue1Qty  = trim((string)$issue1Qty);
            //$issue2Qty  = trim((string)$issue2Qty);

            $reject_qty = ($reject_qty === '') ? null : (float)$reject_qty;
           // $issue1Qty  = ($issue1Qty === '') ? null : (float)$issue1Qty;
           // $issue2Qty  = ($issue2Qty === '') ? null : (float)$issue2Qty;

            $params_ls1 = [
                $site_cd,
                $mst_RowID,
                $linen,
                $reject_qty,
                $remark,
                $LOGINID,
                $LOGINID
            ];

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

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

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

        $sql_chk_exists = "
            SELECT 1
            FROM lrr_ls2 WITH (NOLOCK)
            WHERE site_cd = ? AND mst_RowID = ? AND lrr_ls2_varchar1 = ?
        ";
        $stmt = sqlsrv_query($conn, $sql_chk_exists, [$site_cd, $mst_RowID, $status]);
        if ($stmt === false) {
            throw new Exception("Select lrr_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_lrr_ls2 = "
                INSERT INTO lrr_ls2 (
                    site_cd, mst_RowID,
                    lrr_ls2_varchar1,
                    lrr_ls2_varchar2,
                    lrr_ls2_varchar3,
                    lrr_ls2_varchar4,
                    lrr_ls2_datetime1,
                    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,
                $lrr_mst_lrr_no,
                $status,
                $originator,
                $name,
                $LOGINID,
                $LOGINID
            ];

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

        $last_lri_no = $lrr_mst_lrr_no;
        $last_rowid  = $mst_RowID;
    }

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

    sqlsrv_close($conn);

    echo json_encode([
        'status' => 'SUCCESS',
        'message' => 'New Linen Reject ' . $last_lri_no . ' created successfully',
        'lrr_mst_lrr_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();
}
?>