Update: 2026-06-15 01:37:40

This commit is contained in:
Hamza-Ayed
2026-06-15 01:37:41 +03:00
parent f021ba5a35
commit 2321b78244
164 changed files with 1356 additions and 1560 deletions

View File

@@ -58,7 +58,7 @@ SELECT
(SELECT COUNT(*) FROM (SELECT driver_id FROM ride GROUP BY driver_id) AS sub) AS num_Driver,
-- التحويلات البنكية
(SELECT COUNT(*) FROM payments WHERE payment_method = 'TransferFrom') AS transfer_from_count
0 AS transfer_from_count
";
$stmt = $con->prepare($sql);

View File

@@ -1,48 +1,6 @@
<?php
require_once __DIR__ . '/../connect.php';
// جلب البيانات
$sql = "SELECT
COUNT(DISTINCT driverID) AS driver_count,
`payments`.driverID,
COALESCE(SUM(amount), 0) AS total_amount,
`driver`.`phone`,
`driver`.`name_arabic`,
`driver`.`accountBank`,
`driver`.`bankCode`,
`driver`.`email`
FROM
payments
LEFT JOIN `driver` ON `driver`.`id` = payments.driverID
WHERE
isGiven = 'waiting' AND payment_method IN(
'visa-in', 'visa', 'visaRide', 'TransferFrom',
'payout', 'TransferTo', 'payFromSeferToDriver'
)
AND WEEK(`payments`.created_at) = WEEK(CURRENT_DATE)
GROUP BY
driverID
HAVING
COALESCE(SUM(amount), 0) > 0 AND total_amount > 100
LIMIT 0, 25";
$stmt = $con->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
// فك التشفير للحقول المطلوبة
foreach ($result as &$row) {
$fieldsToDecrypt = ['phone', 'email', 'accountBank', 'bankCode', 'name_arabic'];
foreach ($fieldsToDecrypt as $field) {
if (isset($row[$field]) && $row[$field] !== null) {
$row[$field] = $encryptionHelper->decryptData($row[$field]);
}
}
}
if ($stmt->rowCount() > 0) {
jsonSuccess($result);
} else {
jsonError("No wallet record found");
}
// Return empty list as payments table resides on the payment server
jsonSuccess([]);
?>

View File

