<?php
// File: verify_otp.php (with enhanced logging)
// intaleq_v1/auth/token_passenger
require_once __DIR__ . '/../../connect.php';

// --- Start of Script Execution ---
 error_log("--- [verify_otp.php] Script execution started. ---");

$phoneNumber = filterRequest("phone_number");
$otp = filterRequest("otp");

// Log received data for debugging. Be mindful of logging sensitive data in production.
 error_log("[verify_otp.php] Received phone_number: $phoneNumber | Received otp: $otp");

if (empty($phoneNumber) || empty($otp)) {
     error_log("[verify_otp.php] Error: Phone number or OTP is empty.");
    jsonError("Phone number and OTP are required.");
    exit();
}

$phoneNumber_encrypted = $encryptionHelper->encryptData($phoneNumber);
$otp_encrypted = $encryptionHelper->encryptData($otp);

try {
    // 1. التحقق من Redis بدلاً من MySQL
    if (!$redis) {
        jsonError("Security service unavailable");
        exit;
    }

    $cachedOtp = $redis->get("otp:passenger:$phoneNumber");

    if ($cachedOtp && $cachedOtp == $otp) {
        // ننجح في التحقق ونحذف المفتاح من Redis لمنع استخدامه مرة أخرى (One-time use)
        $redis->del("otp:passenger:$phoneNumber");
        
        error_log("[verify_otp.php] OTP verified via Redis for phone: $phoneNumber");

        // 2. التحقق من وجود الراكب في قاعدة البيانات
        $passengerStmt = $con->prepare("SELECT id FROM passengers WHERE phone = ?");
        $passengerStmt->execute([$phoneNumber_encrypted]);
        $passenger = $passengerStmt->fetch(PDO::FETCH_ASSOC);

        if ($passenger) {
            $passengerID = $passenger['id'];
            
            // تحديث التوكن والبصمة إن وجدا
            $newToken = filterRequest("token");
            $fingerPrint = filterRequest("fingerPrint");

            if ($newToken && $fingerPrint) {
                $tokenEncrypted = $encryptionHelper->encryptData($newToken);
                $updateTokenStmt = $con->prepare("UPDATE tokens SET token = ?, fingerPrint = ? WHERE passengerID = ?");
                $updateTokenStmt->execute([$tokenEncrypted, $fingerPrint, $passengerID]);
            }
            
            printSuccess([
                "message" => "Token verified and updated.",
                "isRegistered" => true,
                "passengerID" => $passengerID
            ]);

        } else {
            printSuccess([
                "message" => "Phone verified, passenger not found.",
                "isRegistered" => false
            ]);
        }

    } else {
        error_log("[verify_otp.php] Invalid or expired OTP for phone: $phoneNumber");
        jsonError("Invalid or expired OTP.");
    }

} catch (Exception $e) {
    // Log the detailed database error message for debugging.
     error_log("[verify_otp.php] FATAL DATABASE ERROR: " . $e->getMessage());
    jsonError("Database error: " . $e->getMessage());
}
?>