<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
exit(0);
}
include_once 'includes/db.php';
// Function to calculate distance between two points using Haversine formula
function calculateDistance($lat1, $lon1, $lat2, $lon2) {
$earthRadius = 6371; // Earth's radius in kilometers
$dLat = deg2rad($lat2 - $lat1);
$dLon = deg2rad($lon2 - $lon1);
$a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin($dLon/2) * sin($dLon/2);
$c = 2 * atan2(sqrt($a), sqrt(1-$a));
return $earthRadius * $c;
}
// Get user location from request
$input = json_decode(file_get_contents('php://input'), true);
if (!isset($input['lat']) || !isset($input['lng'])) {
echo json_encode([
'success' => false,
'message' => 'الرجاء توفير الإحداثيات'
]);
exit;
}
$userLat = floatval($input['lat']);
$userLng = floatval($input['lng']);
try {
// Get all branches from database
$sql = "SELECT id, name, address, phone, lat, lng FROM branches WHERE lat IS NOT NULL AND lng IS NOT NULL";
$result = $conn->query($sql);
if ($result->num_rows == 0) {
echo json_encode([
'success' => false,
'message' => 'لا توجد فروع متاحة حالياً'
]);
exit;
}
$nearestBranch = null;
$minDistance = PHP_FLOAT_MAX;
// Calculate distance to each branch
while ($branch = $result->fetch_assoc()) {
$distance = calculateDistance(
$userLat,
$userLng,
floatval($branch['lat']),
floatval($branch['lng'])
);
if ($distance < $minDistance) {
$minDistance = $distance;
$nearestBranch = $branch;
$nearestBranch['distance'] = round($distance, 2);
}
}
if ($nearestBranch) {
echo json_encode([
'success' => true,
'branch' => [
'name' => $nearestBranch['name'],
'address' => $nearestBranch['address'],
'phone' => $nearestBranch['phone'],
'distance' => $nearestBranch['distance']
]
]);
} else {
echo json_encode([
'success' => false,
'message' => 'لم يتم العثور على فروع قريبة'
]);
}
} catch (Exception $e) {
echo json_encode([
'success' => false,
'message' => 'حدث خطأ في النظام'
]);
}
$conn->close();
?>