<?php
/**
 * Analytics & Statistics Service
 * خدمة الإحصائيات والتحليلات
 * 
 * @author Almanara GPS Team
 * @version 1.0
 */

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/firebase_service.php';

class AnalyticsService {
    private $conn;
    private $userId;
    
    public function __construct($connection, $userId) {
        $this->conn = $connection;
        $this->userId = $userId;
    }
    
    /**
     * جلب إحصائيات الجهاز لفترة محددة
     */
    public function getDeviceStatistics($deviceId, $startDate, $endDate) {
        $stats = [
            'total_distance' => 0,
            'total_driving_time' => 0,
            'total_stop_time' => 0,
            'max_speed' => 0,
            'avg_speed' => 0,
            'stops_count' => 0,
            'locations_count' => 0,
            'battery_stats' => [
                'min' => 100,
                'max' => 0,
                'avg' => 0
            ]
        ];
        
        if (defined('USE_FIREBASE') && USE_FIREBASE) {
            $locations = FirebaseService::getLocationsByTimeRange($deviceId, $startDate, $endDate);
        } else {
            $stmt = $this->conn->prepare("
                SELECT * FROM locations
                WHERE device_id = ? AND timestamp BETWEEN ? AND ?
                ORDER BY timestamp ASC
            ");
            $stmt->execute([$deviceId, $startDate, $endDate]);
            $locations = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
        
        if (empty($locations)) {
            return $stats;
        }
        
        $stats['locations_count'] = count($locations);
        $totalSpeed = 0;
        $speedCount = 0;
        $batteries = [];
        $prevLocation = null;
        $isDriving = false;
        $drivingStartTime = null;
        $stopStartTime = null;
        
        foreach ($locations as $location) {
            $speed = isset($location['speed']) ? floatval($location['speed']) : 0;
            $battery = isset($location['battery']) ? intval($location['battery']) : null;
            $timestamp = strtotime($location['timestamp']);
            
            // إحصائيات السرعة
            if ($speed > 0) {
                $stats['max_speed'] = max($stats['max_speed'], $speed);
                $totalSpeed += $speed;
                $speedCount++;
            }
            
            // إحصائيات البطارية
            if ($battery !== null) {
                $batteries[] = $battery;
                $stats['battery_stats']['min'] = min($stats['battery_stats']['min'], $battery);
                $stats['battery_stats']['max'] = max($stats['battery_stats']['max'], $battery);
            }
            
            // حساب المسافة والوقت
            if ($prevLocation) {
                $distance = $this->calculateDistance(
                    $prevLocation['latitude'],
                    $prevLocation['longitude'],
                    $location['latitude'],
                    $location['longitude']
                );
                $stats['total_distance'] += $distance;
                
                $timeDiff = $timestamp - strtotime($prevLocation['timestamp']);
                
                // تحديد حالة القيادة/التوقف
                $currentIsDriving = $speed > 7; // أكثر من 7 كم/س = قيادة
                
                if ($currentIsDriving && !$isDriving) {
                    // بدء القيادة
                    if ($stopStartTime) {
                        $stats['total_stop_time'] += ($timestamp - $stopStartTime);
                        $stopStartTime = null;
                    }
                    $drivingStartTime = $timestamp;
                    $isDriving = true;
                } elseif (!$currentIsDriving && $isDriving) {
                    // بدء التوقف
                    if ($drivingStartTime) {
                        $stats['total_driving_time'] += ($timestamp - $drivingStartTime);
                        $drivingStartTime = null;
                    }
                    $stopStartTime = $timestamp;
                    $isDriving = false;
                    $stats['stops_count']++;
                }
            }
            
            $prevLocation = $location;
        }
        
        // إنهاء الفترات المفتوحة
        if ($isDriving && $drivingStartTime && $prevLocation) {
            $stats['total_driving_time'] += (strtotime($prevLocation['timestamp']) - $drivingStartTime);
        } elseif (!$isDriving && $stopStartTime && $prevLocation) {
            $stats['total_stop_time'] += (strtotime($prevLocation['timestamp']) - $stopStartTime);
        }
        
        // حساب المتوسطات
        if ($speedCount > 0) {
            $stats['avg_speed'] = round($totalSpeed / $speedCount, 2);
        }
        
        if (!empty($batteries)) {
            $stats['battery_stats']['avg'] = round(array_sum($batteries) / count($batteries), 1);
        }
        
        // تحويل المسافة من متر إلى كيلومتر
        $stats['total_distance'] = round($stats['total_distance'] / 1000, 2);
        
        // تحويل الوقت من ثانية إلى دقيقة
        $stats['total_driving_time'] = round($stats['total_driving_time'] / 60, 1);
        $stats['total_stop_time'] = round($stats['total_stop_time'] / 60, 1);
        
        return $stats;
    }
    
    /**
     * جلب إحصائيات يومية
     */
    public function getDailyStatistics($deviceId, $days = 7) {
        $dailyStats = [];
        
        for ($i = $days - 1; $i >= 0; $i--) {
            $date = date('Y-m-d', strtotime("-$i days"));
            $startDate = $date . ' 00:00:00';
            $endDate = $date . ' 23:59:59';
            
            $stats = $this->getDeviceStatistics($deviceId, $startDate, $endDate);
            $dailyStats[$date] = $stats;
        }
        
        return $dailyStats;
    }
    
    /**
     * حساب المسافة بين نقطتين
     */
    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;
    }
}

