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

// استلام المتغيرات
$passengerID = filterRequest("passengerID");
$driverID    = filterRequest("driverID");
$rideID      = filterRequest("rideID");
$tipAmount   = filterRequest("tipAmount");
$countryCode = filterRequest("country_code"); // sent from flutter

// تحقق من صحة قيمة البقشيش
if (!is_numeric($tipAmount) || $tipAmount <= 0 || $tipAmount > 599.99) {
    echo json_encode(["status" => "failure", "message" => "Invalid tip amount."]);
    exit();
}

$con->beginTransaction();

try {
    // إدراج بيانات البقشيش
    $sql = "INSERT INTO `tips` (`driverID`, `passengerID`, `rideID`, `tipAmount`) 
            VALUES (:driverID, :passengerID, :rideID, :tipAmount)";
    
    $stmt = $con->prepare($sql);
    $stmt->execute([
        ':driverID' => $driverID,
        ':passengerID' => $passengerID,
        ':rideID' => $rideID,
        ':tipAmount' => $tipAmount
    ]);
    
    if ($stmt->rowCount() > 0) {
        $walletServer = "https://walletintaleq.intaleq.xyz"; // Default
        if (strtolower($countryCode) == 'jordan') {
            $walletServer = $_ENV['WALLET_SERVER_JORDAN'] ?? "https://walletintaleq.intaleq.xyz";
        } elseif (strtolower($countryCode) == 'egypt') {
            $walletServer = $_ENV['WALLET_SERVER_EGYPT'] ?? "https://walletintaleq.intaleq.xyz";
        } else {
            $walletServer = $_ENV['WALLET_SERVER_SYRIA'] ?? "https://walletintaleq.intaleq.xyz";
        }

        // Amount logic depending on country (as done previously in flutter)
        $driverTipAmount = $tipAmount;
        if (strtolower($countryCode) == 'egypt') {
            $driverTipAmount = round($tipAmount, 0); // Egypt
        } else {
            $driverTipAmount = $tipAmount * 100; // Syria and Jordan use * 100
        }

        // 1. Deduct from passenger
        $urlPassenger = "$walletServer/v2/main/ride/payment/add.php";
        $dataPassenger = [
            "user_id" => $passengerID,
            "user_type" => "passenger",
            "amount" => -1 * $tipAmount, // negative
            "action" => "subtract",
            "reason" => "Tip Deduction"
        ];
        
        $ch1 = curl_init($urlPassenger);
        curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch1, CURLOPT_POST, true);
        curl_setopt($ch1, CURLOPT_POSTFIELDS, http_build_query($dataPassenger));
        $resPassenger = curl_exec($ch1);
        curl_close($ch1);

        // 2. Add to Driver
        $urlDriver = "$walletServer/v2/main/ride/payment/add.php";
        $dataDriver = [
            "user_id" => $driverID,
            "user_type" => "driver",
            "amount" => $driverTipAmount,
            "action" => "add",
            "paymentID" => $rideID . "tip",
            "paymentMethod" => "visa-tip"
        ];

        $ch2 = curl_init($urlDriver);
        curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch2, CURLOPT_POST, true);
        curl_setopt($ch2, CURLOPT_POSTFIELDS, http_build_query($dataDriver));
        $resDriver = curl_exec($ch2);
        curl_close($ch2);

        $con->commit();
        echo json_encode(["status" => "success", "message" => "Tip inserted and wallet updated"]);
    } else {
        $con->rollBack();
        echo json_encode(["status" => "failure", "message" => "Failed to save tip information"]);
    }
} catch (Exception $e) {
    $con->rollBack();
    error_log("Error in addTips: " . $e->getMessage());
    echo json_encode(["status" => "failure", "message" => "Server error"]);
}
?>