<?php
// wallet/finalize_wallet_payment.php

// لم نعد بحاجة لـ jwtconnect.php هنا لأن الاتصال يتم تمريره من السكربت الرئيسي

if (!function_exists('logError')) {
    function logError($step, $message, $data = null) {
        $logFile = __DIR__ . "/../logs/finalization.log";
        $logDir = dirname($logFile);
        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($logFile, $logEntry . PHP_EOL, FILE_APPEND);
    }
}


/**
 * دالة لإنشاء توكن دفع فريد وحفظه في قاعدة البيانات.
 */
function generateToken($con, $driverId, $amount): ?string {
    // افترض أن secretKey تم تعريفه في ملف jwtconnect.php
    global $secretKey; 
    $data = $driverId . $amount . time() . ($secretKey ?? 'default_secret_for_token');
    $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;
}

/**
 * دالة لإنشاء سجل دفعة جديد وإرجاع الـ ID الخاص به.
 */
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;
}

/**
 * دالة الإتمام الرئيسية، تم تعديلها لتستقبل ID الفاتورة مباشرة
 */
function finalizeWalletPaymentByInvoice($con, $invoiceId) {
    logError("FINALIZE", "Starting finalization for invoice ID: {$invoiceId}");

    try {
        // 1. جلب بيانات الفاتورة المكتملة
        $stmt = $con->prepare("SELECT * FROM `invoices_sms` WHERE id = :id AND status = 'completed' LIMIT 1");
        $stmt->execute([':id' => $invoiceId]);
        $invoice = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$invoice) {
            logError("FINALIZE", "Invoice not found or not completed", ['invoiceId' => $invoiceId]);
            return false;
        }

        $driverId = $invoice['driverID'];
        $originalAmount = floatval($invoice['amount']);
        $paymentMethod = $invoice['sender'] ?? 'sms';

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

        // إنشاء التوكنات ومعرف الدفع
        $tokenDriver = generateToken($con, $driverId, $bonusAmount);
        $tokenSiro = generateToken($con, $driverId, $originalAmount);
        $paymentID = generatePaymentID($con, $driverId, $bonusAmount, $paymentMethod);

        if (!$tokenDriver || !$tokenSiro || !$paymentID) {
            throw new Exception('Failed to generate required tokens or 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) VALUES (:driverId, 'driver', :amount, :paymentMethod, :token)");
        $insertSiro->execute([
            ':driverId' => $driverId, ':amount' => $originalAmount,
            ':paymentMethod' => $paymentMethod, ':token' => $tokenSiro
        ]);
        if ($insertSiro->rowCount() === 0) throw new Exception('Insert to siroWallet failed');
        $con->prepare("UPDATE payment_tokens SET isUsed = TRUE WHERE token = :token")->execute([':token' => $tokenSiro]);

        logError("FINALIZE", "SUCCESS: Wallets updated successfully for invoice ID: {$invoiceId}");
        return true;

    } catch (Throwable $e) {
        logError("FINALIZE", "EXCEPTION: " . $e->getMessage(), ['invoiceId' => $invoiceId]);
        return false;
    }
}
?>
