<?php
// backend/ride/driverWallet/transfer.php

require_once __DIR__ . '/../../connect.php';

header('Content-Type: application/json');

// 1. Authenticate user
$decodedToken = authenticateJWT();
if (!$decodedToken) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

$senderID = filterRequest('driverID');
$receiverPhone = filterRequest('receiverPhone');
$amount = filterRequest('amount');
$country = filterRequest('country');

if (empty($senderID) || empty($receiverPhone) || empty($amount) || empty($country)) {
    echo json_encode(['status' => 'error', 'message' => 'Missing required fields']);
    exit;
}

// Ensure the sender matches the token
if ($decodedToken->id != $senderID) {
     echo json_encode(['status' => 'error', 'message' => 'Unauthorized driver ID']);
     exit;
}

// 2. Fetch Receiver details
$stmt = $con->prepare("SELECT d.id as driver_id, dt.token as fcm_token, d.name_arabic 
                       FROM driver d 
                       LEFT JOIN driverToken dt ON d.id = dt.captain_id 
                       WHERE d.phone = :phone LIMIT 1");
$stmt->execute([':phone' => $receiverPhone]);
$receiver = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$receiver) {
    echo json_encode(['status' => 'error', 'message' => 'Receiver not found']);
    exit;
}

$receiverID = $receiver['driver_id'];

if ($receiverID == $senderID) {
    echo json_encode(['status' => 'error', 'message' => 'Cannot transfer to yourself']);
    exit;
}

// 3. Determine Payment Server URL based on Country
$walletServer = "https://walletintaleq.intaleq.xyz"; // Default
if (strtolower($country) === 'jordan') {
    $walletServer = getenv('WALLET_SERVER_JORDAN') ?: "https://walletintaleq.intaleq.xyz";
} elseif (strtolower($country) === 'egypt') {
    $walletServer = getenv('WALLET_SERVER_EGYPT') ?: "https://walletintaleq.intaleq.xyz";
} elseif (strtolower($country) === 'syria') {
    $walletServer = getenv('WALLET_SERVER_SYRIA') ?: "https://walletintaleq.intaleq.xyz";
}

$paymentServerUrl = "$walletServer/v2/main/ride/driverWallet/transfer.php";

$postData = [
    'senderID' => $senderID,
    'receiverID' => $receiverID,
    'amount' => $amount,
    'country' => $country
];

// Generate Headers for Payment Server (Use internal payment key)
$headers = [];
$paymentKey = getenv('PAYMENT_KEY') ;

if (!empty($paymentKey)) {
    $headers[] = "payment-key: $paymentKey";
} else {
    // Fallback just in case
    $headers[] = "payment-key: default_internal_secret_123";
}

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $paymentServerUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$paymentResponseRaw = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$paymentResponse = json_decode($paymentResponseRaw, true);

// 4. Handle Payment Server Response
if ($httpCode === 200 && isset($paymentResponse['status']) && $paymentResponse['status'] === 'success') {
    // Transaction successful, send Push Notification
    if (!empty($receiver['fcm_token'])) {
        $senderName = $decodedToken->name ?? 'A driver'; // Optional: Fetch sender name
        
        $fcmBody = "You have received a transfer of " . $amount . " from " . $senderName;
        // Arabic fallback if name available
        $fcmBodyAr = "لقد تلقيت حوالة بقيمة " . $amount . " من " . $senderName;

        sendFCM_Internal(
            $receiver['fcm_token'],
            "Transfer Received",
            $fcmBodyAr,
            ['type' => 'transfer', 'amount' => $amount],
            'Transfer',
            false,
            'ding'
        );
    }
    
    echo json_encode([
        'status' => 'success', 
        'message' => 'Transfer completed successfully', 
        'receiver' => $receiver['name_arabic']
    ]);
} else {
    // Payment failed or server error
    echo json_encode([
        'status' => 'error', 
        'message' => $paymentResponse['message'] ?? 'Payment server error',
        'debug' => $paymentResponseRaw
    ]);
}
?>
