<?php
// wallet/finalize_wallet_payment.php
include_once "../../../jwtconnect.php";

define("LOG_FILE", "../logs/payment_verification.log");

function logError($step, $message, $data = null) {
    $logDir = dirname(LOG_FILE);
    if (!is_dir($logDir)) { mkdir($logDir, 0755, true); }
    $logEntry = "[" . date('Y-m-d H:i:s') . "] STEP {$step}: {$message}";
    if ($data !== null) { $logEntry .= " | Data: " . json_encode($data, JSON_UNESCAPED_UNICODE); }
    file_put_contents(LOG_FILE, $logEntry . PHP_EOL, FILE_APPEND);
}

function generateToken($con, $driverId, $amount): ?string {
    global $secretKey;
    $data = $driverId . $amount . time() . ($secretKey ?? 'default_secret');
    $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;
}

function finalizeWalletPayment($con) {
    $orderRef = $_GET['orderRef'] ?? null;
    if (empty($orderRef)) {
        logError("FINALIZE", "Missing orderRef");
        return;
    }

    // 1. تحقق من الدفع
    $stmt = $con->prepare("SELECT * FROM `paymentsLogSyriaDriver` WHERE order_ref = :order_ref AND status = 1 LIMIT 1");
    $stmt->execute([':order_ref' => $orderRef]);
    $payment = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$payment) {
        logError("FINALIZE", "Payment not found or not completed", ['orderRef' => $orderRef]);
        return;
    }

    try {
        $driverId = $payment['user_id'];
        $originalAmount = floatval($payment['amount']);
        $paymentMethod = $payment['payment_method'] ?? 'ecash';

        // حساب المكافأة
        $bonusAmount = match ((int)$originalAmount) {
            10000   => 10000.0,
            20000  => 21000.0,
            40000  => 45000.0,
            100000 => 110000.0,
            default => $originalAmount,
        };

        // إنشاء التوكنات
        $tokenDriver = generateToken($con, $driverId, $bonusAmount);
        if (!$tokenDriver) throw new Exception('Failed to generate driver token');

        $tokenSiro = generateToken($con, $driverId, $originalAmount);
        if (!$tokenSiro) throw new Exception('Failed to generate siro token');

        $paymentID = generatePaymentID($con, $driverId, $bonusAmount, $paymentMethod);
        if (!$paymentID) throw new Exception('Failed to generate payment ID');

        // driverWallet
        $insertDriver = $con->prepare("INSERT INTO driverWallet (driverID, paymentID, amount, paymentMethod) VALUES (:driverID, :paymentID, :amount, :paymentMethod)");
        $insertDriver->execute([
            ':driverID' => $driverId,
            ':paymentID' => $paymentID,
            ':amount' => $bonusAmount,
            ':paymentMethod' => $paymentMethod
        ]);
        if ($insertDriver->rowCount() === 0) throw new Exception('Insert to driverWallet failed');

        $con->prepare("UPDATE payment_tokens SET isUsed = TRUE WHERE token = :token")->execute([':token' => $tokenDriver]);

        // 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
        ]);
        $con->prepare("UPDATE payment_tokens SET isUsed = TRUE WHERE token = :token")->execute([':token' => $tokenSiro]);

        logError("FINALIZE", "Wallets updated successfully", ['orderRef' => $orderRef]);
		printSuccess("FINALIZE", "Wallets updated successfully");
    } catch (Throwable $e) {
        logError("FINALIZE", "Exception during finalization: " . $e->getMessage(), ['orderRef' => $orderRef]);
    }
}