Update: 2026-06-12 20:40:40

This commit is contained in:
Hamza-Ayed
2026-06-12 20:40:40 +03:00
parent 305ae01d52
commit f907212c57
294 changed files with 3592 additions and 3581 deletions

View File

@@ -1,75 +0,0 @@
<?php
// Start a session to store state and tokens.
session_start();
// 1. SETUP: Install the Google API Client Library
// Run this command in your project directory: composer require google/apiclient:^2.0
require_once __DIR__ . '/vendor/autoload.php';
// 2. CONFIGURATION: Replace with your credentials from Google Cloud Console
$clientID = '1086900987150-j8brn0i5s97315kh1ej9jr72grkfqgh5.apps.googleusercontent.com'; // Replace with your Client ID
$clientSecret = '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'; // Replace with your Client Secret
// This must be the exact URL of this script.
$redirectUri = 'https://api.tripz-egypt.com/tripz/auth/syria/auth_proxy.php'; // Replace with your script's URL
// 3. APP CONFIGURATION: Your Flutter app's custom URI scheme
// This is how the browser will redirect back to your app.
$appRedirectScheme = 'siroapp://auth'; // e.g., myapp://auth
// Create a new Google Client object
$client = new Google_Client();
$client->setClientId($clientID);
$client->setClientSecret($clientSecret);
$client->setRedirectUri($redirectUri);
$client->addScope("email");
$client->addScope("profile");
// 4. LOGIC: Handle the authentication flow
if (isset($_GET['code'])) {
// A. User has been redirected back from Google with an authorization code.
try {
// Exchange the authorization code for an access token.
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
if (isset($token['error'])) {
// Handle error from Google
throw new Exception('Error fetching access token: ' . $token['error_description']);
}
$client->setAccessToken($token['access_token']);
// Get user profile information from Google.
$google_oauth = new Google_Service_Oauth2($client);
$google_account_info = $google_oauth->userinfo->get();
$id = $google_account_info->id;
$email = $google_account_info->email;
$name = $google_account_info->name;
$picture = $google_account_info->picture;
// B. Redirect back to the Flutter app with the user data in the URL.
// We use urlencode to ensure data is passed correctly.
$redirectUrl = $appRedirectScheme .
'?status=success' .
'&id=' . urlencode($id) .
'&email=' . urlencode($email) .
'&name=' . urlencode($name) .
'&picture=' . urlencode($picture);
header('Location: ' . $redirectUrl);
exit();
} catch (Exception $e) {
// C. Handle any errors and redirect back to the app with an error status.
$error_message = urlencode($e->getMessage());
header('Location: ' . $appRedirectScheme . '?status=error&message=' . $error_message);
exit();
}
} else {
// D. This is the initial request from the Flutter app.
// Redirect the user to Google's OAuth 2.0 server for authentication.
$authUrl = $client->createAuthUrl();
header('Location: ' . $authUrl);
exit();
}
?>

View File

