<?php

include "../../../jwtconnect.php";
define('BASE_URL', 'https://wl.tripz-egypt.com/v1/main/ride');

try {
    $driverId      = filterRequest('driverID');
    $user_id       = filterRequest('user_id');
    $paymentMethod = filterRequest('paymentMethod');

    if (empty($user_id) || empty($driverId)) {
        printFailure('Missing user_id or driverID.');
        exit;
    }

    // 1️⃣ تحقق من سجل الدفع خلال آخر دقيقتين
    $stmt = $con->prepare(
        'SELECT * FROM payment_log_driver
         WHERE user_id = :uid
           AND created_at >= DATE_SUB(NOW(), INTERVAL 2 MINUTE)
         ORDER BY created_at DESC LIMIT 1'
    );
    $stmt->execute([':uid' => $user_id]);
    $payment = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$payment || $payment['status'] != 1) {
        printFailure('No valid payment found.');
        exit;
    }

    $originalAmount = floatval($payment['amount']);
    $bonus = match ((int)$originalAmount) {
        80   => 80.0,
        200  => 215.0,
        400  => 450.0,
        1000 => 1140.0,
        default => $originalAmount,
    };

    // 2️⃣ توكن لـ DriverWallet
    $tokenDriver = generateToken($con, $driverId, $bonus);
    if (!$tokenDriver) {
        printFailure('Failed to generate token for driver wallet.');
        exit;
    }

    // 3️⃣ توكن مستقل لـ SiroWallet
    $tokenSiro = generateToken($con, $driverId, $originalAmount);
    if (!$tokenSiro) {
        printFailure('Failed to generate token for siro wallet.');
        exit;
    }

    // 4️⃣ Payment ID
    $paymentID = generatePaymentID($con, $driverId, $bonus, $paymentMethod);
    if (!$paymentID) {
        printFailure('Failed to generate payment ID.');
        exit;
    }

    // 5️⃣ Insert into driverWallet
    $insertDriver = $con->prepare("INSERT INTO driverWallet (driverID, paymentID, amount, paymentMethod) VALUES (:driverID, :paymentID, :amount, :paymentMethod)");
    $insertDriver->execute([
        ':driverID'      => $driverId,
        ':paymentID'     => $paymentID,
        ':amount'        => $bonus,
        ':paymentMethod' => $paymentMethod
    ]);

    if ($insertDriver->rowCount() === 0) {
        printFailure('Failed to insert into driverWallet.');
        exit;
    }

    // 6️⃣ Update tokenDriver to isUsed = TRUE
    $markTokenDriver = $con->prepare("UPDATE payment_tokens SET isUsed = TRUE WHERE token = :token");
    $markTokenDriver->execute([':token' => $tokenDriver]);

    // 7️⃣ Insert into siroWallet
    $insertSiro = $con->prepare("INSERT INTO siroWallet (driverId, passengerId, amount, paymentMethod, token, createdAt)
                                  VALUES (:driverId, :passengerId, :amount, :paymentMethod, :token, CURRENT_TIMESTAMP)");
    $insertSiro->execute([
        ':driverId'      => $driverId,
        ':passengerId'   => 'driver',
        ':amount'        => $originalAmount,
        ':paymentMethod' => $paymentMethod,
        ':token'         => $tokenSiro
    ]);

    // 8️⃣ Update tokenSiro to isUsed = TRUE
    $markTokenSiro = $con->prepare("UPDATE payment_tokens SET isUsed = TRUE WHERE token = :token");
    $markTokenSiro->execute([':token' => $tokenSiro]);

    // 🎉 Success response
    printSuccess([
        'message'    => 'Payment verified and all wallets updated successfully.',
        'amount'     => $originalAmount,
        'bonus'      => $bonus,
        'paymentID'  => $paymentID,
        'tokenUsed'  => [
            'driverWalletToken' => $tokenDriver,
            'siroWalletToken'  => $tokenSiro
        ]
    ]);

} catch (Throwable $e) {
    printFailure("Server error: " . $e->getMessage());
}


// ───────────────────────────
//  FUNCTIONS
// ───────────────────────────

function generateToken($con, $driverId, $amount): ?string {
    global $secretKey;

    // نفس المنطق من سكربتك
    $data = $driverId . $amount . time();
    $data .= $secretKey;
    $hash = hash('sha256', $data);
    $randomBytes = bin2hex(random_bytes(16));
    $token = substr($hash . $randomBytes, 0, 64);
    // تخزين التوكن في قاعدة البيانات
    $stmt = $con->prepare("INSERT INTO payment_tokens (token, driverID, dateCreated, amount)
                       VALUES (:token, :driverID, NOW(), :amount)");
    $stmt->execute([
        ':token'    => $token,
        ':driverID' => $driverId,
        ':amount'   => $amount
    ]);

    return $stmt->rowCount() > 0 ? $token : null;
}

function generatePaymentID($con, $driverId, $amount, $method): ?string {
  
    $stmt = $con->prepare("INSERT INTO paymentsDriverPoints (`amount`, `payment_method`, `driverID`)
                       VALUES (:amount, :method, :driverID)");
    $stmt->execute([
        ':driverID' => $driverId,
        ':amount'   => $amount,
        ':method'   => $method
    ]);
    return $stmt->rowCount() > 0 ? $con->lastInsertId() : null;
}
