<?php
// request_payout.php
include "../jwtconnect.php"; // ملف الاتصال الذي يتحقق من JWT

error_log("[RequestPayout] --- Request Started ---");

// --- 1. استقبال المدخلات ---
$driverId    = filterRequest("driverId");
$amount_raw  = filterRequest("amount");
$wallet_type = filterRequest("wallet_type") ?? 'Sham Cash'; // قيمة افتراضية
$phone       = filterRequest("phone");

// تأكيد المبلغ كرقم
$amount = is_numeric($amount_raw) ? (float)$amount_raw : 0.0;

// تحقق أساسي
if (empty($driverId) || $amount <= 0) {
    printFailure("driverId and a valid amount are required.");
    exit;
}

try {
    // --- Atomic balance check + insert with transaction ---
    $con->beginTransaction();

    $stmt_driver = $con->prepare("
        SELECT COALESCE(SUM(amount), 0) AS balance
        FROM driverWallet
        WHERE driverID = :id
        FOR UPDATE
    ");
    $stmt_driver->execute([':id' => $driverId]);
    $driver = $stmt_driver->fetch(PDO::FETCH_ASSOC);

    $payout_fee      = 3500.00;
    $total_deduction = $amount + $payout_fee;
    
    if ($driver['balance'] < $total_deduction) {
        $con->rollBack();
        printFailure("Insufficient balance. Required: $total_deduction");
        exit;
    }

    $sql = "
        INSERT INTO payout_requests (driver_id, driver_phone, amount, wallet_type)
        VALUES (:did, :phone, :amount, :wallet)
    ";
    $stmt = $con->prepare($sql);
    $stmt->execute([
        ':did'   => $driverId,
        ':phone' => $phone,
        ':amount'=> $amount,
        ':wallet'=> $wallet_type
    ]);

    $con->commit();

    if ($stmt->rowCount() > 0) {
        // --- 4. إرسال إشعار لخدمة العملاء ---
        $customerServicePhone = getenv('CUSTOMER_SERVICE_PHONE');

        $message = 
            "⚠️ طلب دفع جديد:\n" .
            "ID السائق: {$driverId}\n" .
            "هاتف السائق: {$phone}\n" .
            "نوع المحفظة: {$wallet_type}\n" .
            "المبلغ: {$amount} SYP\n\n" .
            "الرجاء من فريق خدمة العملاء تنفيذ عملية الدفع الآن.";

        // الإرسال (الفنكشن مُضمّن لديك مسبقًا)
        sendWhatsAppFromServer($customerServicePhone, $message);      

        error_log("[RequestPayout] Successfully created payout request for driver ID: $driverId");
        printSuccess("Payout request created successfully. It will be processed shortly.");
    } else {
        printFailure("Failed to create payout request.");
    }

} catch (PDOException $e) {
    error_log("[RequestPayout] PDOException: " . $e->getMessage());
    printFailure("A database error occurred.");
}
?>