@@ -1,85 +0,0 @@
<?php
/**
* delete_old_serial_docs.php
* يحذف صور الوثائق الأقدم من مدة محددة (افتراضي 48 ساعة) من private_uploads
* ضع الملف بجانب upload_serial_document.php ليستخدم نفس الشجرة.
*/
date_default_timezone_set('Asia/Damascus');
// === الإعدادات ===
// نفس ما في upload_serial_document.php:
const UPLOAD_ROOT = __DIR__ . "/../../private_uploads";
const ALLOWED_EXTS = ['jpg','png','webp'];
// المدة قبل الحذف (ثواني): افتراضي يومين، ويمكن تمريرها عبر CLI
$ttlSeconds = 2 * 24 * 60 * 60; // 48 ساعة
if (PHP_SAPI === 'cli' && isset($argv[1]) && ctype_digit($argv[1])) {
$ttlSeconds = (int)$argv[1];
}
// ملف لوج اختياري
$logFile = __DIR__ . '/delete_old_serial_docs.log';
$log = @fopen($logFile, 'ab');
// دالة بسيطة للّوج
$logln = function(string $msg) use ($log) {
$line = '[' . date('Y-m-d H:i:s') . '] ' . $msg . PHP_EOL;
if ($log) @fwrite($log, $line);
};
// تحقّق أن مجلد الرفع صحيح وموجود
$root = realpath(UPLOAD_ROOT);
if ($root === false || !is_dir($root)) {
$logln("❌ UPLOAD_ROOT not found: " . UPLOAD_ROOT);
exit(1);
}
$logln("===== Start cleanup in: {$root} | TTL={$ttlSeconds}s =====");
// مُكرّر آمن عبر RecursiveIterator
$it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST
);
$now = time();
$deleted = 0;
$checked = 0;
// اسم الملف المتوقع: driverId__docType.ext
$docTypes = [
'driver_license_front','driver_license_back',
'car_license_front','car_license_back',
];
$docTypesRegex = implode('|', array_map('preg_quote', $docTypes));
foreach ($it as $node) {
if (!$node->isFile()) continue;
$checked++;
$path = $node->getPathname();
$ext = strtolower($node->getExtension());
// فلترة الامتدادات
if (!in_array($ext, ALLOWED_EXTS, true)) continue;
// فلترة اسم الملف (حماية من حذف ملفات أخرى)
$name = $node->getBasename();
if (!preg_match('/^[A-Za-z0-9_-]+__(' . $docTypesRegex . ')\.(jpg|png|webp)$/i', $name)) {
continue;
}
$age = $now - $node->getMTime();
if ($age >= $ttlSeconds) {
if (@unlink($path)) {
$deleted++;
$logln("🗑 Deleted: {$path} | age=" . round($age/3600, 1) . "h");
} else {
$logln("⚠️ Failed to delete: {$path}");
}
}
}
$logln("Done. checked={$checked}, deleted={$deleted}");
if ($log) @fclose($log);

0
backend/auth/syria/driver/driver_details.php Executable file → Normal file
View File

0
backend/auth/syria/driver/drivers_pending_list.php Executable file → Normal file
View File

0
backend/auth/syria/driver/isPhoneVerified.php Executable file → Normal file
View File

0
backend/auth/syria/driver/register_driver_and_car.php Executable file → Normal file
View File

View File

View File

