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

$now = date("YmdHis");
$file_name = __DIR__ . "\\mobile_log\\_update_satisfaction_survey.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");
    }

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

    // -----------------------------
    // HEADER DATA
    // -----------------------------
    $site_cd          	= trim($Header->site_cd ?? '');
    $lss_mst_lss_no   	= trim($Header->survey_no ?? '');
    $dept_cd          	= trim($Header->dept_mst_dept_cod ?? '');
    $dept_desc        	= trim($Header->dept_mst_description ?? '');
    $lss_mst_lss_date 	= trim($Header->request_date_time ?? '');
    $lss_mst_lss_year 	= trim($Header->lss_mst_lss_year ?? '');
    $lss_mst_lss_month 	= trim($Header->lss_mst_lss_month ?? '');
    $LOGINID          	= trim($Header->LoginID ?? '');
    $rawStatus 			= $Header->lss_mst_status ?? false;
	$status 			= filter_var($rawStatus, FILTER_VALIDATE_BOOLEAN) ? 'ISU' : 'OPN';
	

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

    $sqlDate = $lss_mst_lss_date;

    // -----------------------------
    // GET mst_RowID
    // -----------------------------
    $sql_get = "
        SELECT RowID
        FROM lss_mst WITH (NOLOCK)
        WHERE site_cd = ?
          AND lss_mst_lss_no = ?
          AND lss_mst_lss_date >= ?
          AND lss_mst_lss_date < DATEADD(DAY, 1, ?)
    ";
    $stmt = sqlsrv_query($conn, $sql_get, [$site_cd, $lss_mst_lss_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("Survey record not found");
    }

    $mst_RowID = $row['RowID'];

    // -----------------------------
    // UPDATE lss_mst
    // -----------------------------
    $sql_upd_mst = "
        UPDATE lss_mst
        SET
            lss_mst_status     = ?,
            lss_mst_lss_year     = ?,
            lss_mst_lss_month     = ?,
            audit_user         = ?,
            audit_date         = GETDATE(),
            mbl_audit_user     = ?,
            mbl_audit_date     = GETDATE()
        WHERE site_cd = ?
          AND RowID = ?
    ";

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

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

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

    // -----------------------------
    // UPDATE lss_ls1
    // Must have RowID
    // -----------------------------
    $sql_upd_ls1 = "
        UPDATE lss_ls1
        SET
            
            lss_ls1_answer     = ?,
            lss_ls1_varchar1   = ?,
            audit_user         = ?,
            audit_date         = GETDATE(),
            mbl_audit_user     = ?,
            mbl_audit_date     = GETDATE()
        WHERE site_cd = ?
          AND mst_RowID = ?
          AND RowID = ?
    ";

    foreach ($details as $d) {

       
        $answer   = trim((string)($d->stp_zom_data ?? $d->stp_zom_data ?? ''));
        $remark   = trim((string)($d->remark ?? $d->lss_ls1_varchar1 ?? ''));
        $rowid    = trim((string)($d->RowID ?? ''));

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

        $params_ls1 = [
           
            $answer,
            $remark,
            $LOGINID,
            $LOGINID,
            $site_cd,
            $mst_RowID,
            $rowid
        ];

        $stmt = sqlsrv_query($conn, $sql_upd_ls1, $params_ls1);
        if (!$stmt) {
            throw new Exception("Update lss_ls1 error: " . print_r(sqlsrv_errors(), true));
        }
        sqlsrv_free_stmt($stmt);
    }

    // ---------------------------------------------------------------------
    // Insert STATUS AUDIT into lss_ls2 (avoid inserting same status multiple times)
    // Rule: if latest status == new status -> SKIP
    // ---------------------------------------------------------------------

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

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

    $sql_chk_exists = "
        SELECT 1
        FROM lss_ls2 WITH (NOLOCK)
        WHERE site_cd = ? AND mst_RowID = ? AND lss_ls2_varchar2 = ?
    ";
    $stmt = sqlsrv_query($conn, $sql_chk_exists, [$site_cd, $mst_RowID, $status]);
    if ($stmt === false) {
        throw new Exception("Select lss_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_upd_det = "
			UPDATE lss_ls2
			SET
				lss_ls2_datetime2 	= GETDATE(),
				audit_user     		= ?,
				audit_date     		= GETDATE(),
				mbl_audit_user 		= ?,
				mbl_audit_date 		= GETDATE()
			WHERE site_cd = ?
			  AND mst_RowID = ?
			  AND lss_ls2_datetime2 IS NULL
		";

		$stmt = sqlsrv_query($conn, $sql_upd_det, [$LOGINID, $LOGINID, $site_cd, $mst_RowID]);
		if (!$stmt) throw new Exception("Update lri_ls2 error: " . print_r(sqlsrv_errors(), true));
		sqlsrv_free_stmt($stmt);

        $sql_lss_ls2 = "
            INSERT INTO lss_ls2 (
                site_cd, mst_RowID,
                lss_ls2_varchar1,
                lss_ls2_varchar2,
                lss_ls2_varchar3,
                lss_ls2_varchar4,
                lss_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,
            $lss_mst_lss_no,
            $status,
            $originator,
            $name,
            $LOGINID,
            $LOGINID
        ];

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

    if (!sqlsrv_commit($conn)) {
        throw new Exception("Commit failed");
    }

    sqlsrv_close($conn);

    echo json_encode([
        "status" => "SUCCESS",
        "message" => 'Satisfaction Survey ' . $lss_mst_lss_no . ' updated successfully',
        "lss_mst_lss_no" => $lss_mst_lss_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();
}
?>