@@ -15,8 +15,8 @@ try {
SUM(price_for_passenger) as total_revenue,
SUM(price_for_driver) as total_driver_pay,
SUM(price_for_passenger - price_for_driver) as total_platform_commission,
(SELECT SUM(amount) FROM payments WHERE payment_method = 'Cash') as cash_payments,
(SELECT SUM(amount) FROM payments WHERE payment_method != 'Cash') as digital_payments
0 as cash_payments,
0 as digital_payments
FROM ride
WHERE status = 'Finished'
");

View File

@@ -0,0 +1,38 @@
<?php
require_once __DIR__ . '/../connect.php';
// Ensure the caller has a valid user_id
if (empty($user_id)) {
jsonError("Unauthorized", 401);
exit;
}
$latitude = filterRequest("latitude");
$longitude = filterRequest("longitude");
// Validate inputs
if ($latitude === '' || $longitude === '') {
jsonError("Latitude and longitude are required", 400);
exit;
}
try {
// Insert location log
$sql = "INSERT INTO `passenger_opening_locations` (`passenger_id`, `latitude`, `longitude`)
VALUES (:passenger_id, :latitude, :longitude)";
$stmt = $con->prepare($sql);
$stmt->bindParam(':passenger_id', $user_id);
$stmt->bindParam(':latitude', $latitude);
$stmt->bindParam(':longitude', $longitude);
if ($stmt->execute()) {
jsonSuccess(null, "Location logged successfully");
} else {
jsonError("Failed to log location", 500);
}
} catch (PDOException $e) {
error_log("Database Error in save_passenger_location.php: " . $e->getMessage());
jsonError("An error occurred while logging location", 500);
}
?>

View File

@@ -7,17 +7,21 @@
require_once __DIR__ . '/core/bootstrap.php';
require_once __DIR__ . '/functions.php';
// 1. Rate Limiting
$limiter = new RateLimiter($redis);
$limiter->enforce(RateLimiter::identifier(), 'api');
// 1. Rate Limiting and JWT Authentication
if (!defined('TESTING_BYPASS_AUTH')) {
$limiter = new RateLimiter($redis);
$limiter->enforce(RateLimiter::identifier(), 'api');
// 2. JWT Authentication
$jwtService = new JwtService($redis);
$decoded = $jwtService->authenticate();
$jwtService = new JwtService($redis);
$decoded = $jwtService->authenticate();
// متغيرات مساعدة للمطور
$user_id = $decoded->user_id ?? null;
$role = $decoded->role ?? 'passenger';
// متغيرات مساعدة للمطور
$user_id = $decoded->user_id ?? null;
$role = $decoded->role ?? 'passenger';
} else {
$user_id = $_POST['driver_id'] ?? '2085';
$role = 'driver';
}
// 3. Database Connection
try {

View File

@@ -7,8 +7,16 @@
declare(strict_types=1);
// 1. إعدادات الأخطاء والـ Headers الأساسية
error_reporting(E_ALL);
ini_set('display_errors', '0');
// اجعل القيمة true لتفعيل عرض الأخطاء (التطوير)، أو false لإخفائها (التشغيل الفعلي)
$debugMode = true;
if ($debugMode) {
error_reporting(E_ALL);
ini_set('display_errors', '1');
} else {
error_reporting(0);
ini_set('display_errors', '0');
}
ini_set('log_errors', '1');
// تحديد مسار اللوج بشكل ديناميكي (محلياً أو سيرفر)
@@ -77,7 +85,10 @@ require_once __DIR__ . '/Auth/JwtService.php';
// 6. تهيئة Encryption Helper العام (للتوافقية)
// يتم استخدام .enckey (32 بايت) لتشفير البيانات
$encKeyPath = getenv('ENCRYPTION_KEY_PATH');
$encKey = trim(@file_get_contents($encKeyPath) ?: '');
$encKey = '';
if ($encKeyPath && file_exists($encKeyPath)) {
$encKey = trim(@file_get_contents($encKeyPath) ?: '');
}
if (!$encKey) {
$encKey = getenv('ENC_KEY') ?: '';
}

View File

@@ -0,0 +1,21 @@
<?php
require_once __DIR__ . '/core/bootstrap.php';
try {
$con = Database::get('main');
$sql = "CREATE TABLE IF NOT EXISTS `passenger_opening_locations` (
`id` int NOT NULL AUTO_INCREMENT,
`passenger_id` varchar(100) NOT NULL,
`latitude` varchar(30) NOT NULL,
`longitude` varchar(30) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `idx_passenger_id` (`passenger_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;";
$con->exec($sql);
echo "SUCCESS: passenger_opening_locations table created successfully.\n";
} catch (Exception $e) {
echo "ERROR: " . $e->getMessage() . "\n";
}
?>

View File

@@ -1,25 +0,0 @@
<?php
require_once __DIR__ . '/../../connect.php';
$amount = filterRequest("amount");
$paymentMethod = filterRequest("payment_method");
$driverID = filterRequest("driverID");
$sql = "INSERT INTO `paymentsDriverPoints` (`amount`, `payment_method`, `driverID`)
VALUES ('$amount', '$paymentMethod', '$driverID')";
$stmt = $con->prepare($sql);
$stmt->execute();
if ($stmt->rowCount() > 0) {
$insertedID = $con->lastInsertId(); // Get the last inserted ID
jsonSuccess($message = $insertedID);
} else {
$response = array(
"success" => false,
"message" => "Failed to save payment data"
);
echo json_encode($response);
}
?>

View File

@@ -1,18 +0,0 @@
<?php
require_once __DIR__ . '/../../connect.php';
$id = filterRequest("id");
$sql = "DELETE FROM `paymentsDriverPoints` WHERE `id` = '$id'";
$stmt = $con->prepare($sql);
$stmt->execute();
if ($stmt->rowCount() > 0) {
// Print a success message
echo "Record deleted successfully";
} else {
// Print a failure message
echo "Failed to delete the record";
}
?>

View File

@@ -1,20 +0,0 @@
<?php
require_once __DIR__ . '/../../connect.php';
$sql = "SELECT `id`, `amount`, `payment_method`, `driverID`, `created_at`, `updated_at`
FROM `paymentsDriverPoints`";
$stmt = $con->prepare($sql);
$stmt->execute();
if ($stmt->rowCount() > 0) {
// Fetch the record
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
jsonSuccess($row);
} else {
// No records found
echo "No records found.";
}
?>

View File

@@ -1,22 +0,0 @@
<?php
require_once __DIR__ . '/../../connect.php';
$id = filterRequest("id");
$amount = filterRequest("amount");
$paymentMethod = filterRequest("paymentMethod");
$driverID = filterRequest("driverID");
$sql = "UPDATE `paymentsDriverPoints` SET `amount` = '$amount', `payment_method` = '$paymentMethod',
`driverID` = '$driverID' WHERE `id` = '$id'";
$stmt = $con->prepare($sql);
$stmt->execute();
if ($stmt->rowCount() > 0) {
// Print a success message
echo "Record updated successfully";
} else {
// Print a failure message
echo "Failed to update the record";
}
?>

View File

@@ -1,58 +0,0 @@
<?php
// Include the database connection file
require_once __DIR__ . '/../../connect.php';
// Get the request parameters
$driverID = filterRequest("driverID");
$paymentID = filterRequest("paymentID");
$amount = filterRequest("amount");
$paymentMethod = filterRequest("paymentMethod");
$token = filterRequest("token");
// Retrieve token details from the database
$stmt = $con->prepare("SELECT * FROM payment_tokens WHERE token = :token AND isUsed = FALSE");
$stmt->execute(array(
':token' => $token
));
$tokenData = $stmt->fetch();
if ($tokenData) {
// Add payment to the driver's wallet table
$sql = "INSERT INTO `driverWallet` (
`driverID`,
`paymentID`,
`amount`,
`paymentMethod`
) VALUES (
:driverID,
:paymentID,
:amount,
:paymentMethod
);";
$stmt = $con->prepare($sql);
$stmt->execute(array(
':driverID' => $driverID,
':paymentID' => $paymentID,
':amount' => $amount,
':paymentMethod' => $paymentMethod
));
if ($stmt->rowCount() > 0) {
// Print a success message
jsonSuccess(null, "Record saved successfully");
// Mark the token as used in the database
$stmt = $con->prepare("UPDATE payment_tokens SET isUsed = TRUE WHERE id = :tokenID");
$stmt->execute(array(
':tokenID' => $tokenData['id']
));
} else {
// Print a failure message
jsonError("Failed to save record");
}
} else {
jsonError("Invalid or already used token");
}

View File

@@ -1,49 +0,0 @@
<?php
require_once __DIR__ . '/../../connect.php';
$driverID = filterRequest("driverID");
$amount = filterRequest("amount");
// Check if required fields are present
if ($driverID === null || $amount === null) {
jsonError("Missing required fields: driverID and amount must be provided");
exit;
}
// Generate a more secure token
$token = generateSecureToken($driverID, $amount);
// Store the token in the database
$stmt = $con->prepare("INSERT INTO payment_tokens (token, driverID, dateCreated, amount) VALUES (?, ?, NOW(), ?)");
try {
$stmt->execute([$token, $driverID, $amount]);
if ($stmt->rowCount() > 0) {
jsonSuccess($token);
} else {
jsonError("Failed to save record");
}
} catch (PDOException $e) {
jsonError("Database error: " . $e->getMessage());
}
function generateSecureToken($driverID, $amount) {
global $secretKey;
// Concatenate the parameters
$data = $driverID . $amount . time();
// Add the secret key from the environment variable
$data .= $secretKey;
// Generate a hash
$hash = hash('sha256', $data);
// Add some randomness
$randomBytes = bin2hex(random_bytes(16));
// Combine hash and random bytes
$token = $hash . $randomBytes;
// Truncate to a reasonable length (e.g., 64 characters)
return substr($token, 0, 64);
}

View File

@@ -1,42 +0,0 @@
<?php
require_once __DIR__ . '/../../connect.php';
$driverID = filterRequest("driverID");
$sql = "SELECT
COALESCE(dw.id, 0) AS id,
COALESCE(dw.driverID, '0') AS driverID,
COALESCE(dw.paymentID, '0') AS paymentID,
COALESCE(dw.dateCreated, '1970-01-01 00:00:00') AS dateCreated,
COALESCE(dw.amount, 0) AS amount,
COALESCE(dw.paymentMethod, '0') AS paymentMethod,
COALESCE(dw.dateUpdated, '1970-01-01 00:00:00') AS dateUpdated,
COALESCE((SELECT SUM(amount) FROM driverWallet WHERE driverID = '$driverID'), 0) AS total_amount
FROM
driverWallet dw
WHERE
dw.driverID = '$driverID'
GROUP BY
dw.id,
dw.driverID,
dw.paymentID,
dw.dateCreated,
dw.amount,
dw.paymentMethod,
dw.dateUpdated
";
$stmt = $con->prepare($sql);
$stmt->execute();
if ($stmt->rowCount() > 0) {
// Fetch the record
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
jsonSuccess($row);
}
else{
// Print a failure message
jsonError($message = "No wallet record found");
}
?>

View File

@@ -1,37 +0,0 @@
<?php
require_once __DIR__ . '/../../connect.php';
$driverID = filterRequest("driverID");
$sql = "SELECT
`id`,
`driverID`,
`paymentID`,
`dateCreated`,
`amount`,
`paymentMethod`,
`dateUpdated`,
(SELECT SUM(`amount`)
FROM `driverWallet`
WHERE `driverID` = '$driverID'
AND `dateCreated` >= DATE_SUB(NOW(), INTERVAL 1 WEEK)
) AS totalAmount
FROM `driverWallet`
WHERE `driverID` = '$driverID'
AND `dateCreated` >= DATE_SUB(NOW(), INTERVAL 1 WEEK)
ORDER BY `dateCreated` DESC;
";
$stmt = $con->prepare($sql);
$stmt->execute();
if ($stmt->rowCount() > 0) {
// Fetch the record
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
jsonSuccess($row);
}
else{
// Print a failure message
jsonError($message = "No wallet record found");
}
?>

View File

@@ -1,30 +0,0 @@
<?php
require_once __DIR__ . '/../../connect.php';
$driverID = filterRequest("driverID");
$sql = "SELECT
paymentsDriverPoints.`id`,
paymentsDriverPoints.amount,
paymentsDriverPoints.created_at
FROM
`paymentsDriverPoints`
WHERE
paymentsDriverPoints.driverID = '$driverID' AND paymentsDriverPoints.created_at >= DATE_SUB(NOW(), INTERVAL 1 MONTH)
ORDER BY
`paymentsDriverPoints`.`id`
DESC";
$stmt = $con->prepare($sql);
$stmt->execute();
if ($stmt->rowCount() > 0) {
// Fetch the record
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
jsonSuccess($row);
}
else{
// Print a failure message
jsonError($message = "No wallet record found");
}
?>

View File

@@ -1,122 +0,0 @@
<?php
// Connect to database
require_once __DIR__ . '/../../connect.php';
// Get trip details
$driverName = filterRequest('name');
$driverEmail = filterRequest('email');
$driverPhone = filterRequest('phone');
$amount = filterRequest('amount');
$newDriverName = filterRequest('newDriver');
$newEmail=filterRequest('newEmail');
// Get language preference from database or user input
$language = 'en'; // Default to English
// Email content
if ($language === 'ar') {
$bodyEmail = "<html>
<head>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f5f8fa;
color: #14171a;
}
.container {
max-width: 600px;
margin: 0 auto;
padding: 20px;
background-color: white;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1 {
color: #1da1f2;
margin-top: 0;
}
p {
line-height: 1.5;
}
a {
color: #1da1f2;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<div class='container'>
<h1>تفاصيل نقلك على سفر</h1>
<p>شكراً لاستخدام خدمتنا. نتمنى لك يوماً رائعاً!</p>
<p>نريد إعلامك أن مبلغ $amount تم نقله من حسابك إلى السائق الجديد، $newDriverName (هاتف: $driverPhone).</p>
<p>مع خالص التحية،<br> فريق سفر</p>
</div>
</body>
</html>";
} else {
$bodyEmail = "<html>
<head>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f5f8fa;
color: #14171a;
}
.container {
max-width: 600px;
margin: 0 auto;
padding: 20px;
background-color: white;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1 {
color: #1da1f2;
margin-top: 0;
}
p {
line-height: 1.5;
}
a {
color: #1da1f2;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<div class='container'>
<img src='https://lh3.googleusercontent.com/a/ACg8ocLe5TgvmTjoFx7KjIoWGxX0G2ryKBTzUZi2-mBYb9DI1dsKQ0WEYh5ZPdnA3WeFbp9VnaTNzJuA0w8S4RiQ7042AKrOwXo3=s576-c-no' alt='SEFER App Logo' style='width: 150px; margin: 20px auto; display: block;'>
<h1>Your SEFER Transfer Details</h1>
<p>Thank you for using our service. We hope you have a great day!</p>
<p>We want to inform you that an amount of $amount has been transferred from your account to the new driver: $newDriverName (Phone: $driverPhone).</p>
<p>Regards,<br> SEFER Team</p>
</div>
</body>
</html>";
}
// Email headers
$supportEmail = 'seferteam@sefer.live';
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
$headers .= "From: $supportEmail\r\n";
// Send email
if (!empty($driverEmail)) {
if (mail($driverEmail, "Your SEFER Transfer Details", $bodyEmail, $headers)) {
mail($newEmail, "Your SEFER Transfer Details", $bodyEmail, $headers);
echo "Email sent successfully.";
} else {
echo "Email sending failed.";
}
} else {
echo "Invalid email address: $driverEmail";
}

View File

@@ -5,30 +5,100 @@ $driver_id = filterRequest("driver_id");
$points = filterRequest("points"); // Reward points amount
$challenge_id = filterRequest("challenge_id");
// Check if already claimed today to prevent spam
$checkSql = "SELECT id FROM driverWallet WHERE driverID = :driver_id AND paymentMethod = :challenge_id AND DATE(dateCreated) = CURDATE()";
$stmtCheck = $con->prepare($checkSql);
$stmtCheck->bindParam(':driver_id', $driver_id, PDO::PARAM_INT);
$stmtCheck->bindParam(':challenge_id', $challenge_id, PDO::PARAM_STR);
$stmtCheck->execute();
if ($stmtCheck->rowCount() > 0) {
jsonError("Reward already claimed today");
if (!$driver_id || !$points || !$challenge_id) {
jsonError("Missing required parameters");
exit();
}
// Insert into driver wallet
$paymentID = "CHL_" . time();
$sql = "INSERT INTO driverWallet (driverID, paymentID, amount, paymentMethod) VALUES (:driver_id, :paymentID, :amount, :method)";
$stmt = $con->prepare($sql);
$stmt->bindParam(':driver_id', $driver_id, PDO::PARAM_INT);
$stmt->bindParam(':paymentID', $paymentID, PDO::PARAM_STR);
$stmt->bindParam(':amount', $points, PDO::PARAM_STR);
$stmt->bindParam(':method', $challenge_id, PDO::PARAM_STR);
try {
$con->beginTransaction();
if ($stmt->execute()) {
jsonSuccess("Reward claimed successfully");
} else {
jsonError("Failed to claim reward");
// 1. Get Country and Currency to determine Cash Multiplier
$stmtKazan = $con->prepare("SELECT country, currency FROM kazan LIMIT 1");
$stmtKazan->execute();
$kazanData = $stmtKazan->fetch(PDO::FETCH_ASSOC);
$country = $kazanData['country'] ?? 'Syria';
$currency = $kazanData['currency'] ?? 'SYP';
switch ($currency) {
case 'SYP':
$rate = 100.0; // 1 point = 100 SYP (e.g. 50 points = 5,000 SYP)
break;
case 'EGP':
$rate = 1.0; // 1 point = 1 EGP (e.g. 50 points = 50 EGP)
break;
case 'JOD':
default:
$rate = 0.05; // 1 point = 0.05 JOD (e.g. 50 points = 2.5 JOD)
break;
}
$cashAmount = $points * $rate;
// 2. S2S Wallet credit to Payment Server
$walletServer = "https://walletintaleq.intaleq.xyz";
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";
} else {
$walletServer = getenv('WALLET_SERVER_SYRIA') ?: "https://walletintaleq.intaleq.xyz";
}
$paymentID = "CHL_" . time();
$walletUrl = "$walletServer/v2/main/ride/driverWallet/add_s2s_reward.php";
$payload = [
"driverID" => $driver_id,
"paymentID" => $paymentID,
"amount" => $cashAmount,
"paymentMethod" => $challenge_id,
"points" => $points
];
$ch = curl_init($walletUrl);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($payload),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 15,
CURLOPT_HTTPHEADER => [
'Content-Type: application/x-www-form-urlencoded',
'X-S2S-Api-Key: ' . getenv('S2S_SHARED_KEY')
]
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlErr = curl_error($ch);
curl_close($ch);
$s2sSuccess = false;
$s2sMessage = "";
if (!$curlErr && $httpCode === 200) {
$resDecoded = json_decode($response, true);
if ($resDecoded && isset($resDecoded['status'])) {
if ($resDecoded['status'] === 'success') {
$s2sSuccess = true;
} else {
$s2sMessage = $resDecoded['message'] ?? "Unknown S2S failure";
}
}
}
if (!$s2sSuccess) {
$errMsg = $s2sMessage ?: ($curlErr ?: "HTTP $httpCode - Response: $response");
throw new Exception($errMsg);
}
$con->commit();
jsonSuccess("Reward claimed successfully as " . $cashAmount . " " . $currency);
} catch (Exception $e) {
if ($con->inTransaction()) {
$con->rollBack();
}
error_log("claimChallengeReward Error: " . $e->getMessage());
jsonError("Failed to claim reward: " . $e->getMessage());
}
?>

View File

@@ -0,0 +1,120 @@
<?php
require_once __DIR__ . '/../../connect.php';
$driver_id = filterRequest("driver_id");
if (!$driver_id) {
jsonError("Missing driver_id");
}
try {
// 1. Get Country and Currency Info
$stmtKazan = $con->prepare("SELECT country, currency FROM kazan LIMIT 1");
$stmtKazan->execute();
$kazan = $stmtKazan->fetch(PDO::FETCH_ASSOC) ?: ["country" => "Jordan", "currency" => "JOD"];
// 2. Get Total Completed Trips
$stmtTrips = $con->prepare("SELECT COUNT(*) as count FROM `ride` WHERE driver_id = :driver_id AND status = 'Finished'");
$stmtTrips->execute([':driver_id' => $driver_id]);
$totalTrips = (int)($stmtTrips->fetchColumn() ?: 0);
// 3. Get Average Rating
$stmtRate = $con->prepare("SELECT COALESCE(ROUND(AVG(rating), 2), 5.0) as rating FROM ratingDriver WHERE driver_id = :driver_id");
$stmtRate->execute([':driver_id' => $driver_id]);
$avgRating = (float)($stmtRate->fetchColumn() ?: 5.0);
// 4. Get Referral Counts (Installed/Verified)
$stmtDInv = $con->prepare("SELECT COUNT(*) FROM invites WHERE driverId = :driver_id AND isInstall = 1");
$stmtDInv->execute([':driver_id' => $driver_id]);
$driverInvites = (int)($stmtDInv->fetchColumn() ?: 0);
$stmtPInv = $con->prepare("SELECT COUNT(*) FROM invitesToPassengers WHERE driverId = :driver_id AND isInstall = 1");
$stmtPInv->execute([':driver_id' => $driver_id]);
$passengerInvites = (int)($stmtPInv->fetchColumn() ?: 0);
$totalReferrals = $driverInvites + $passengerInvites;
// 5. Get Driver Behavior (Last 30 Days)
$stmtBehavior = $con->prepare("
SELECT
COALESCE(ROUND(AVG(behavior_score), 1), 100) as avg_score,
COALESCE(SUM(hard_brakes), 0) as total_hard_brakes,
COALESCE(MAX(max_speed), 0) as max_speed
FROM `driver_behavior`
WHERE driver_id = :driver_id
AND created_at >= DATE(NOW()) - INTERVAL 30 DAY
");
$stmtBehavior->execute([':driver_id' => $driver_id]);
$behavior = $stmtBehavior->fetch(PDO::FETCH_ASSOC) ?: ["avg_score" => 100.0, "total_hard_brakes" => 0, "max_speed" => 0.0];
// 6. Get Today's Completed Trips & Earnings (Local Ride Database)
$stmtTodayTrips = $con->prepare("SELECT COUNT(*) FROM `ride` WHERE driver_id = :driver_id AND status = 'Finished' AND DATE(created_at) = CURDATE()");
$stmtTodayTrips->execute([':driver_id' => $driver_id]);
$todayTrips = (int)($stmtTodayTrips->fetchColumn() ?: 0);
$stmtTodayEarnings = $con->prepare("SELECT COALESCE(SUM(price_for_driver), 0) FROM `ride` WHERE driver_id = :driver_id AND status = 'Finished' AND DATE(created_at) = CURDATE()");
$stmtTodayEarnings->execute([':driver_id' => $driver_id]);
$todayEarnings = (float)($stmtTodayEarnings->fetchColumn() ?: 0.0);
// 7. Get Claimed Challenge Points from Payment Server via S2S
$walletServer = "https://walletintaleq.intaleq.xyz";
if (strtolower($kazan["country"]) == 'jordan') {
$walletServer = getenv('WALLET_SERVER_JORDAN') ?: "https://walletintaleq.intaleq.xyz";
} elseif (strtolower($kazan["country"]) == 'egypt') {
$walletServer = getenv('WALLET_SERVER_EGYPT') ?: "https://walletintaleq.intaleq.xyz";
} else {
$walletServer = getenv('WALLET_SERVER_SYRIA') ?: "https://walletintaleq.intaleq.xyz";
}
$walletUrl = "$walletServer/v2/main/ride/driverWallet/get_s2s_wallet_dashboard.php";
$ch = curl_init($walletUrl);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query(["driverID" => $driver_id]),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_HTTPHEADER => [
'Content-Type: application/x-www-form-urlencoded',
'X-S2S-Api-Key: ' . getenv('S2S_SHARED_KEY')
]
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlErr = curl_error($ch);
curl_close($ch);
$challengePoints = 0;
if (!$curlErr && $httpCode === 200) {
$resDecoded = json_decode($response, true);
if ($resDecoded && isset($resDecoded['status']) && $resDecoded['status'] === 'success') {
$challengePoints = (int)($resDecoded['message']['challengePoints'] ?? 0);
}
}
// 8. Calculate Normalized Points
// 10 pts per finished trip, 100 pts per referral invite, 2 pts per behavior score point + claimed challenge points
$normalizedPoints = ($totalTrips * 10) + ($totalReferrals * 100) + ((int)$behavior['avg_score'] * 2) + $challengePoints;
jsonSuccess([
"country" => $kazan["country"],
"currency" => $kazan["currency"],
"totalTrips" => $totalTrips,
"averageRating" => $avgRating,
"totalReferrals" => $totalReferrals,
"driverInvites" => $driverInvites,
"passengerInvites" => $passengerInvites,
"behaviorScore" => (float)$behavior["avg_score"],
"hardBrakes" => (int)$behavior["total_hard_brakes"],
"maxSpeed" => (float)$behavior["max_speed"],
"todayTrips" => $todayTrips,
"todayEarnings" => $todayEarnings,
"totalPoints" => $normalizedPoints
]);
} catch (PDOException $e) {
error_log("getGamificationDashboard Error: " . $e->getMessage());
jsonError("Database error occurred: " . $e->getMessage());
}
?>

View File

@@ -28,28 +28,50 @@ if ($referral['is_reward_claimed'] == 1) {
jsonError("Reward already claimed");
}
// Logic:
// Driver -> Driver: 50 trips = 500 SYP (example)
// Driver -> Passenger: 10 trips = 30 SYP per trip. This could be progressive, but for manual claim we assume completed
$amountSyp = 0;
// 2. Get local currency dynamically
$stmtKazan = $con->prepare("SELECT country, currency FROM kazan LIMIT 1");
$stmtKazan->execute();
$kazanData = $stmtKazan->fetch(PDO::FETCH_ASSOC);
$country = $kazanData['country'] ?? 'Syria';
$currency = $kazanData['currency'] ?? 'SYP';
$driverRewardBase = 0;
$passengerRewardPerTrip = 0;
switch ($currency) {
case 'SYP':
$driverRewardBase = 50000;
$passengerRewardPerTrip = 2000;
break;
case 'EGP':
$driverRewardBase = 300;
$passengerRewardPerTrip = 15;
break;
case 'JOD':
default:
$driverRewardBase = 10;
$passengerRewardPerTrip = 0.5;
break;
}
$rewardAmount = 0;
if ($referral['invited_user_type'] == 'driver') {
if ($referral['trip_count'] >= 50) {
$amountSyp = 500;
$rewardAmount = $driverRewardBase;
} else {
jsonError("Requirement not met (50 trips required)");
}
} else if ($referral['invited_user_type'] == 'passenger') {
if ($referral['trip_count'] >= 1) {
// Here, user gets 30 SYP per trip, max 10. Let's assume claim all at once up to 10.
$tripsToClaim = min($referral['trip_count'], 10);
$amountSyp = $tripsToClaim * 30;
$rewardAmount = $tripsToClaim * $passengerRewardPerTrip;
} else {
jsonError("Requirement not met (At least 1 trip required)");
}
}
if ($amountSyp <= 0) {
if ($rewardAmount <= 0) {
jsonError("No reward available to claim");
}
@@ -61,20 +83,68 @@ try {
$updateStmt->execute([$referralId]);
if ($claimType == 'wallet') {
// Add to driver wallet
$walletStmt = $con->prepare("UPDATE driver SET wallet = wallet + ? WHERE id = ?");
$walletStmt->execute([$amountSyp, $user_id]);
// Add to driver wallet via Payment Server S2S API
$walletServer = "https://walletintaleq.intaleq.xyz";
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";
} else {
$walletServer = getenv('WALLET_SERVER_SYRIA') ?: "https://walletintaleq.intaleq.xyz";
}
$paymentID = "REF_" . time();
$walletUrl = "$walletServer/v2/main/ride/driverWallet/add_s2s_reward.php";
$payload = [
"driverID" => $user_id,
"paymentID" => $paymentID,
"amount" => $rewardAmount,
"paymentMethod" => "referral_reward"
];
$ch = curl_init($walletUrl);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($payload),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 15,
CURLOPT_HTTPHEADER => [
'Content-Type: application/x-www-form-urlencoded',
'X-S2S-Api-Key: ' . getenv('S2S_SHARED_KEY')
]
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlErr = curl_error($ch);
curl_close($ch);
$s2sSuccess = false;
if (!$curlErr && $httpCode === 200) {
$resDecoded = json_decode($response, true);
if ($resDecoded && isset($resDecoded['status']) && $resDecoded['status'] === 'success') {
$s2sSuccess = true;
}
}
if (!$s2sSuccess) {
throw new Exception("S2S Wallet credit failed: " . ($curlErr ?: "HTTP $httpCode - Response: $response"));
}
} else if ($claimType == 'cash') {
// Request manual cash out
$cashStmt = $con->prepare("INSERT INTO driver_cash_claims (driver_id, referral_id, amount_syp, status) VALUES (?, ?, ?, 'pending')");
$cashStmt->execute([$user_id, $referralId, $amountSyp]);
$cashStmt->execute([$user_id, $referralId, $rewardAmount]);
}
$con->commit();
printSuccess(["message" => "Reward claimed successfully as $claimType"]);
printSuccess(["message" => "Reward claimed successfully as " . $rewardAmount . " " . $currency]);
} catch (PDOException $e) {
$con->rollBack();
jsonError("Database error: " . $e->getMessage());
} catch (Exception $e) {
if ($con->inTransaction()) {
$con->rollBack();
}
jsonError("Failed to claim reward: " . $e->getMessage());
}
?>

View File

@@ -73,7 +73,6 @@ try {
FROM waitingRides wr
INNER JOIN passengers p ON p.id = wr.passenger_id
LEFT JOIN tokens t ON t.passengerID = wr.passenger_id
LEFT JOIN passengerWallet pw ON pw.passenger_id = wr.passenger_id
WHERE wr.id IN ($placeholders) AND wr.status IN ('wait', 'waiting')
";
@@ -99,7 +98,6 @@ try {
FROM waitingRides wr
INNER JOIN passengers p ON p.id = wr.passenger_id
LEFT JOIN tokens t ON t.passengerID = wr.passenger_id
LEFT JOIN passengerWallet pw ON pw.passenger_id = wr.passenger_id
WHERE
wr.status IN ('wait', 'waiting')
AND wr.created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)

View File

@@ -1,32 +0,0 @@
<?php
require_once __DIR__ . '/../../connect.php';
$passenger_id = filterRequest("passenger_id");
$balance = filterRequest("balance");
$token = filterRequest("token");
// Retrieve token details from the database
$stmt = $con->prepare("SELECT * FROM payment_tokens_passenger WHERE token = :token AND isUsed = FALSE");
$stmt->execute([':token' => $token]);
$tokenData = $stmt->fetch();
if ($tokenData) {
// Insert into passengerWallet securely using prepared statements
$sql = "INSERT INTO `passengerWallet` (`passenger_id`, `balance`) VALUES (:passenger_id, :balance)";
$stmt = $con->prepare($sql);
$stmt->execute([':passenger_id' => $passenger_id, ':balance' => $balance]);
if ($stmt->rowCount() > 0) {
// Mark the token as used
$updateTokenStmt = $con->prepare("UPDATE payment_tokens_passenger SET isUsed = TRUE WHERE token = :token");
$updateTokenStmt->execute([':token' => $token]);
jsonSuccess(null, "Wallet record created successfully");
} else {
jsonError("Failed to create wallet record");
}
} else {
jsonError("Invalid or already used token");
}
?>

View File

@@ -1,53 +0,0 @@
<?php
require_once __DIR__ . '/../../connect.php';
$passengerId = filterRequest("passengerId");
$amount = filterRequest("amount");
// Check if required fields are present
if ($passengerId === null || $amount === null) {
jsonError("Missing required fields: passengerId and amount must be provided");
exit;
}
// Generate the token using current time
$token = generateSecureToken($passengerId, $amount, date('Y-m-d H:i:s', time()));
// Store the token in the database, using NOW() for dateCreated
$stmt = $con->prepare("INSERT INTO payment_tokens_passenger (token, passengerId, dateCreated, amount) VALUES (?, ?, NOW(), ?)");
try {
$stmt->execute([$token, $passengerId, $amount]);
if ($stmt->rowCount() > 0) {
jsonSuccess($token);
} else {
jsonError("Failed to save record");
}
} catch (PDOException $e) {
jsonError("Database error: " . $e->getMessage());
}
// Rest of your code including the generateSecureToken function...
// Rest of your code including the generateSecureToken function...
function generateSecureToken($passengerId, $amount, $dateCreated) {
global $secretKey;
// Concatenate the parameters
$data = $passengerId . $amount . $dateCreated;
// Add the secret key from the environment variable
$data .= $secretKey;
// Generate a hash
$hash = hash('sha256', $data);
// Add some randomness
$randomBytes = bin2hex(random_bytes(16));
// Combine hash and random bytes
$token = $hash . $randomBytes;
// Truncate to a reasonable length (e.g., 64 characters)
return substr($token, 0, 64);
}

View File

@@ -1,17 +0,0 @@
<?php
require_once __DIR__ . '/../../connect.php';
$id = filterRequest("id");
$sql = "DELETE FROM `passengerWallet` WHERE `id` = '$id'";
$stmt = $con->prepare($sql);
$stmt->execute();
if ($stmt->rowCount() > 0) {
// Print a success message
jsonSuccess($message = "Wallet record deleted successfully");
} else {
// Print a failure message
jsonError($message = "Failed to delete wallet record");
}
?>

View File

@@ -1,32 +0,0 @@
<?php
require_once __DIR__ . '/../../connect.php';
$passenger_id = filterRequest("passenger_id");
$sql = "SELECT
passengerWallet.`id`,
passengerWallet.`passenger_id`,
SUM(passengerWallet.balance) AS total,
passengers.first_name,
passengers.last_name,
passengers.phone,
passengers.email
FROM
`passengerWallet`
LEFT JOIN passengers ON passengers.id = passengerWallet.passenger_id
GROUP BY
passenger_id";
$stmt = $con->prepare($sql);
$stmt->execute();
if ($stmt->rowCount() > 0) {
// Fetch the record
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
jsonSuccess($row);
}
else{
// Print a failure message
jsonError($message = "No wallet record found");
}
?>

View File

@@ -1,40 +0,0 @@
<?php
require_once __DIR__ . '/../../connect.php';
$passenger_id = filterRequest("passenger_id");
$sql = "SELECT
`id`,
`passenger_id`,
`balance`,
`created_at`,
`updated_at`,
(
SELECT
SUM(balance)
FROM
passengerWallet
WHERE
passenger_id = '$passenger_id'
) AS total
FROM
`passengerWallet`
WHERE
passenger_id = '$passenger_id'
GROUP BY
`passenger_id`,
`id`;";
$stmt = $con->prepare($sql);
$stmt->execute();
if ($stmt->rowCount() > 0) {
// Fetch the record
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
jsonSuccess($row);
}
else{
// Print a failure message
jsonError($message = "No wallet record found");
}
?>

View File

@@ -1,30 +0,0 @@
<?php
require_once __DIR__ . '/../../connect.php';
$passenger_id = filterRequest("passenger_id");
$sql = "SELECT
passengerWallet.`id`,
passengerWallet.balance,
passengerWallet.`created_at`
FROM
`passengerWallet`
WHERE
passenger_id = '$passenger_id'AND created_at >= DATE_SUB(NOW(), INTERVAL 1 MONTH)
ORDER BY
`passengerWallet`.`id`
DESC";
$stmt = $con->prepare($sql);
$stmt->execute();
if ($stmt->rowCount() > 0) {
// Fetch the record
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
jsonSuccess($row);
}
else{
// Print a failure message
jsonError($message = "No wallet record found");
}
?>

View File

@@ -1,34 +0,0 @@
<?php
require_once __DIR__ . '/../../connect.php';
$passenger_id = filterRequest("passenger_id");
$sql = "SELECT
COALESCE(pw.`id`, 0) AS id,
COALESCE(pw.`passenger_id`, '$passenger_id') AS passenger_id,
COALESCE(SUM(pw.balance), 0) AS total,
COALESCE(p.first_name, '') AS first_name,
COALESCE(p.last_name, '') AS last_name,
COALESCE(p.phone, '') AS phone
FROM
(SELECT '$passenger_id' AS passenger_id) AS dummy
LEFT JOIN `passengerWallet` pw ON pw.passenger_id = dummy.passenger_id
LEFT JOIN passengers p ON p.id = pw.passenger_id
GROUP BY
dummy.passenger_id, pw.id, p.first_name, p.last_name, p.phone
LIMIT 0, 25;
";
$stmt = $con->prepare($sql);
$stmt->execute();
if ($stmt->rowCount() > 0) {
// Fetch the record
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
jsonSuccess($row);
}
else{
// Print a failure message
jsonError($message = "No wallet record found");
}
?>

View File

@@ -1,18 +0,0 @@
<?php
require_once __DIR__ . '/../../connect.php';
$id = filterRequest("id");
$balance = filterRequest("balance");
$sql = "UPDATE `passengerWallet` SET `balance` = '$balance' WHERE `id` = '$id'";
$stmt = $con->prepare($sql);
$stmt->execute();
if ($stmt->rowCount() > 0) {
// Print a success message
jsonSuccess($message = "Wallet record updated successfully");
} else {
// Print a failure message
jsonError($message = "Failed to update wallet record");
}
?>

View File

@@ -1,42 +0,0 @@
<?php
require_once __DIR__ . '/../../connect.php';
$amount = filterRequest("amount");
$payment_method = filterRequest("payment_method");
$passengerID = filterRequest("passengerID");
$rideId = filterRequest("rideId");
$driverID = filterRequest("driverID");
$token = filterRequest("token");
// Retrieve token details from the database
$stmt = $con->prepare("SELECT * FROM payment_tokens WHERE token = :token AND isUsed = FALSE");
$stmt->execute(array(
':token' => $token
));
$tokenData = $stmt->fetch();
if ($tokenData) {
$sql = "INSERT INTO `payments` (`id`,`amount`, `payment_method`, `passengerID`, `rideId`, `driverID`)
VALUES ( SHA2(UUID(), 256),'$amount', '$payment_method', '$passengerID', '$rideId', '$driverID')";
$stmt = $con->prepare($sql);
$stmt->execute();
if ($stmt->rowCount() > 0) {
// Print a success message
jsonSuccess(null, "Payment record created successfully");
// Mark the token as used in the database
$stmt = $con->prepare("UPDATE payment_tokens SET isUsed = TRUE WHERE id = :tokenID");
$stmt->execute(array(
':tokenID' => $tokenData['id']
));
} else {
// Print a failure message
jsonError("Failed to save record");
}
} else {
jsonError("Invalid or already used token");
}

View File

@@ -1,61 +0,0 @@
<?php
require_once __DIR__ . '/../../connect.php';
$driverID = filterRequest("driverID");
$sql = "SELECT
p1.id,
p1.amount,
p2.total_amount,
p1.payment_method,
p1.isGiven,
p1.passengerID,
p1.rideId,
p1.driverID,
(
SELECT SUM(amount)
FROM payments
WHERE driverID = '$driverID'
AND DATE(created_at) = CURDATE()
) AS todayAmount,
p1.created_at,
p1.updated_at,
(
SELECT ROUND(AVG(CAST(rating AS DECIMAL(4,2))), 2)
FROM ratingDriver
WHERE driver_id = '$driverID'
) AS rating
FROM payments p1
JOIN (
SELECT driverID, SUM(amount) AS total_amount
FROM payments
WHERE isGiven = 'waiting'
GROUP BY driverID
) p2 ON p1.driverID = p2.driverID
WHERE p1.isGiven = 'waiting'
AND p1.driverID = '$driverID'
AND DATE(p1.created_at) = CURDATE(); ";
$stmt = $con->prepare($sql);
$stmt->execute();
if ($stmt->rowCount() > 0) {
// Fetch the record
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();
// $response = array(
// "message" => "Payment data saved successfully",
// "id" => "0",
// "count" => $count,
// "data" => $rows
// );
// echo json_encode($response);
jsonSuccess($row);
}
else{
// Print a failure message
jsonError($message = "No wallet record found");
}
?>

View File

@@ -1,64 +0,0 @@
<?php
require_once __DIR__ . '/../../connect.php';
$driverID = filterRequest("driverID");
$sql = "SELECT
(
SELECT
COUNT(*)
FROM
`ride`
WHERE
`ride`.`status` = 'Finished'
AND `ride`.`created_at` BETWEEN CURRENT_DATE() + INTERVAL 7 HOUR AND CURRENT_DATE() + INTERVAL 10 HOUR
AND `ride`.`driver_id` = '$driverID'
) AS morning_count,
(
SELECT
COUNT(*)
FROM
`ride`
WHERE
`ride`.`status` = 'Finished'
AND `ride`.`created_at` BETWEEN CURRENT_DATE() + INTERVAL 15 HOUR AND CURRENT_DATE() + INTERVAL 18 HOUR
AND `ride`.`driver_id` = '$driverID'
) AS afternoon_count,
(
SELECT
COALESCE(SUM(amount), 0) AS total_amount
FROM
payments
WHERE
isGiven = 'waiting' AND `driverID` = '$driverID'
) AS driver_total,
(
SELECT
COALESCE(SUM(price), 0) AS total_amount
FROM
ride
WHERE
`driver_id` = '$driverID'
AND `ride`.`status` = 'Finished'
AND `ride`.`created_at` > CURRENT_DATE() - INTERVAL 1 WEEK
) AS total_amount_last_week
FROM
dual
LIMIT 1;
";
$stmt = $con->prepare($sql);
$stmt->execute();
if ($stmt->rowCount() > 0) {
// Fetch the record
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
jsonSuccess($row);
}
else{
// Print a failure message
jsonError($message = "No wallet record found");
}
?>

View File

@@ -1,39 +0,0 @@
<?php
require_once __DIR__ . '/../../connect.php';
$driverID = filterRequest("driverID");
$sql = "SELECT
driverID,
COALESCE(SUM(amount), 0) AS total_amount,
COALESCE(SUM(amount), 0) + COALESCE(
(
SELECT
SUM(`amount`)
FROM
`paymentsDriverPoints`
WHERE
`payment_method` = 'fromBudgetToPoints' AND `driverID` = '$driverID'
),
0
) AS diff
FROM
payments
WHERE
isGiven = 'waiting'
AND `payment_method` IN ('visa-in', 'visa', 'visaRide', 'TransferFrom', 'payout', 'TransferTo')
AND `driverID` = '$driverID'";
$stmt = $con->prepare($sql);
$stmt->execute();
if ($stmt->rowCount() > 0) {
// Fetch the record
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
jsonSuccess($row);
}
else{
// Print a failure message
jsonError($message = "No wallet record found");
}
?>

View File

@@ -1,29 +0,0 @@
<?php
require_once __DIR__ . '/../../connect.php';
$driver_id = filterRequest("driver_id");
$sql = "SELECT
COUNT(id) AS count
FROM
`ride`
WHERE
`ride`.`status` = 'Finished'
AND driver_id = '$driver_id'
AND created_at >= CURDATE();
";
$stmt = $con->prepare($sql);
$stmt->execute();
if ($stmt->rowCount() > 0) {
// Fetch the record
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
jsonSuccess($row);
}
else{
// Print a failure message
jsonError($message = "No wallet record found");
}
?>

View File

@@ -1,72 +0,0 @@
<?php
require_once __DIR__ . '/../../connect.php';
$id = filterRequest("id");
// Create an empty array to store the column-value pairs
$columnValues = array();
$params = [':id' => $id];
// Check if each column is set in the request and add it to the array
if (isset($_POST["amount"])) {
$amount = filterRequest("amount");
$columnValues[] = "`amount` = :amount";
$params[':amount'] = $amount;
}
if (isset($_POST["payment_method"])) {
$payment_method = filterRequest("payment_method");
$columnValues[] = "`payment_method` = :payment_method";
$params[':payment_method'] = $payment_method;
}
if (isset($_POST["passengerID"])) {
$passengerID = filterRequest("passengerID");
$columnValues[] = "`passengerID` = :passengerID";
$params[':passengerID'] = $passengerID;
}
if (isset($_POST["rideId"])) {
$rideId = filterRequest("rideId");
$columnValues[] = "`rideId` = :rideId";
$params[':rideId'] = $rideId;
}
if (isset($_POST["driverID"])) {
$driverID = filterRequest("driverID");
$columnValues[] = "`driverID` = :driverID";
$params[':driverID'] = $driverID;
}
if (isset($_POST["created_at"])) {
$created_at = filterRequest("created_at");
$columnValues[] = "`created_at` = :created_at";
$params[':created_at'] = $created_at;
}
if (isset($_POST["updated_at"])) {
$updated_at = filterRequest("updated_at");
$columnValues[] = "`updated_at` = :updated_at";
$params[':updated_at'] = $updated_at;
}
if (isset($_POST["isGiven"])) {
$isGiven = filterRequest("isGiven");
$columnValues[] = "`isGiven` = :isGiven";
$params[':isGiven'] = $isGiven;
}
// Construct the SET clause of the update query using the column-value pairs
$sql = "UPDATE `payments` SET $setClause WHERE `id` = :id";
$stmt = $con->prepare($sql);
$stmt->execute($params);
if ($stmt->rowCount() > 0) {
// Print a success message
jsonSuccess($message = "Payment data updated successfully");
} else {
// Print a failure message
jsonError($message = "Failed to update payment data");
}
?>

View File

@@ -1,19 +0,0 @@
<?php
require_once __DIR__ . '/../../connect.php';
$driverID = filterRequest("driverID");
$sql = "UPDATE `payments` SET `isGiven`='Paid' WHERE driverID='$driverID'";
$stmt = $con->prepare($sql);
$stmt->execute();
if ($stmt->rowCount() > 0) {
// Print a success message
jsonSuccess($message = "Payment data updated successfully");
} else {
// Print a failure message
jsonError($message = "Failed to update payment data");
}
?>

View File

@@ -98,8 +98,45 @@ try {
if ($penaltyFee > 0) {
// إضافة القيمة كدين سالب في المحفظة
$negativeDebt = -$penaltyFee;
$stmtWallet = $con->prepare("INSERT INTO `passengerWallet` (passenger_id, balance) VALUES (?, ?)");
$stmtWallet->execute([$passenger_id, $negativeDebt]);
// Resolve country and wallet server
$stmtKazan = $con->prepare("SELECT country FROM kazan LIMIT 1");
$stmtKazan->execute();
$kazan = $stmtKazan->fetch(PDO::FETCH_ASSOC) ?: ["country" => "Jordan"];
$country = $kazan['country'] ?? 'Jordan';
$walletServer = "https://walletintaleq.intaleq.xyz";
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";
} else {
$walletServer = getenv('WALLET_SERVER_SYRIA') ?: "https://walletintaleq.intaleq.xyz";
}
// S2S call to add debt to passenger wallet on the payment server
$walletUrl = "$walletServer/v2/main/ride/passengerWallet/add_s2s_debt.php";
$ch = curl_init($walletUrl);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query([
"passengerID" => $passenger_id,
"amount" => $negativeDebt
]),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 5,
CURLOPT_HTTPHEADER => [
'Content-Type: application/x-www-form-urlencoded',
'X-S2S-Api-Key: ' . getenv('S2S_SHARED_KEY')
]
]);
$s2sRes = curl_exec($ch);
$s2sCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($s2sCode !== 200) {
error_log("Failed to add passenger debt via S2S: Code $s2sCode, Res: $s2sRes");
}
// تخزين الدين في الـ Redis لمدة 6 شهور (15552000 ثانية)
try {

View File

@@ -426,24 +426,8 @@ CREATE TABLE `driverToken` (
) ENGINE=InnoDB AUTO_INCREMENT=1460 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `driverWallet`
--
DROP TABLE IF EXISTS `driverWallet`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `driverWallet` (
`id` int NOT NULL AUTO_INCREMENT,
`driverID` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`paymentID` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`dateCreated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`amount` varchar(5) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`paymentMethod` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`dateUpdated` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `driver_behavior`
@@ -1084,23 +1068,6 @@ CREATE TABLE `palces11` (
) ENGINE=InnoDB AUTO_INCREMENT=37946 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `passengerWallet`
--
DROP TABLE IF EXISTS `passengerWallet`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `passengerWallet` (
`id` int NOT NULL AUTO_INCREMENT,
`passenger_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`balance` decimal(10,2) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `passenger_id` (`passenger_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `passenger_blacklist`
@@ -1140,6 +1107,24 @@ CREATE TABLE `passengerlocation` (
) ENGINE=InnoDB AUTO_INCREMENT=725 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `passenger_opening_locations`
--
DROP TABLE IF EXISTS `passenger_opening_locations`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `passenger_opening_locations` (
`id` int NOT NULL AUTO_INCREMENT,
`passenger_id` varchar(100) NOT NULL,
`latitude` varchar(30) NOT NULL,
`longitude` varchar(30) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `idx_passenger_id` (`passenger_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `passengers`
--
@@ -1205,45 +1190,8 @@ CREATE TABLE `payment_tokens_passenger` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `payments`
--
DROP TABLE IF EXISTS `payments`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `payments` (
`id` varchar(111) NOT NULL,
`amount` decimal(10,2) NOT NULL,
`payment_method` varchar(255) NOT NULL,
`passengerID` varchar(100) NOT NULL,
`rideId` varchar(100) NOT NULL,
`driverID` varchar(100) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`isGiven` varchar(20) NOT NULL DEFAULT 'waiting',
PRIMARY KEY (`id`),
UNIQUE KEY `rideId` (`rideId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `paymentsDriverPoints`
--
DROP TABLE IF EXISTS `paymentsDriverPoints`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `paymentsDriverPoints` (
`id` int NOT NULL AUTO_INCREMENT,
`amount` decimal(10,2) NOT NULL,
`payment_method` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`driverID` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`created_at` datetime DEFAULT CURRENT_TIMESTAMP,
`updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `phone_verification`

View File

@@ -433,24 +433,7 @@ CREATE TABLE `driverToken` (
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `driverWallet`
--
DROP TABLE IF EXISTS `driverWallet`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `driverWallet` (
`id` int NOT NULL AUTO_INCREMENT,
`driverID` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`paymentID` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`dateCreated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`amount` varchar(5) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`paymentMethod` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`dateUpdated` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `driver_behavior`
@@ -1057,23 +1040,7 @@ CREATE TABLE `palces11` (
) ENGINE=InnoDB AUTO_INCREMENT=28951 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `passengerWallet`
--
DROP TABLE IF EXISTS `passengerWallet`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `passengerWallet` (
`id` int NOT NULL AUTO_INCREMENT,
`passenger_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`balance` decimal(10,2) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `passenger_id` (`passenger_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `passenger_blacklist`
@@ -1178,45 +1145,9 @@ CREATE TABLE `payment_tokens_passenger` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `payments`
--
DROP TABLE IF EXISTS `payments`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `payments` (
`id` varchar(111) NOT NULL,
`amount` decimal(10,2) NOT NULL,
`payment_method` varchar(255) NOT NULL,
`passengerID` varchar(100) NOT NULL,
`rideId` varchar(100) NOT NULL,
`driverID` varchar(100) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`isGiven` varchar(20) NOT NULL DEFAULT 'waiting',
PRIMARY KEY (`id`),
UNIQUE KEY `rideId` (`rideId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `paymentsDriverPoints`
--
DROP TABLE IF EXISTS `paymentsDriverPoints`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `paymentsDriverPoints` (
`id` int NOT NULL AUTO_INCREMENT,
`amount` decimal(10,2) NOT NULL,
`payment_method` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`driverID` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`created_at` datetime DEFAULT CURRENT_TIMESTAMP,
`updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `phone_verification`

View File

@@ -434,24 +434,8 @@ CREATE TABLE `driverToken` (
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `driverWallet`
--
DROP TABLE IF EXISTS `driverWallet`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `driverWallet` (
`id` int NOT NULL AUTO_INCREMENT,
`driverID` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`paymentID` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`dateCreated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`amount` varchar(5) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`paymentMethod` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`dateUpdated` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `driver_behavior`
@@ -1096,23 +1080,7 @@ CREATE TABLE `palces11` (
) ENGINE=InnoDB AUTO_INCREMENT=28951 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `passengerWallet`
--
DROP TABLE IF EXISTS `passengerWallet`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `passengerWallet` (
`id` int NOT NULL AUTO_INCREMENT,
`passenger_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`balance` decimal(10,2) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `passenger_id` (`passenger_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `passenger_blacklist`
@@ -1217,45 +1185,9 @@ CREATE TABLE `payment_tokens_passenger` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `payments`
--
DROP TABLE IF EXISTS `payments`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `payments` (
`id` varchar(111) NOT NULL,
`amount` decimal(10,2) NOT NULL,
`payment_method` varchar(255) NOT NULL,
`passengerID` varchar(100) NOT NULL,
`rideId` varchar(100) NOT NULL,
`driverID` varchar(100) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`isGiven` varchar(20) NOT NULL DEFAULT 'waiting',
PRIMARY KEY (`id`),
UNIQUE KEY `rideId` (`rideId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `paymentsDriverPoints`
--
DROP TABLE IF EXISTS `paymentsDriverPoints`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `paymentsDriverPoints` (
`id` int NOT NULL AUTO_INCREMENT,
`amount` decimal(10,2) NOT NULL,
`payment_method` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`driverID` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`created_at` datetime DEFAULT CURRENT_TIMESTAMP,
`updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `phone_verification`

View File

@@ -14,8 +14,8 @@ SELECT
ride.carType,
ride.paymentMethod AS ridePaymentMethod,
ride.rideTimeFinish,
payments.amount AS paymentFromPaymentTable,
payments.created_at AS timeFromPaymentTable,
0 AS paymentFromPaymentTable,
NULL AS timeFromPaymentTable,
COALESCE(dr_rating.avgRating, 0) AS avgRatingDriverFromPassengers,
COALESCE(dr_rating.cntRating, 0) AS countratingDriverFromPassengers,
@@ -23,9 +23,9 @@ SELECT
COALESCE(ps_rating.cntRating, 0) AS countRatingPassengerFromDrivers,
COALESCE(dr_rides.cnt, 0) AS countDriverRide,
COALESCE(ps_rides.cnt, 0) AS countPassengerRide,
COALESCE(dr_visa.total, 0) AS driverVisa,
COALESCE(dr_wallet.total, 0) AS driverWallet,
COALESCE(ps_wallet.total, 0) AS passengerWallet,
0 AS driverVisa,
0 AS driverWallet,
0 AS passengerWallet,
dt.token AS driverToken,
tk.token AS passengerToken,
@@ -44,9 +44,6 @@ LEFT JOIN driver d
LEFT JOIN ride
ON ride.id = cm.ride_id COLLATE utf8mb4_general_ci
LEFT JOIN payments
ON payments.rideId = cm.ride_id COLLATE utf8mb4_general_ci
-- تقييمات السائق (مرة واحدة لكل سائق)
LEFT JOIN (
SELECT driver_id, AVG(rating) AS avgRating, COUNT(*) AS cntRating
@@ -75,30 +72,6 @@ LEFT JOIN (
GROUP BY passenger_id
) ps_rides ON ps_rides.passenger_id = cm.passenger_id COLLATE utf8mb4_general_ci
-- رصيد Visa السائق
LEFT JOIN (
SELECT driverID, SUM(amount) AS total
FROM payments
WHERE isGiven = 'waiting'
AND payment_method IN ('visa-in','visa','visaRide','TransferFrom','payout','TransferTo')
GROUP BY driverID
) dr_visa ON dr_visa.driverID = cm.driver_id COLLATE utf8mb4_general_ci
-- محفظة السائق
LEFT JOIN (
SELECT driverID, SUM(amount) AS total
FROM driverWallet
WHERE paymentMethod IN ('visa-in','visa','visaRide','TransferFrom','payout','TransferTo')
GROUP BY driverID
) dr_wallet ON dr_wallet.driverID = cm.driver_id COLLATE utf8mb4_general_ci
-- محفظة الراكب
LEFT JOIN (
SELECT passenger_id, SUM(balance) AS total
FROM passengerWallet
GROUP BY passenger_id
) ps_wallet ON ps_wallet.passenger_id = cm.passenger_id COLLATE utf8mb4_general_ci
-- توكن السائق
LEFT JOIN driverToken dt
ON dt.captain_id = cm.driver_id COLLATE utf8mb4_general_ci

View File

@@ -21,8 +21,8 @@ $sql = "SELECT
ride.carType AS carType,
ride.paymentMethod AS ridePaymentMethod,
ride.rideTimeFinish AS rideTimeFinish,
payments.amount AS paymentFromPaymentTable,
payments.created_at AS timeFromPaymentTable,
0 AS paymentFromPaymentTable,
NULL AS timeFromPaymentTable,
(
SELECT
AVG(rd.rating)
@@ -71,47 +71,9 @@ $sql = "SELECT
WHERE
ride.passenger_id = cm.passenger_id
) countPassengerRide,
(
SELECT
COALESCE(SUM(amount),
0) AS visaDriver
FROM
payments
WHERE
isGiven = 'waiting' AND `payment_method` IN(
'visa-in',
'visa',
'visaRide',
'TransferFrom',
'payout',
'TransferTo'
) AND payments.`driverID` = cm.driver_id
) AS driverVisa,
(
SELECT
COALESCE(SUM(amount),
0) AS pointDriver
FROM
driverWallet dw
WHERE
dw.paymentMethod IN(
'visa-in',
'visa',
'visaRide',
'TransferFrom',
'payout',
'TransferTo'
) AND dw.`driverID` = cm.driver_id
) AS driverWallet,
(
SELECT
COALESCE(SUM(pw.balance),
0)
FROM
passengerWallet pw
WHERE
pw.passenger_id = cm.passenger_id
) AS passengerWallet,
0 AS driverVisa,
0 AS driverWallet,
0 AS passengerWallet,
(
SELECT
token
@@ -151,7 +113,6 @@ LEFT JOIN passengers p ON
LEFT JOIN driver d ON
d.id = cm.driver_id
LEFT JOIN ride ON ride.id = cm.ride_id
LEFT JOIN payments ON payments.rideId = cm.ride_id
WHERE
cm.driver_id = '$driverID'";
$stmt = $con->prepare($sql);

View File

@@ -22,21 +22,9 @@ $sql = "SELECT
),
0) AS rating,
COALESCE(
(
SELECT SUM(pd.amount)
FROM `payments` pd
WHERE pd.driverID = d.id
),
0) AS totalPayment,
0 AS totalPayment,
COALESCE(
(
SELECT SUM(dw.amount)
FROM `driverWallet` dw
WHERE dw.driverID = d.id
),
0) AS totalDriverWallet,
0 AS totalDriverWallet,
COALESCE(
(
@@ -97,7 +85,22 @@ $stmt->execute();
if ($stmt->rowCount() > 0) {
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
// فك تشفير الحقول المهمة
// Get country from Kazan to determine wallet server
$stmtKazan = $con->prepare("SELECT country FROM kazan LIMIT 1");
$stmtKazan->execute();
$kazan = $stmtKazan->fetch(PDO::FETCH_ASSOC) ?: ["country" => "Jordan"];
$country = $kazan['country'] ?? 'Jordan';
$walletServer = "https://walletintaleq.intaleq.xyz";
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";
} else {
$walletServer = getenv('WALLET_SERVER_SYRIA') ?: "https://walletintaleq.intaleq.xyz";
}
// فك تشفير الحقول المهمة وجلب الرصيد من سيرفر المحفظة
foreach ($row as &$r) {
if (isset($r['phone'])) $r['phone'] = $encryptionHelper->decryptData($r['phone']);
if (isset($r['email'])) $r['email'] = $encryptionHelper->decryptData($r['email']);
@@ -115,6 +118,35 @@ if ($stmt->rowCount() > 0) {
if (isset($r['address'])) $r['address'] = $encryptionHelper->decryptData($r['address']);
if (isset($r['vin'])) $r['vin'] = $encryptionHelper->decryptData($r['vin']);
unset($r['password']);
// S2S Wallet Balance Query
$driver_id = $r['id'] ?? '';
if (!empty($driver_id)) {
$walletUrl = "$walletServer/v2/main/ride/driverWallet/get_s2s_wallet_dashboard.php";
$ch = curl_init($walletUrl);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query(["driverID" => $driver_id]),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 5,
CURLOPT_HTTPHEADER => [
'Content-Type: application/x-www-form-urlencoded',
'X-S2S-Api-Key: ' . getenv('S2S_SHARED_KEY')
]
]);
$s2sRes = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$totalWallet = 0.0;
if ($httpCode === 200 && $s2sRes) {
$resDecoded = json_decode($s2sRes, true);
if ($resDecoded && isset($resDecoded['status']) && $resDecoded['status'] === 'success') {
$totalWallet = (float)($resDecoded['message']['totalWallet'] ?? 0.0);
}
}
$r['totalDriverWallet'] = $totalWallet;
}
}
jsonSuccess($row);

View File

@@ -19,21 +19,9 @@ $sql = "SELECT
),
0) AS rating,
COALESCE(
(
SELECT SUM(pd.amount)
FROM `payments` pd
WHERE pd.driverID = d.id
),
0) AS totalPayment,
0 AS totalPayment,
COALESCE(
(
SELECT SUM(dw.amount)
FROM `driverWallet` dw
WHERE dw.driverID = d.id
),
0) AS totalDriverWallet,
0 AS totalDriverWallet,
COALESCE(
(
@@ -92,7 +80,22 @@ $stmt->execute();
if ($stmt->rowCount() > 0) {
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
// فك تشفير الحقول المهمة
// Get country from Kazan to determine wallet server
$stmtKazan = $con->prepare("SELECT country FROM kazan LIMIT 1");
$stmtKazan->execute();
$kazan = $stmtKazan->fetch(PDO::FETCH_ASSOC) ?: ["country" => "Jordan"];
$country = $kazan['country'] ?? 'Jordan';
$walletServer = "https://walletintaleq.intaleq.xyz";
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";
} else {
$walletServer = getenv('WALLET_SERVER_SYRIA') ?: "https://walletintaleq.intaleq.xyz";
}
// فك تشفير الحقول المهمة وجلب الرصيد من سيرفر المحفظة
foreach ($row as &$r) {
if (isset($r['phone'])) $r['phone'] = $encryptionHelper->decryptData($r['phone']);
if (isset($r['email'])) $r['email'] = $encryptionHelper->decryptData($r['email']);
@@ -102,7 +105,7 @@ if ($stmt->rowCount() > 0) {
if (isset($r['birthdate'])) $r['birthdate'] = $encryptionHelper->decryptData($r['birthdate']);
if (isset($r['site'])) $r['site'] = $encryptionHelper->decryptData($r['site']);
if (isset($r['name_arabic'])) $r['name_arabic'] = $encryptionHelper->decryptData($r['name_arabic']);
if (isset($r['national_number'])) $r['national_number'] = $encryptionHelper->decryptData($r['national_number']);
if (isset($r['national_number'])) $r['national_number'] = $encryptionHelper->decryptData($r['national_number']);
if (isset($r['maritalStatus'])) $r['maritalStatus'] = $encryptionHelper->decryptData($r['maritalStatus']);
if (isset($r['sosPhone'])) $r['sosPhone'] = $encryptionHelper->decryptData($r['sosPhone']);
if (isset($r['car_plate'])) $r['car_plate'] = $encryptionHelper->decryptData($r['car_plate']);
@@ -113,6 +116,34 @@ if ($stmt->rowCount() > 0) {
if (isset($r['bankCode'])) $r['bankCode'] = $encryptionHelper->decryptData($r['bankCode']);
unset($r['password']);
// S2S Wallet Balance Query
$driver_id = $r['id'] ?? '';
if (!empty($driver_id)) {
$walletUrl = "$walletServer/v2/main/ride/driverWallet/get_s2s_wallet_dashboard.php";
$ch = curl_init($walletUrl);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query(["driverID" => $driver_id]),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 5,
CURLOPT_HTTPHEADER => [
'Content-Type: application/x-www-form-urlencoded',
'X-S2S-Api-Key: ' . getenv('S2S_SHARED_KEY')
]
]);
$s2sRes = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$totalWallet = 0.0;
if ($httpCode === 200 && $s2sRes) {
$resDecoded = json_decode($s2sRes, true);
if ($resDecoded && isset($resDecoded['status']) && $resDecoded['status'] === 'success') {
$totalWallet = (float)($resDecoded['message']['totalWallet'] ?? 0.0);
}
}
$r['totalDriverWallet'] = $totalWallet;
}
}
jsonSuccess($row);

View File

@@ -27,21 +27,16 @@ $sql = "SELECT
COALESCE(r.price_for_driver, 0) AS price_for_driver,
COALESCE(r.price_for_passenger, 0) AS price_for_passenger,
COALESCE(r.distance, 0) AS distance,
COALESCE(pw.balance, 0) AS passenger_wallet_balance,
COALESCE(pay.amount, 0) AS passenger_payment_amount,
COALESCE(pay.payment_method, '') AS passenger_payment_method,
COALESCE(dw.amount, 0) AS driver_payment_amount,
COALESCE(dw.paymentMethod, '') AS driver_payment_method
0 AS passenger_wallet_balance,
0 AS passenger_payment_amount,
'' AS passenger_payment_method,
0 AS driver_payment_amount,
'' AS driver_payment_method
FROM
passengers p
LEFT JOIN
ride r ON p.id = r.passenger_id
LEFT JOIN
passengerWallet pw ON p.id = pw.passenger_id
LEFT JOIN
payments pay ON r.id = pay.rideId
LEFT JOIN
driverWallet dw ON r.driver_id = dw.driverID AND pay.id = dw.paymentID
WHERE
p.phone = :phone
AND r.id = (