<?php
include '../../jwtconnect.php';

// Disable error reporting output for production API
error_reporting(E_ALL);
ini_set('display_errors', 0);

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

$senderID = filterRequest('senderID');
$receiverID = filterRequest('receiverID'); // Now receiving the ID directly from Main Server
$amount = floatval(filterRequest('amount'));
$country = filterRequest('country'); // e.g. Egypt, Syria, Jordan

if (empty($senderID) || empty($receiverID) || empty($amount) || empty($country)) {
    echo json_encode(['status' => 'error', 'message' => 'Missing required fields']);
    exit;
}
// --- Payment Key Authentication ---
$expectedKey = getenv('PAYMENT_KEY'); 
$providedKey = $_SERVER['HTTP_PAYMENT_KEY'] ?? '';

if (empty($expectedKey) || $providedKey !== $expectedKey) {
    http_response_code(401);
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized Payment Server Access (Invalid Key)']);
    exit;
}
// 1. Determine Fee based on Country
$fee = 0;
if (strtolower($country) === 'egypt') {
    $fee = 5;
    if ($amount < 10) {
        echo json_encode(['status' => 'error', 'message' => 'Minimum transfer amount in Egypt is 10']);
        exit;
    }
} elseif (strtolower($country) === 'syria') {
    $fee = 10;
    if ($amount < 100) {
        echo json_encode(['status' => 'error', 'message' => 'Minimum transfer amount in Syria is 100']);
        exit;
    }
} elseif (strtolower($country) === 'jordan') {
    $fee = 0.25;
    if ($amount < 1) {
        echo json_encode(['status' => 'error', 'message' => 'Minimum transfer amount in Jordan is 1']);
        exit;
    }
} else {
    // Default fee if unknown
    $fee = 5;
}

try {
    $con->beginTransaction();

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

    // 2. Fetch Sender Budget (with FOR UPDATE to lock rows)
    $stmt = $con->prepare("SELECT SUM(amount) as diff FROM payments WHERE captain_id = :senderID FOR UPDATE");
    $stmt->execute([':senderID' => $senderID]);
    $sumRow = $stmt->fetch(PDO::FETCH_ASSOC);
    $totalBudget = floatval($sumRow['diff']);

    if ($totalBudget < $amount) {
        $con->rollBack();
        echo json_encode(['status' => 'error', 'message' => 'Insufficient budget']);
        exit;
    }

    $amountForReceiver = $amount - $fee;
    if ($amountForReceiver <= 0) {
        $con->rollBack();
        echo json_encode(['status' => 'error', 'message' => 'Transfer amount must be greater than the fee']);
        exit;
    }

    // 3. Generate unique Tokens and paymentIDs
    $paymentID1 = "transfer_" . time() . rand(1000, 9999);
    $paymentID2 = "transfer_recv_" . time() . rand(1000, 9999);
    $token1 = md5(uniqid("tk1", true));
    $token2 = md5(uniqid("tk2", true));
    $seferToken = md5(uniqid("sfr", true));

    // 4. Deduct from Sender (payments table)
    $deductAmount = -$amount;
    $stmt = $con->prepare("INSERT INTO payments (captain_id, amount, rideId, payment_method, passengerID, token) 
                           VALUES (:senderID, :amount, :rideId, 'cash_transfer', :receiverRef, :token)");
    $stmt->execute([
        ':senderID' => $senderID,
        ':amount' => $deductAmount,
        ':rideId' => $paymentID1,
        ':receiverRef' => 'To ' . $receiverID,
        ':token' => $token1
    ]);

    // 5. Add to Receiver Points (paymentsDriverPoints table)
    $stmt = $con->prepare("INSERT INTO paymentsDriverPoints (captain_id, paymentID, amount, token, paymentMethod) 
                           VALUES (:receiverID, :paymentID, :amount, :token, 'Transfer')");
    $stmt->execute([
        ':receiverID' => $receiverID,
        ':paymentID' => $paymentID2,
        ':amount' => $amountForReceiver,
        ':token' => $token2
    ]);

    // 6. Add Fee to Sefer Wallet
    $stmt = $con->prepare("INSERT INTO seferWallet (amount, paymentMethod, passengerId, token, driverId) 
                           VALUES (:fee, 'payout fee', 'driver', :token, :senderID)");
    $stmt->execute([
        ':fee' => $fee,
        ':token' => $seferToken,
        ':senderID' => $senderID
    ]);

    // Commit Transaction
    $con->commit();

    echo json_encode(['status' => 'success', 'message' => 'Transfer completed successfully on payment server']);

} catch (Exception $e) {
    $con->rollBack();
    echo json_encode(['status' => 'error', 'message' => 'Database transaction failed: ' . $e->getMessage()]);
}
?>
