Update: 2026-06-11 18:22:57

This commit is contained in:
Hamza-Ayed
2026-06-11 18:22:59 +03:00
parent c5170a88d2
commit 727068b668
629 changed files with 46050 additions and 46109 deletions

View File

@@ -0,0 +1,107 @@
<?php
// --- backend/ride/invitor/claim.php ---
include "../../connect.php";
include "../../functions.php"; // Assuming a functions file exists for helper methods
header('Content-Type: application/json');
try {
$inviteId = filterRequest("invite_id");
$driverId = filterRequest("driver_id");
$passengerId = filterRequest("passenger_id");
$countryCode = filterRequest("country_code"); // Expected: Jordan, Syria, Egypt
if (empty($inviteId)) {
echo json_encode(["status" => "failure", "message" => "Invite ID required."]);
exit;
}
$walletServer = "https://walletintaleq.intaleq.xyz"; // Default
if (strtolower($countryCode) == 'jordan') {
$rewardAmount = 5;
$currency = "JOD";
$walletServer = $_ENV['WALLET_SERVER_JORDAN'] ?? "https://walletintaleq.intaleq.xyz";
} elseif (strtolower($countryCode) == 'egypt') {
$rewardAmount = 500;
$currency = "EGP";
$walletServer = $_ENV['WALLET_SERVER_EGYPT'] ?? "https://walletintaleq.intaleq.xyz";
} else {
$rewardAmount = 500; // Default Syria
$currency = "SYP";
$walletServer = $_ENV['WALLET_SERVER_SYRIA'] ?? "https://walletintaleq.intaleq.xyz";
}
$walletUrl = "$walletServer/v2/main/ride/payment/add.php";
$con->beginTransaction();
if (!empty($driverId)) {
// Driver Invitation Reward Logic
$stmt = $con->prepare("SELECT * FROM invit_driver WHERE id = :invite_id AND driverId = :driver_id AND isGiftToken = 0 FOR UPDATE");
$stmt->execute([':invite_id' => $inviteId, ':driver_id' => $driverId]);
$invitation = $stmt->fetch(PDO::FETCH_ASSOC);
if ($invitation) {
$upd = $con->prepare("UPDATE invit_driver SET isGiftToken = 1 WHERE id = :invite_id");
$upd->execute([':invite_id' => $inviteId]);
// Reward for current driver
addWalletBalance($walletUrl, $driverId, "driver", $rewardAmount);
// Reward for inviter
addWalletBalance($walletUrl, $invitation['driverInviterId'], "driver", $rewardAmount);
$con->commit();
echo json_encode(["status" => "success", "message" => "Reward of $rewardAmount $currency claimed successfully."]);
} else {
$con->rollBack();
echo json_encode(["status" => "failure", "message" => "Invitation not valid or already claimed."]);
}
} elseif (!empty($passengerId)) {
// Passenger Invitation Reward Logic
$stmt = $con->prepare("SELECT * FROM invit_passenger WHERE id = :invite_id AND passengerInviterId = :passenger_id AND isGiftToken = 0 FOR UPDATE");
$stmt->execute([':invite_id' => $inviteId, ':passenger_id' => $passengerId]);
$invitation = $stmt->fetch(PDO::FETCH_ASSOC);
if ($invitation) {
$upd = $con->prepare("UPDATE invit_passenger SET isGiftToken = 1 WHERE id = :invite_id");
$upd->execute([':invite_id' => $inviteId]);
// Call Wallet Server
addWalletBalance($walletUrl, $passengerId, "passenger", $rewardAmount);
$con->commit();
echo json_encode(["status" => "success", "message" => "Reward of $rewardAmount $currency claimed successfully."]);
} else {
$con->rollBack();
echo json_encode(["status" => "failure", "message" => "Invitation not valid or already claimed."]);
}
} else {
echo json_encode(["status" => "failure", "message" => "User ID required."]);
}
} catch (Exception $e) {
if ($con && $con->inTransaction()) { $con->rollBack(); }
error_log("Error in claim.php: " . $e->getMessage());
echo json_encode(["status" => "error", "message" => "Server error."]);
}
function addWalletBalance($url, $userId, $userType, $amount) {
$data = [
"user_id" => $userId,
"user_type" => $userType,
"amount" => $amount,
"action" => "add",
"reason" => "Invitation Reward"
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
?>

View File

@@ -0,0 +1,269 @@
<?php
require_once __DIR__ . '/../../connect.php';
$distance = (float) filterRequest("distance");
$duration = (float) filterRequest("durationToRide");
$promo_code = filterRequest("promo_code");
$passenger_id = filterRequest("passenger_id");
$promo_code_id = filterRequest("promo_code_id") ? filterRequest("promo_code_id") : 0;
$country = filterRequest("country");
$startNameAddress = filterRequest("startNameAddress");
$endNameAddress = filterRequest("endNameAddress");
$destLat = (float) filterRequest("destLat");
$destLng = (float) filterRequest("destLng");
$passengerLat = (float) filterRequest("passengerLat");
$passengerLng = (float) filterRequest("passengerLng");
$activeMenuWaypointCount = (int) filterRequest("activeMenuWaypointCount");
if (!$country) {
echo json_encode(["status" => "failure", "message" => "Country parameter is required"]);
exit;
}
$price = 0.0;
$price_for_driver = 0.0;
$withCommission = 0.0;
$kazan = 0.0;
$isNightFare = false;
// Common variables
date_default_timezone_set('Asia/Damascus');
$currentTime = new DateTime();
$hour = (int)$currentTime->format('H');
switch ($country) {
case 'Syria':
$minFare = 150.0;
break;
case 'Egypt':
$minFare = 20.0;
break;
case 'Jordan':
$minFare = 1.0;
break;
default:
$minFare = 0.0;
break;
}
// Fetch kazan from DB for the specified country
$sql = "SELECT * FROM `kazan` WHERE country = :country LIMIT 1";
$stmt = $con->prepare($sql);
$stmt->execute([':country' => $country]);
$kazanRow = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$kazanRow) {
echo json_encode(["status" => "failure", "message" => "No pricing available for this country"]);
exit;
}
$result = calculateDynamicPrice($country, $minFare, $distance, $duration, $kazanRow, $startNameAddress, $endNameAddress, $destLat, $destLng, $passengerLat, $passengerLng);
$price = $result['price'];
$price_for_driver = $result['price_for_driver'];
$withCommission = $result['withCommission'];
$kazan = $result['kazan'];
$isNightFare = $result['isNightFare'];
// ----------------------------------------------------------------------
// Helper Functions for Countries
// ----------------------------------------------------------------------
function calculateDynamicPrice($country, $minFare, $distance, $duration, $kazanRow, $startNameAddress, $endNameAddress, $destLat, $destLng, $passengerLat, $passengerLng) {
$comfortPrice = (float) $kazanRow['comfortPrice'];
$speedPrice = (float) $kazanRow['speedPrice'];
$familyPrice = (float) $kazanRow['familyPrice'];
$deliveryPrice = (float) $kazanRow['deliveryPrice'];
$naturePrice = (float) $kazanRow['naturePrice'];
$heavyPrice = (float) $kazanRow['heavyPrice'];
$latePrice = (float) $kazanRow['latePrice'];
$kazanPercent = (float) $kazanRow['kazan'];
// === General Settings ===
$minBillableKm = 0.2;
$airportAddon = 0.0;
$damascusAirportBoundAddon = 0.0;
switch ($country) {
case 'Egypt':
$airportAddon = 35.0;
break;
case 'Jordan':
$airportAddon = 5.0;
break;
default: // Syria
$airportAddon = 200.0;
$damascusAirportBoundAddon = 1400.0;
break;
}
$longSpeedThresholdKm = 40.0;
$longSpeedPerKm = 26.0;
$mediumDistThresholdKm = 25.0;
$longDistThresholdKm = 35.0;
$longTripPerMin = 6.0;
$minuteCapMedium = 60;
$minuteCapLong = 80;
$freeMinutesLong = 10;
$extraReduction100 = 0.07;
$maxReductionCap = 0.35;
$totalMinutes = floor($duration / 60);
$airportCtx = (stripos($startNameAddress, 'airport') !== false || stripos($startNameAddress, 'مطار') !== false || stripos($endNameAddress, 'airport') !== false || stripos($endNameAddress, 'مطار') !== false);
$clubCtx = (stripos($startNameAddress, 'club') !== false || stripos($startNameAddress, 'ديسكو') !== false || stripos($endNameAddress, 'club') !== false || stripos($endNameAddress, 'ديسكو') !== false);
$northLat = 33.415313;
$southLat = 33.400265;
$eastLng = 36.531505;
$westLng = 36.499687;
$damascusAirportBoundCtx = ($destLat <= $northLat && $destLat >= $southLat && $destLng <= $eastLng && $destLng >= $westLng);
$isInDamascusAirportBoundCtx = ($passengerLat <= $northLat && $passengerLat >= $southLat && $passengerLng <= $eastLng && $passengerLng >= $westLng);
$billableDistance = ($distance < $minBillableKm) ? $minBillableKm : $distance;
$isLongSpeed = $billableDistance > $longSpeedThresholdKm;
$perKmSpeedBaseFromServer = $speedPrice;
$perKmSpeed = $isLongSpeed ? $longSpeedPerKm : $perKmSpeedBaseFromServer;
$reductionPct40 = 0.0;
if ($perKmSpeedBaseFromServer > 0) {
$r = 1.0 - ($longSpeedPerKm / $perKmSpeedBaseFromServer);
$reductionPct40 = max(0.0, min($maxReductionCap, $r));
}
$reductionPct100 = max(0.0, min($maxReductionCap, $reductionPct40 + $extraReduction100));
$distanceReduction = 0.0;
if ($billableDistance > 100.0) {
$distanceReduction = $reductionPct100;
} else if ($billableDistance > 40.0) {
$distanceReduction = $reductionPct40;
}
date_default_timezone_set('Asia/Damascus');
$hour = (int)date('H');
$effectivePerMin = $naturePrice;
if ($hour >= 21 || $hour < 1) {
$effectivePerMin = $latePrice;
} else if ($hour >= 1 && $hour < 5) {
$effectivePerMin = $clubCtx ? ($latePrice * 2) : $latePrice;
} else if ($hour >= 14 && $hour <= 17) {
$effectivePerMin = $heavyPrice;
}
$billableMinutes = $totalMinutes;
if ($billableDistance > $longDistThresholdKm) {
$effectivePerMin = $longTripPerMin;
$capped = ($billableMinutes > $minuteCapLong) ? $minuteCapLong : $billableMinutes;
$billableMinutes = max(0, $capped - $freeMinutesLong);
} else if ($billableDistance > $mediumDistThresholdKm) {
$effectivePerMin = $longTripPerMin;
$billableMinutes = ($billableMinutes > $minuteCapMedium) ? $minuteCapMedium : $billableMinutes;
}
$fare = $billableDistance * $perKmSpeed;
$fare += $billableMinutes * $effectivePerMin;
if ($airportCtx) $fare += $airportAddon;
if ($damascusAirportBoundCtx || $isInDamascusAirportBoundCtx) {
$fare += $damascusAirportBoundAddon;
}
$price = max($fare, $minFare);
// Apply kazan (e.g. 11%)
$withCommission = ceil($price * (1 + $kazanPercent / 100));
$kazan = $withCommission - $price;
$price_for_driver = $price;
return [
'price' => $price,
'price_for_driver' => $price_for_driver,
'withCommission' => $withCommission,
'kazan' => $kazan,
'isNightFare' => false
];
}
// 2. Validate Promo Code
$discount = 0;
if (!empty($promo_code)) {
$sqlPromo = "SELECT amount FROM `promos`
WHERE promo_code = :promo_code
AND (passengerID = :passenger_id OR passengerID LIKE '%all%')
AND validity_start_date <= CURDATE()
AND validity_end_date >= CURDATE()";
$stmtPromo = $con->prepare($sqlPromo);
$stmtPromo->execute([
':promo_code' => $promo_code,
':passenger_id' => $passenger_id
]);
if ($stmtPromo->rowCount() > 0) {
$promoData = $stmtPromo->fetch(PDO::FETCH_ASSOC);
$discount = (float) $promoData['amount'];
}
}
// 3. Fetch Passenger Wallet (Negative Balance / Debt)
// Using Redis for ultra-fast reads, with a fallback to the Payment Server API.
$negativeBalance = 0;
if (!empty($passenger_id)) {
try {
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redisKey = "passenger_debt_" . $passenger_id;
$redisDebt = $redis->get($redisKey);
if ($redisDebt !== false) {
$negativeBalance = (float) $redisDebt;
} else {
// Fallback: If not in Redis, call the Payment Server Endpoint
// TODO: Replace with the actual Payment Server Endpoint URL and API Key
/*
$paymentApiUrl = "https://payment.siroapp.com/api/get_debt?passenger_id=" . urlencode($passenger_id);
$options = [
"http" => [
"header" => "Authorization: Bearer YOUR_API_KEY\r\n"
]
];
$context = stream_context_create($options);
$response = file_get_contents($paymentApiUrl, false, $context);
if ($response !== false) {
$data = json_decode($response, true);
if (isset($data['debt'])) {
$negativeBalance = (float) $data['debt'];
// Cache the result in Redis for future pricing calls (e.g. 1 hour)
$redis->setex($redisKey, 3600, $negativeBalance);
}
}
*/
}
} catch (Exception $e) {
// If Redis fails, gracefully default to 0 or fallback API
$negativeBalance = 0;
}
}
$prices = ['total' => $withCommission];
// 4. Apply Discount and Negative Balance
foreach ($prices as $key => $price) {
// Apply discount (Assuming percentage discount if amount <= 100, else fixed amount)
if ($discount > 0 && $discount <= 100) {
$prices[$key] = max(0, $price - ($price * ($discount / 100)));
} else {
$prices[$key] = max(0, $price - $discount);
}
// Add negative balance
$prices[$key] += $negativeBalance;
}
echo json_encode([
'status' => 'success',
'data' => $prices,
'applied_discount' => $discount,
'added_negative_balance' => $negativeBalance
]);
?>

View File

@@ -12,6 +12,7 @@ $rideId = filterRequest("ride_id");
$driverId = filterRequest("driver_id");
$reason = filterRequest("reason");
$passengerToken = filterRequest("passenger_token");
$penaltyFee = (float) filterRequest("penalty_fee");
// تثبيت الحالة
$statusText = "CancelFromDriverAfterApply";
@@ -92,6 +93,27 @@ try {
if (function_exists('notifyPassengerOnRideServer')) {
notifyPassengerOnRideServer($passenger_id, $socketPayload);
}
// 4.1. إضافة غرامة الإلغاء على الراكب (الدين) إذا كانت موجودة
if ($penaltyFee > 0) {
// إضافة القيمة كدين سالب في المحفظة
$negativeDebt = -$penaltyFee;
$stmtWallet = $con->prepare("INSERT INTO `passengerWallet` (passenger_id, balance) VALUES (?, ?)");
$stmtWallet->execute([$passenger_id, $negativeDebt]);
// تخزين الدين في الـ Redis لمدة 6 شهور (15552000 ثانية)
try {
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redisKey = "passenger_debt_" . $passenger_id;
// إضافة الدين الجديد إلى الدين السابق إن وجد
$currentDebt = (float) $redis->get($redisKey);
$newDebt = $currentDebt + $negativeDebt;
$redis->setex($redisKey, 15552000, $newDebt);
} catch (Exception $e) {
error_log("Redis Error: " . $e->getMessage());
}
}
}
// ب) FCM (Internal)

View File

@@ -58,6 +58,30 @@ try {
$stmtPas->execute([$ride_id]);
$passenger_id = $stmtPas->fetchColumn();
// 2.5 تصفير الدين من Redis عند بدء الرحلة (كما طلبت)
if ($passenger_id) {
try {
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redisKey = "passenger_debt_" . $passenger_id;
// قراءة الدين الحالي من Redis قبل الحذف (إن لزم الأمر للتسجيل مستقبلاً)
$currentDebt = (float) $redis->get($redisKey);
// تصفير / حذف الدين
$redis->del($redisKey);
// يمكنك هنا أيضاً إدراج حركة معاكسة في جدول passengerWallet إذا أردت تسوية قاعدة البيانات
if ($currentDebt < 0) {
$positiveOffset = abs($currentDebt);
$stmtWallet = $con->prepare("INSERT INTO `passengerWallet` (passenger_id, balance) VALUES (?, ?)");
$stmtWallet->execute([$passenger_id, $positiveOffset]);
}
} catch (Exception $e) {
error_log("Redis Error (zeroing debt): " . $e->getMessage());
}
}
if ($passenger_id) {
// أ) إرسال السوكيت (Socket)

View File

@@ -6,27 +6,91 @@ $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 > 99999999.99) {
jsonError("Invalid tip amount.");
if (!is_numeric($tipAmount) || $tipAmount <= 0 || $tipAmount > 99999999.99) {
echo json_encode(["status" => "failure", "message" => "Invalid tip amount."]);
exit();
}
// إدراج بيانات البقشيش
$sql = "INSERT INTO `tips` (`driverID`, `passengerID`, `rideID`, `tipAmount`)
VALUES (:driverID, :passengerID, :rideID, :tipAmount)";
$con->beginTransaction();
$stmt = $con->prepare($sql);
$stmt->bindParam(':driverID', $driverID);
$stmt->bindParam(':passengerID', $passengerID);
$stmt->bindParam(':rideID', $rideID);
$stmt->bindParam(':tipAmount', $tipAmount);
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";
}
// تنفيذ العملية
if ($stmt->execute() && $stmt->rowCount() > 0) {
jsonSuccess(null, "Tip inserted successfully");
} else {
jsonError("Failed to save tip information");
// 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"]);
}
?>