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

$now = date("YmdHis");
$file_name = __DIR__ . "\\mobile_log\\_insert_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 ?? '');
    $period        	 	= trim($Header->period ?? ($Header->liu_mst_liu_period ?? ''));
    $liu_date      		= trim($Header->liu_date ?? ($Header->liu_mst_liu_date ?? ''));
    $desc           	= trim($Header->desc ?? ($Header->liu_mst_desc ?? ''));
    $liu_mst_department = trim($Header->liu_mst_department ?? ($Header->liu_mst_department ?? ''));
    $remark         	= trim($Header->remark ?? ($Header->liu_mst_remark ?? ''));
    $LOGINID        	= trim($Header->LoginID ?? ($Header->loginid ?? ''));
    $status         	= 'OPN';

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

    // totals
    $ttl_item = 0;
    $ttl_qty  = 0;

    foreach ($details as $d) {
        $linen = is_object($d) ? ($d->linen ?? ($d->liu_ls1_linen ?? '')) : ($d['linen'] ?? ($d['liu_ls1_linen'] ?? ''));
        $qty   = is_object($d) ? ($d->qty ?? ($d->liu_ls1_qty ?? null)) : ($d['qty'] ?? ($d['liu_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) Duplicate check by site_cd + period + date
    // ---------------------------------------------------------------------
    $sql_check = "
        SELECT TOP 1
            liu_mst_liu_no
        FROM liu_mst WITH (NOLOCK)
        WHERE site_cd = ?
          AND liu_mst_liu_period = ?
		  AND liu_mst_department =?
          AND CONVERT(date, liu_mst_liu_date) = CONVERT(date, ?)
        ORDER BY RowID DESC
    ";

    $stmt = sqlsrv_query($conn, $sql_check, [$site_cd, $period, $liu_mst_department,$liu_date]);
    if ($stmt === false) {
        throw new Exception("Duplicate check error: " . print_r(sqlsrv_errors(), true));
    }

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

    if ($dup) {
        throw new Exception("There is already a checklist / In Use created for this period and deparment. Checklist No: " . $dup['liu_mst_liu_no']);
    }

    // ---------------------------------------------------------------------
    // 2) Generate checklist no from cnt_mst
    // ---------------------------------------------------------------------
    $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 = 'LIUS';

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

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

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

    if ($liu_no === '') {
        throw new Exception("Failed to generate checklist no");
    }

    // ---------------------------------------------------------------------
    // 3) Insert liu_mst
    // ---------------------------------------------------------------------
    $sql_liu_mst = "
        INSERT INTO liu_mst (
            site_cd,
			liu_mst_liu_no,
            liu_mst_liu_period,
            liu_mst_liu_date,
            liu_mst_status,
            liu_mst_ttl_item,
            liu_mst_ttl_qty,
            liu_mst_desc,
			liu_mst_department,
            liu_mst_remark,
            liu_mst_create_by,
            liu_mst_create_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_liu_mst = [
        $site_cd,
        $liu_no,
        $period,
        $liu_date,
        $status,
        $ttl_item,
        $ttl_qty,
        $desc,
		$liu_mst_department,
        $remark,
        $LOGINID,
        $LOGINID,
        $LOGINID
    ];

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

    // ---------------------------------------------------------------------
    // 4) Get mst RowID from liu_mst
    // ---------------------------------------------------------------------
    $sql_get = "
        SELECT TOP 1 RowID
        FROM liu_mst
        WHERE site_cd = ?
          AND liu_mst_liu_no = ?
        ORDER BY RowID DESC
    ";

    $stmt = sqlsrv_query($conn, $sql_get, [$site_cd, $liu_no]);
    if ($stmt === false) {
        throw new Exception("Select liu_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 liu_mst_liu_no: " . $liu_no);
    }

    // ---------------------------------------------------------------------
    // 5) Insert into liu_det
    // ---------------------------------------------------------------------
    $sql_liu_det = "
        INSERT INTO liu_det (
            site_cd,
            mst_RowID,
            liu_det_sign_by,
            liu_det_sign_by_id,
            liu_det_sign_by_contact,
            liu_det_sign_by_title,
            liu_det_sign_date,
            liu_det_varchar1,
            liu_det_varchar2,
            liu_det_varchar3,
            liu_det_varchar4,
            liu_det_varchar5,
            liu_det_varchar6,
            liu_det_varchar7,
            liu_det_varchar8,
            liu_det_varchar9,
            liu_det_varchar10,
            liu_det_numeric1,
            liu_det_numeric2,
            liu_det_numeric3,
            liu_det_numeric4,
            liu_det_numeric5,
            liu_det_datetime1,
            liu_det_datetime2,
            liu_det_datetime3,
            liu_det_datetime4,
            liu_det_datetime5,
            liu_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_liu_det = [$site_cd, $mst_RowID, $LOGINID, $LOGINID];

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

    // ---------------------------------------------------------------------
    // 6) Insert liu_ls1 lines
    // ---------------------------------------------------------------------
    $sql_ins_ls1 = "
        INSERT INTO liu_ls1 (
            site_cd,
            mst_RowID,
            liu_ls1_linen,
            liu_ls1_qty,
            liu_ls1_remark,
            liu_ls1_varchar1,
            liu_ls1_varchar2,
            liu_ls1_varchar3,
            liu_ls1_varchar4,
            liu_ls1_varchar5,
            liu_ls1_numeric1,
            liu_ls1_numeric2,
            liu_ls1_numeric3,
            liu_ls1_numeric4,
            liu_ls1_numeric5,
            liu_ls1_datetime1,
            liu_ls1_datetime2,
            liu_ls1_datetime3,
            liu_ls1_datetime4,
            liu_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->liu_ls1_linen ?? '')) : ($d['linen'] ?? ($d['liu_ls1_linen'] ?? ''));
        $qty    = is_object($d) ? ($d->qty ?? ($d->liu_ls1_qty ?? null)) : ($d['qty'] ?? ($d['liu_ls1_qty'] ?? null));
        $remark_ls1 = is_object($d) ? ($d->remark ?? ($d->liu_ls1_remark ?? '')) : ($d['remark'] ?? ($d['liu_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;

        $params_ls1 = [
            $site_cd,
            $mst_RowID,
            $linen,
            $qty,
            $remark_ls1,
            $LOGINID,
            $LOGINID
        ];

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

    // ---------------------------------------------------------------------
    // 7) Insert STATUS AUDIT into liu_ls2
    // ---------------------------------------------------------------------
    $sql_chk_ls2 = "
        SELECT TOP 1 liu_ls2_varchar2
        FROM liu_ls2 WITH (NOLOCK)
        WHERE site_cd = ? AND mst_RowID = ?
        ORDER BY liu_ls2_datetime1 DESC, RowID DESC
    ";
    $stmt = sqlsrv_query($conn, $sql_chk_ls2, [$site_cd, $mst_RowID]);
    if ($stmt === false) {
        throw new Exception("Select liu_ls2 latest status error: " . print_r(sqlsrv_errors(), true));
    }

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

    $sql_chk_exists = "
        SELECT 1
        FROM liu_ls2 WITH (NOLOCK)
        WHERE site_cd = ? AND mst_RowID = ? AND liu_ls2_varchar2 = ?
    ";
    $stmt = sqlsrv_query($conn, $sql_chk_exists, [$site_cd, $mst_RowID, $status]);
    if ($stmt === false) {
        throw new Exception("Select liu_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_liu_ls2 = "
            INSERT INTO liu_ls2 (
                site_cd,
                mst_RowID,
                liu_ls2_varchar1,
                liu_ls2_varchar2,
                liu_ls2_varchar3,
                liu_ls2_varchar4,
                liu_ls2_varchar5,
                liu_ls2_varchar6,
                liu_ls2_varchar7,
                liu_ls2_varchar8,
                liu_ls2_varchar9,
                liu_ls2_varchar10,
                liu_ls2_numeric1,
                liu_ls2_numeric2,
                liu_ls2_numeric3,
                liu_ls2_numeric4,
                liu_ls2_numeric5,
                liu_ls2_numeric6,
                liu_ls2_numeric7,
                liu_ls2_numeric8,
                liu_ls2_numeric9,
                liu_ls2_numeric10,
                liu_ls2_datetime1,
                liu_ls2_datetime2,
                liu_ls2_datetime3,
                liu_ls2_datetime4,
                liu_ls2_datetime5,
                liu_ls2_datetime6,
                liu_ls2_datetime7,
                liu_ls2_datetime8,
                liu_ls2_datetime9,
                liu_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,
            $liu_no,   // liu_ls2_varchar1
            $status,    // liu_ls2_varchar2
            $originator,// liu_ls2_varchar3
            $name,      // liu_ls2_varchar4
            $LOGINID,
            $LOGINID
        ];

        $stmt = sqlsrv_query($conn, $sql_liu_ls2, $params_ls2);
        if ($stmt === false) {
            throw new Exception("Insert liu_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 In Use count ' . $liu_no . ' created successfully',
        'liu_mst_liu_no' => $liu_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(),
        'data' => []
    ]);
    exit();
}
?>