@@ -1,109 +0,0 @@
<?php
require_once __DIR__ . '/../../../connect.php';
//sendWhatsAppDriver.php
error_log("--- [send_otp_driver.php] Started ---");
/**
* فحص البلاك ليست (خاصة بالسائقين)
* - يشفّر الهاتف الخام ويبحث عنه في جدول blacklist_driver
*/
function is_blacklisted_driver(PDO $con, $encryptionHelper, string $phone): bool {
$raw = trim($phone);
$enc_raw = $encryptionHelper->encryptData($raw);
$sql = "SELECT 1 FROM blacklist_driver WHERE phone = :ph LIMIT 1";
$q = $con->prepare($sql);
$q->execute(['ph' => $enc_raw]);
return (bool)$q->fetchColumn();
}
/* 0) استقبل الرقم وتحقق من البلاك ليست */
$receiver = filterRequest("receiver");
if (!$receiver) {
jsonError('Phone number is required.');
error_log("[send_otp_driver.php] Error: phone empty");
exit();
}
if (is_blacklisted_driver($con, $encryptionHelper, $receiver)) {
jsonError('This driver is blacklisted and cannot receive OTP.');
error_log("[send_otp_driver.php] BLOCKED (blacklisted): $receiver");
exit();
}
/* 1) توليد الـ OTP (3 خانات) */
$otp = (string)rand(100, 999);
/* 2) إرسال الرمز عبر بوابة الفلاش كول / واتساب */
$nabehUrl = 'https://otp.intaleqapp.com/api/request-otp.php';
$appKey = getenv('NABEH_OTP_APP_KEY');
$phoneWithPlus = (strpos($receiver, '+') === 0) ? $receiver : '+' . $receiver;
$payload = [
'phone' => $phoneWithPlus,
'device_type' => 'android',
'method' => 'whatsapp',
'code' => $otp
];
$ch = curl_init($nabehUrl);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
"X-App-Key: $appKey"
],
CURLOPT_TIMEOUT => 15,
CURLOPT_CONNECTTIMEOUT => 5
]);
$res = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
error_log("⚠️ [Flash Call OTP Driver] Curl Error: $error");
jsonError('Failed to connect to OTP service');
exit;
}
$decoded = json_decode((string)$res, true);
if ($httpCode !== 200 || !($decoded['success'] ?? false)) {
error_log("❌ [Flash Call OTP Driver] Failed response: Code $httpCode | Body: " . (string)$res);
jsonError($decoded['message'] ?? 'Failed to request verification code');
exit;
}
/* 3) حفظ الـ OTP في قاعدة البيانات */
$receiver_enc = $encryptionHelper->encryptData($receiver);
$otp_enc = $encryptionHelper->encryptData($otp);
$exp = date('Y-m-d H:i:s', strtotime('+5 minutes'));
$now = date('Y-m-d H:i:s');
try {
// حذف أي رموز سابقة لنفس الرقم
$con->prepare("DELETE FROM phone_verification WHERE phone_number = ?")
->execute([$receiver_enc]);
$stmt = $con->prepare("
INSERT INTO phone_verification
(phone_number, token_code, expiration_time, is_verified, created_at)
VALUES (?, ?, ?, 0, ?)
");
$stmt->execute([$receiver_enc, $otp_enc, $exp, $now]);
jsonSuccess(null, 'OTP sent and saved successfully');
error_log("[send_otp_driver.php] OTP saved for driver $receiver");
} catch (PDOException $e) {
error_log("[send_otp_driver.php] DB error: ".$e->getMessage());
jsonError('OTP generated but failed to save to database');
}
?>

View File

@@ -1,96 +0,0 @@
<?php
require_once __DIR__ . '/../../../connect.php';
$phoneNumber = filterRequest("phone_number");
$otp = filterRequest("otp");
$email = $phoneNumber . '@intaleqapp.com';
error_log("📥 [verifyOtp.php] Received phone number: $phoneNumber | OTP: $otp");
if (empty($phoneNumber) || empty($otp)) {
jsonError("Phone number and OTP are required.");
exit();
}
// 🔐 تشفير البيانات
$phoneNumber_encrypted = $encryptionHelper->encryptData($phoneNumber);
$email_encrypted = $encryptionHelper->encryptData($email);
try {
// 🔍 1. التحقق من السجل المخزن في قاعدة البيانات
$stmtSelect = $con->prepare("SELECT * FROM phone_verification WHERE phone_number = ? ORDER BY created_at DESC LIMIT 1");
$stmtSelect->execute([$phoneNumber_encrypted]);
$record = $stmtSelect->fetch(PDO::FETCH_ASSOC);
if (!$record) {
jsonError("Verification session not found. Please request a new code.");
exit();
}
// 🔍 2. فك تشفير ومقارنة الرمز
$decryptedOtp = $encryptionHelper->decryptData($record['token_code']);
if ($decryptedOtp !== $otp) {
jsonError("Invalid verification code.");
exit();
}
// 🔍 3. التحقق من الصلاحية
$now = date('Y-m-d H:i:s');
if ($record['expiration_time'] && $record['expiration_time'] < $now) {
jsonError("Verification code has expired. Please request a new one.");
exit();
}
// 🧹 حذف أي رموز قديمة لنفس الرقم
$con->prepare("DELETE FROM phone_verification WHERE phone_number = ?")
->execute([$phoneNumber_encrypted]);
// 🧾 توليد driverID فريد
$raw = $phoneNumber;
$driverID = substr(md5($raw), 2, 20);
// 🔐 توليد رمز تجريبي (بدون OTP حقيقي لتجنب Null)
$dummyToken = $encryptionHelper->encryptData('AUTO');
// ✅ إدخال سجل تحقق مباشر
$stmt = $con->prepare("
INSERT INTO phone_verification
(phone_number, token_code, email, driverId, expiration_time, is_verified, created_at)
VALUES (?, ?, ?, ?, NULL, 1, ?)
");
$stmt->execute([$phoneNumber_encrypted, $dummyToken, $email_encrypted, $driverID, $now]);
error_log("✅ [verifyOtp.php] Verification record inserted successfully for $phoneNumber");
// 🔍 التحقق إذا السائق موجود مسبقاً
$checkDriverStmt = $con->prepare("SELECT * FROM driver WHERE phone = ?");
$checkDriverStmt->execute([$phoneNumber_encrypted]);
$driver = $checkDriverStmt->fetch(PDO::FETCH_ASSOC);
if ($driver) {
error_log("👤 [verifyOtp.php] Driver already registered. Returning driver info.");
printSuccess([
"message" => "Driver already registered.",
"isRegistered" => true,
"driver" => [
"id" => $driver['id'],
"first_name" => $encryptionHelper->decryptData($driver['first_name']),
"last_name" => $encryptionHelper->decryptData($driver['last_name']),
"email" => $encryptionHelper->decryptData($driver['email']),
"phone" => $phoneNumber
]
]);
} else {
error_log("🆕 [verifyOtp.php] Phone verified. Driver not found.");
printSuccess([
"message" => "Phone number verified successfully.",
"isRegistered" => false,
"driverID" => $driverID
]);
}
} catch (PDOException $e) {
error_log("💥 [verifyOtp.php] PDO ERROR: " . $e->getMessage());
jsonError("Database error: " . $e->getMessage());
}
?>

0
backend/auth/syria/register_passenger.php Executable file → Normal file
View File

View File

@@ -1,72 +0,0 @@
<?php
// File: secure_image.php
// يعرض الملف فقط إذا كان الرابط موقّع وصالح زمنياً.
// يعتمد نفس الثوابت/المسارات في upload_serial_document.php
require_once __DIR__ . '/../../connect.php';
const UPLOAD_ROOT = __DIR__ . "/../../private_uploads";
const SIGN_SECRET = getenv('SECRET_KEY_HMAC'); // نفس المفتاح
// استلام المعطيات من الرابط
$driverId = $_GET['driver_id'] ?? '';
$docType = $_GET['doc_type'] ?? '';
$extShort = $_GET['ext'] ?? '';
$expires = $_GET['expires'] ?? '';
$signature= $_GET['signature'] ?? '';
if ($driverId === '' || $docType === '' || $extShort === '' || $expires === '' || $signature === '') {
http_response_code(400); echo "Missing parameters."; exit;
}
// صلاحية الوقت
if ((int)$expires < time()) {
http_response_code(403); echo "Link expired."; exit;
}
// تحقق من doc_type
$allowedDocTypes = [
'driver_license_front',
'driver_license_back',
'car_license_front',
'car_license_back',
];
if (!in_array($docType, $allowedDocTypes, true)) {
http_response_code(403); echo "Invalid doc_type."; exit;
}
// تحقق من الامتداد
$allowedExts = ['jpg','png','webp'];
if (!in_array($extShort, $allowedExts, true)) {
http_response_code(403); echo "Invalid ext."; exit;
}
// إعادة توليد التوقيع للمقارنة
$driverIdSafe = preg_replace('/[^A-Za-z0-9_\-]/', '_', $driverId);
$message = $driverIdSafe . ':' . $docType . ':' . $extShort . ':' . $expires;
$expected = hash_hmac('sha256', $message, SIGN_SECRET);
if (!hash_equals($expected, $signature)) {
http_response_code(403); echo "Invalid signature."; exit;
}
// بناء المسار
$h = hash('sha1', $driverIdSafe);
$subdir = substr($h, 0, 2) . '/' . substr($h, 2, 2);
$serverName = "{$driverIdSafe}__{$docType}.{$extShort}";
$path = UPLOAD_ROOT . '/' . $subdir . '/' . $serverName;
if (!is_file($path)) {
http_response_code(404); echo "File not found."; exit;
}
// تحديد النوع
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($path) ?: 'application/octet-stream';
header('Content-Type: ' . $mime);
header('Content-Length: ' . filesize($path));
header('X-Content-Type-Options: nosniff');
// (اختياري) اطلب توكن وصول إضافي عبر Authorization للتحكم الأدق.
// مثال: تحقق من $_SERVER['HTTP_AUTHORIZATION'] هنا إن أردت.
readfile($path);

View File

@@ -1,119 +0,0 @@
<?php
$allowRegistration = true;
require_once __DIR__ . '/../../connect.php';
error_log("--- [send_otp_pass.php] Started ---");
/* Helpers */
function normalize_phone($s) { return preg_replace('/\D+/', '', (string)$s); }
/**
* Check blacklist by encrypted phone
*/
function is_blacklisted(PDO $con, $encryptionHelper, string $phone): bool {
$raw = trim($phone);
$norm = normalize_phone($raw);
$enc_raw = $encryptionHelper->encryptData($raw);
$enc_norm = $encryptionHelper->encryptData($norm);
$sql = "SELECT 1
FROM passenger_blacklist
WHERE phone IN (:enc_raw, :enc_norm)
AND (expires_at IS NULL OR expires_at > NOW())
LIMIT 1";
$q = $con->prepare($sql);
$q->execute([
'enc_raw' => $enc_raw,
'enc_norm' => $enc_norm,
]);
return (bool)$q->fetchColumn();
}
/* 0) Get phone number */
$receiver = filterRequest("receiver");
if (!$receiver) {
jsonError('Phone number is required.');
exit();
}
if (is_blacklisted($con, $encryptionHelper, $receiver)) {
jsonError('This phone is blacklisted and cannot receive OTP.');
error_log("[send_otp] BLOCKED (blacklisted): $receiver");
exit();
}
/* 1) Generate OTP (3 digits) */
$otp = (string)rand(100, 999);
/* 2) Send via Flash Call / WhatsApp Gateway */
$nabehUrl = 'https://otp.intaleqapp.com/api/request-otp.php';
$appKey = getenv('NABEH_OTP_APP_KEY');
$phoneWithPlus = (strpos($receiver, '+') === 0) ? $receiver : '+' . $receiver;
$payload = [
'phone' => $phoneWithPlus,
'device_type' => 'android',
'method' => 'whatsapp',
'code' => $otp
];
$ch = curl_init($nabehUrl);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
"X-App-Key: $appKey"
],
CURLOPT_TIMEOUT => 15,
CURLOPT_CONNECTTIMEOUT => 5
]);
$res = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
error_log("⚠️ [Flash Call OTP Passenger] Curl Error: $error");
jsonError('Failed to connect to OTP service');
exit;
}
$decoded = json_decode((string)$res, true);
if ($httpCode !== 200 || !($decoded['success'] ?? false)) {
error_log("❌ [Flash Call OTP Passenger] Failed response: Code $httpCode | Body: " . (string)$res);
jsonError($decoded['message'] ?? 'Failed to request verification code');
exit;
}
/* 3) Save OTP (encrypted) */
$receiver_enc = $encryptionHelper->encryptData($receiver);
$otp_enc = $encryptionHelper->encryptData($otp);
$exp = date('Y-m-d H:i:s', strtotime('+5 minutes'));
$now = date('Y-m-d H:i:s');
try {
$con->prepare("DELETE FROM phone_verification_passenger WHERE phone_number = ?")
->execute([$receiver_enc]);
$stmt = $con->prepare("
INSERT INTO phone_verification_passenger
(phone_number, token, expiration_time, verified, created_at)
VALUES (?, ?, ?, 0, ?)
");
$stmt->execute([$receiver_enc, $otp_enc, $exp, $now]);
jsonSuccess(null, 'OTP sent and saved successfully');
error_log("[send_otp] OTP saved successfully for $receiver");
} catch (PDOException $e) {
error_log("[send_otp] DB error: ".$e->getMessage());
jsonError('OTP generated but failed to save to database');
}

View File

@@ -1,52 +0,0 @@
<?php
require_once __DIR__ . '/../../connect.php';
$receiver = filterRequest("receiver");
if (!$receiver) {
jsonError("رقم الهاتف مفقود");
exit;
}
// توليد تأخير عشوائي بين 45 و 90 ثانية
$delay = rand(45, 90);
sleep($delay);
// رسالة الاستطلاع مع أزرار
$surveyMessage = [
"type" => "buttons",
"header" => [
"type" => "text",
"text" => "استطلاع رأي سريع 🌟"
],
"body" => [
"text" => "هل كانت تجربة التسجيل في تطبيق *سيرو* سهلة بالنسبة لك؟\n\n👇 اضغط أحد الخيارات:"
],
"footer" => [
"text" => "للتواصل: +962 7XXXXXXX - رابط التطبيق: https://intaleq.xyz"
],
"buttons" => [
[
"type" => "reply",
"reply" => [
"id" => "feedback_yes",
"title" => "👍 نعم"
]
],
[
"type" => "reply",
"reply" => [
"id" => "feedback_no",
"title" => "👎 لا"
]
]
]
];
// استدعاء الدالة لإرسال الرسالة
$response = sendWhatsAppFromServer($receiver, $surveyMessage);
if ($response && isset($response["status"]) && $response["status"] === "sent") {
jsonSuccess(null, "تم إرسال استطلاع الرأي بنجاح بعد $delay ثانية.");
} else {
jsonError("فشل في إرسال استطلاع الرأي");
}
?>

0
backend/auth/syria/uploadSyrianDocs.php Executable file → Normal file
View File

View File

@@ -1,114 +0,0 @@
<?php
$allowRegistration = true;
require_once __DIR__ . '/../../connect.php';
// تسجيل بداية الطلب
error_log("[Auth_Debug] Start processing phone verification request.");
$phoneNumber = filterRequest("phone_number");
$otp = filterRequest("otp");
if (!$phoneNumber) {
error_log("[Auth_Error] Phone number is missing in the request.");
jsonError("Phone number is required");
exit();
}
if (!$otp) {
error_log("[Auth_Error] OTP is missing in the request.");
jsonError("OTP is required");
exit();
}
// تسجيل الرقم
error_log("[Auth_Debug] Received phone number (Masked): " . substr($phoneNumber, 0, 7) . "***** | OTP: " . $otp);
// تشفير رقم الهاتف
$phoneNumber_encrypted = $encryptionHelper->encryptData($phoneNumber);
error_log("[Auth_Debug] Phone number encrypted successfully.");
try {
// ✅ 1. التحقق من السجل المخزن في قاعدة البيانات
$stmtSelect = $con->prepare("SELECT * FROM phone_verification_passenger WHERE phone_number = ? ORDER BY created_at DESC LIMIT 1");
$stmtSelect->execute([$phoneNumber_encrypted]);
$record = $stmtSelect->fetch(PDO::FETCH_ASSOC);
if (!$record) {
error_log("[Auth_Error] No verification record found for this number.");
jsonError("Verification session not found. Please request a new code.");
exit();
}
// ✅ 2. فك تشفير ومقارنة الرمز
$decryptedOtp = $encryptionHelper->decryptData($record['token']);
if ($decryptedOtp !== $otp) {
error_log("[Auth_Error] OTP mismatch. Expected: $decryptedOtp, Got: $otp");
jsonError("Invalid verification code.");
exit();
}
// ✅ 3. التحقق من الصلاحية (خلال 5 دقائق)
$now = date('Y-m-d H:i:s');
if ($record['expiration_time'] && $record['expiration_time'] < $now) {
error_log("[Auth_Error] OTP expired.");
jsonError("Verification code has expired. Please request a new one.");
exit();
}
// ✅ 4. حذف السجلات القديمة وإدخال سجل مؤكد (verified = 1)
error_log("[Auth_Step_1] Deleting old verification records for this phone...");
$stmtDelete = $con->prepare("DELETE FROM phone_verification_passenger WHERE phone_number = ?");
$stmtDelete->execute([$phoneNumber_encrypted]);
$stmtInsert = $con->prepare("
INSERT INTO phone_verification_passenger (phone_number, token, expiration_time, verified, created_at)
VALUES (?, NULL, NULL, 1, ?)
");
$stmtInsert->execute([$phoneNumber_encrypted, $now]);
error_log("[Auth_Step_1] Inserted verified record.");
// ✅ 5. فحص هل الراكب موجود مسبقاً
error_log("[Auth_Step_3] Checking if passenger exists in passengers table...");
$checkPassengerStmt = $con->prepare("
SELECT * FROM passengers WHERE phone = ?
");
$checkPassengerStmt->execute([$phoneNumber_encrypted]);
$passenger = $checkPassengerStmt->fetch(PDO::FETCH_ASSOC);
if ($passenger) {
// ✅ الراكب موجود
error_log("[Auth_Result] Passenger Found. ID: " . $passenger['id']);
printSuccess([
"message" => "Passenger already registered.",
"isRegistered" => true,
"passenger" => [
"id" => $passenger['id'],
"first_name" => $encryptionHelper->decryptData($passenger['first_name']),
"last_name" => $encryptionHelper->decryptData($passenger['last_name']),
"email" => $encryptionHelper->decryptData($passenger['email']),
"phone" => $phoneNumber
]
]);
} else {
// ✅ الراكب جديد
error_log("[Auth_Result] Passenger Not Found. Treating as new user.");
printSuccess([
"message" => "Phone number verified successfully.",
"isRegistered" => false
]);
}
} catch (PDOException $e) {
error_log("[Auth_DB_Exception] Error: " . $e->getMessage() . " | File: " . $e->getFile() . " | Line: " . $e->getLine());
jsonError("Database error occurred. Please contact support.");
} catch (Exception $e) {
error_log("[Auth_General_Exception] Error: " . $e->getMessage());
jsonError("An unexpected error occurred.");
}
// تسجيل نهاية الطلب
error_log("[Auth_Debug] Request processing finished.");
?>