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

@@ -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 {