<?php
/**
 * Geofencing Service
 * خدمة المناطق الجغرافية
 * 
 * @author Almanara GPS Team
 * @version 1.0
 */

require_once __DIR__ . '/config.php';

class GeofencingService {
    private $conn;
    private $userId;
    
    public function __construct($connection, $userId) {
        $this->conn = $connection;
        $this->userId = $userId;
        $this->initializeTables();
    }
    
    /**
     * تهيئة الجداول المطلوبة
     */
    private function initializeTables() {
        try {
            // جدول المناطق الجغرافية
            $this->conn->exec("
                CREATE TABLE IF NOT EXISTS `geofences` (
                    `id` int(11) NOT NULL AUTO_INCREMENT,
                    `user_id` int(11) NOT NULL,
                    `name` varchar(255) NOT NULL,
                    `type` enum('safe_zone', 'restricted_zone', 'custom') DEFAULT 'custom',
                    `latitude` decimal(10,7) NOT NULL,
                    `longitude` decimal(10,7) NOT NULL,
                    `radius` int(11) NOT NULL DEFAULT 100,
                    `alert_on_enter` tinyint(1) DEFAULT 1,
                    `alert_on_exit` tinyint(1) DEFAULT 1,
                    `is_active` tinyint(1) DEFAULT 1,
                    `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
                    PRIMARY KEY (`id`),
                    KEY `idx_user_id` (`user_id`),
                    KEY `idx_is_active` (`is_active`)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
            ");
            
            // جدول سجل دخول/خروج المناطق
            $this->conn->exec("
                CREATE TABLE IF NOT EXISTS `geofence_events` (
                    `id` int(11) NOT NULL AUTO_INCREMENT,
                    `geofence_id` int(11) NOT NULL,
                    `device_id` varchar(255) NOT NULL,
                    `event_type` enum('enter', 'exit') NOT NULL,
                    `latitude` decimal(10,7) NOT NULL,
                    `longitude` decimal(10,7) NOT NULL,
                    `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
                    PRIMARY KEY (`id`),
                    KEY `idx_geofence_id` (`geofence_id`),
                    KEY `idx_device_id` (`device_id`),
                    KEY `idx_timestamp` (`timestamp`)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
            ");
        } catch (PDOException $e) {
            error_log("❌ خطأ في تهيئة جداول Geofencing: " . $e->getMessage());
        }
    }
    
    /**
     * إنشاء منطقة جغرافية جديدة
     */
    public function createGeofence($name, $type, $latitude, $longitude, $radius, $alertOnEnter = true, $alertOnExit = true) {
        try {
            $stmt = $this->conn->prepare("
                INSERT INTO geofences (user_id, name, type, latitude, longitude, radius, alert_on_enter, alert_on_exit)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ");
            
            $stmt->execute([
                $this->userId,
                $name,
                $type,
                $latitude,
                $longitude,
                $radius,
                $alertOnEnter ? 1 : 0,
                $alertOnExit ? 1 : 0
            ]);
            
            return $this->conn->lastInsertId();
        } catch (PDOException $e) {
            error_log("❌ خطأ في إنشاء المنطقة الجغرافية: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * جلب جميع المناطق الجغرافية للمستخدم
     */
    public function getGeofences() {
        try {
            $stmt = $this->conn->prepare("
                SELECT * FROM geofences
                WHERE user_id = ? AND is_active = 1
                ORDER BY name ASC
            ");
            $stmt->execute([$this->userId]);
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("❌ خطأ في جلب المناطق الجغرافية: " . $e->getMessage());
            return [];
        }
    }
    
    /**
     * التحقق من وجود جهاز داخل منطقة جغرافية
     */
    public function checkDeviceInGeofence($deviceId, $latitude, $longitude) {
        $geofences = $this->getGeofences();
        $results = [];
        
        foreach ($geofences as $geofence) {
            $distance = $this->calculateDistance(
                $latitude,
                $longitude,
                $geofence['latitude'],
                $geofence['longitude']
            );
            
            $isInside = $distance <= $geofence['radius'];
            
            // التحقق من تغيير الحالة (دخول/خروج)
            $lastEvent = $this->getLastGeofenceEvent($geofence['id'], $deviceId);
            $lastWasInside = $lastEvent && $lastEvent['event_type'] === 'enter';
            
            if ($isInside && !$lastWasInside) {
                // دخول المنطقة
                $this->recordGeofenceEvent($geofence['id'], $deviceId, 'enter', $latitude, $longitude);
                if ($geofence['alert_on_enter']) {
                    $results[] = [
                        'geofence' => $geofence,
                        'event' => 'enter',
                        'message' => "دخل الجهاز منطقة: {$geofence['name']}"
                    ];
                }
            } elseif (!$isInside && $lastWasInside) {
                // خروج من المنطقة
                $this->recordGeofenceEvent($geofence['id'], $deviceId, 'exit', $latitude, $longitude);
                if ($geofence['alert_on_exit']) {
                    $results[] = [
                        'geofence' => $geofence,
                        'event' => 'exit',
                        'message' => "خرج الجهاز من منطقة: {$geofence['name']}"
                    ];
                }
            }
        }
        
        return $results;
    }
    
    /**
     * تسجيل حدث دخول/خروج
     */
    private function recordGeofenceEvent($geofenceId, $deviceId, $eventType, $latitude, $longitude) {
        try {
            $stmt = $this->conn->prepare("
                INSERT INTO geofence_events (geofence_id, device_id, event_type, latitude, longitude)
                VALUES (?, ?, ?, ?, ?)
            ");
            $stmt->execute([$geofenceId, $deviceId, $eventType, $latitude, $longitude]);
            return true;
        } catch (PDOException $e) {
            error_log("❌ خطأ في تسجيل حدث Geofence: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * جلب آخر حدث للمنطقة والجهاز
     */
    private function getLastGeofenceEvent($geofenceId, $deviceId) {
        try {
            $stmt = $this->conn->prepare("
                SELECT * FROM geofence_events
                WHERE geofence_id = ? AND device_id = ?
                ORDER BY timestamp DESC
                LIMIT 1
            ");
            $stmt->execute([$geofenceId, $deviceId]);
            return $stmt->fetch(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            return null;
        }
    }
    
    /**
     * حساب المسافة بين نقطتين (Haversine formula)
     */
    private function calculateDistance($lat1, $lon1, $lat2, $lon2) {
        $earthRadius = 6371000; // متر
        
        $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; // المسافة بالمتر
    }
    
    /**
     * حذف منطقة جغرافية
     */
    public function deleteGeofence($geofenceId) {
        try {
            $stmt = $this->conn->prepare("
                UPDATE geofences SET is_active = 0 WHERE id = ? AND user_id = ?
            ");
            return $stmt->execute([$geofenceId, $this->userId]);
        } catch (PDOException $e) {
            error_log("❌ خطأ في حذف المنطقة الجغرافية: " . $e->getMessage());
            return false;
        }
    }
}

