<?php
include "../../jwtconnect.php";

define("BASE_URL", "https://wl.tripz-egypt.com/v1/main/ride");
define("LOG_FILE", "../logs/payment_verification.log"); // Define log file path

// Function to write to error log
function logError($step, $message, $data = null) {
    $timestamp = date('Y-m-d H:i:s');
    $logEntry = "[{$timestamp}] STEP {$step}: {$message}";
    
    if ($data !== null) {
        $logEntry .= " | Data: " . json_encode($data);
    }
    
    // Ensure log directory exists
    $logDir = dirname(LOG_FILE);
    if (!is_dir($logDir)) {
        mkdir($logDir, 0755, true);
    }
    
    // Append to log file
    file_put_contents(LOG_FILE, $logEntry . PHP_EOL, FILE_APPEND);
    
    // Also log to PHP error log for server monitoring
    // error_log("PAYMENT_VERIFICATION: {$logEntry}");
}

// Receive parameters from GET request
$user_id = filterRequest("user_id");
$passengerId = filterRequest("passengerId");
$paymentMethod = filterRequest("paymentMethod");

// Log initial request
// logError("0", "Request received", [
//     "user_id" => $user_id,
//     "passengerId" => $passengerId
// ]);

// Validate user_id and passengerId
if (!$user_id || !$passengerId) {
    // logError("1", "Invalid parameters", [
    //     "user_id" => $user_id,
    //     "passengerId" => $passengerId
    // ]);
    printFailure("Invalid user ID or passenger ID.");
    exit;
}

try {
    // Step 1: Get the latest successful payment
    // logError("1", "Querying latest payment", ["user_id" => $user_id]);
    
    $stmt = $con->prepare("SELECT * FROM paymentsLog WHERE user_id = :user_id AND created_at >= DATE_SUB(NOW(), INTERVAL 2 MINUTE)
ORDER BY created_at DESC 
LIMIT 1");
    $stmt->bindParam(':user_id', $user_id, PDO::PARAM_STR);
    $stmt->execute();

    $payment = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$payment) {
        logError("1", "No payment found", ["user_id" => $user_id]);
        printFailure("No payment data found.");
        exit;
    }

    // logError("1", "Payment found", [
    //     "payment_id" => $payment['id'] ?? 'unknown',
    //     "status" => $payment['status'],
    //     "amount" => $payment['amount']/100 ?? 'unknown'
    // ]);

    // Step 2: Check payment status
    if ($payment['status'] != 1) {
        // logError("2", "Payment not successful", ["status" => $payment['status']]);
        printFailure("Payment is not successful yet.");
        exit;
    }
    
    // logError("2", "Payment status verified", ["status" => $payment['status']]);
    
    $amount = $payment['amount']/100; // Paid amount

    // Step 3: Calculate bonus based on the paid amount
    // logError("3", "Calculating bonus", ["amount" => $amount]);
    $finalAmount = calculateBonus($amount);
    
    if ($finalAmount <= 0) {
        // logError("3", "Bonus calculation failed", [
        //     "original_amount" => $amount,
        //     "calculated_amount" => $finalAmount
        // ]);
        printFailure("Invalid amount for bonus calculation.");
        exit;
    }
    
    // logError("3", "Bonus calculated", [
    //     "original_amount" => $amount,
    //     "final_amount" => $finalAmount
    // ]);

    // // Step 4: Generate payment token
    // logError("4", "Generating payment token", [
    //     "passengerId" => $passengerId,
    //     "amount" => $finalAmount
    // ]);
    
    $token = generatePaymentToken($passengerId, $finalAmount);
    
    if (!$token) {
        // logError("4", "Token generation failed");
        printFailure("Payment verified, but failed to generate token.");
        exit;
    }
    
    // logError("4", "Token generated successfully", ["token_length" => strlen($token)]);

    // // Step 5: Add balance to passenger's wallet
    // logError("5", "Adding balance to passenger wallet", [
    //     "passengerId" => $passengerId,
    //     "amount" => $finalAmount
    // ]);
    
    $walletResult = addToPassengerWallet($passengerId, $finalAmount, $token);
    
    if (!$walletResult || !isset($walletResult['status']) || $walletResult['status'] != "success") {
        // logError("5", "Failed to add balance to passenger wallet", $walletResult);
        printFailure("Payment verified, but failed to add balance to passenger wallet.");
        exit;
    }
    
    // logError("5", "Balance added to passenger wallet", $walletResult);

    // Step 6: Add balance to Siro wallet
    // logError("6", "Adding balance to Siro wallet", [
    //     "passengerId" => $passengerId,
    //     "amount" => $finalAmount,
    //     "paymentMethod" => $paymentMethod
    // ]);
     
    $token = generatePaymentToken($passengerId, $finalAmount);
    
    if (!$token) {
        // logError("4", "Token generation failed");
        printFailure("Payment verified, but failed to generate token.");
        exit;
    }
    
    // logError("4", "Token generated successfully", ["token_length" => strlen($token)]);

    $siroWalletResult = addToSiroWallet($passengerId, $amount, $paymentMethod);
    
    if (!$siroWalletResult || !isset($siroWalletResult['status']) || $siroWalletResult['status'] != "success") {
        // logError("6", "Failed to add balance to Siro wallet", $siroWalletResult);
        printFailure("Payment verified, but failed to add balance to Siro wallet.");
        exit;
    }
    
    // logError("6", "Balance added to Siro wallet", $siroWalletResult);

    // // Final success
    // logError("7", "Process completed successfully", [
    //     "payment_id" => $payment['id'] ?? 'unknown',
    //     "amount" => $finalAmount,
    //     "passengerId" => $passengerId
    // ]);
    
   printSuccess( "Payment data saved successfully");
    
} catch (PDOException $e) {
    logError("ERROR", "Database error: " . $e->getMessage());
    printFailure("Database error occurred.");
} catch (Exception $e) {
    logError("ERROR", "General error: " . $e->getMessage());
    printFailure("An error occurred during payment verification.");
}

// 🎯 Function to generate payment token with error logging
function generatePaymentToken($passengerId, $amount) {
    $url = BASE_URL . "/passengerWallet/addPaymentTokenPassenger.php";
    
    $postData = [
        'passengerId' => $passengerId,
        'amount' => $amount
    ];
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);
    
    if ($curlError) {
        logError("4.1", "cURL error in token generation", [
            "error" => $curlError,
            "url" => $url
        ]);
        return null;
    }
    
    if ($httpCode != 200) {
        logError("4.2", "HTTP error in token generation", [
            "http_code" => $httpCode,
            "response" => $response
        ]);
        return null;
    }
    
    $data = json_decode($response, true);
    
    if (!$data || !isset($data['message'])) {
        logError("4.3", "Invalid response format in token generation", [
            "response" => $response
        ]);
        return null;
    }
    
    return $data['message']; // ✅ Return token
}

// 🎯 Function to add balance to passenger's wallet with error logging
function addToPassengerWallet($passengerId, $amount, $token) {
    $url = BASE_URL . "/passengerWallet/add.php";
    
    $postData = [
        'passenger_id' => $passengerId,
        'balance' => $amount,
        'token' => $token
    ];
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);
    
    if ($curlError) {
        logError("5.1", "cURL error in passenger wallet update", [
            "error" => $curlError,
            "url" => $url
        ]);
        return null;
    }
    
    if ($httpCode != 200) {
        logError("5.2", "HTTP error in passenger wallet update", [
            "http_code" => $httpCode,
            "response" => $response
        ]);
        return null;
    }
    
    $data = json_decode($response, true);
    
    if (!$data) {
        logError("5.3", "Invalid response format in passenger wallet update", [
            "response" => $response
        ]);
        return null;
    }
    
    return $data; // ✅ Return result
}

// 🎯 Function to add balance to Siro wallet with error logging


function addToSiroWallet($passengerId, $amount, $paymentMethod) {
   
    
    // Generate a new token specifically for the Siro wallet
    $siroToken = generatePaymentToken($passengerId, $amount);
    
    if (!$siroToken) {
        logError("6.0.1", "Failed to generate Siro token");
        return null;
    }
    
    logError("6.0.2", "Generated new Siro token", [
        "token_length" => ($siroToken)
    ]);
    
    $url = BASE_URL . "/siroWallet/add.php";
    
    $postData = [
        'amount' => $amount,
        'paymentMethod' => $paymentMethod,
        'passengerId' => $passengerId,
        'token' => $siroToken,  // Use the new Siro-specific token
        'driverId' => 'passenger'
    ];
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);
    
    if ($curlError) {
        logError("6.1", "cURL error in Siro wallet update", [
            "error" => $curlError,
            "url" => $url
        ]);
        return null;
    }
    
    if ($httpCode != 200) {
        logError("6.2", "HTTP error in Siro wallet update", [
            "http_code" => $httpCode,
            "response" => $response
        ]);
        return null;
    }
    
    $data = json_decode($response, true);
    
    if (!$data) {
        logError("6.3", "Invalid response format in Siro wallet update", [
            "response" => $response
        ]);
        return null;
    }
    
    return $data; // ✅ Return result
}


// 🎯 Function to calculate bonus
function calculateBonus($amount) {
    logError("3.1", "Bonus calculation input", ["amount" => $amount]);
    
    $result = 0;
    if ($amount == 100) $result = 100;
    else if ($amount == 200) $result = 215;
    else if ($amount == 400) $result = 450;
    else if ($amount == 1000) $result = 1140;
    
    logError("3.2", "Bonus calculation result", [
        "input" => $amount, 
        "output" => $result
    ]);
    
    return $result;
}
?>