<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');

require_once __DIR__ . '/../../database.php';

try {
    $database = new Database();
    $db = $database->getConnection();
    
    if (!$db) {
        throw new Exception("فشل الاتصال بقاعدة البيانات");
    }
    
    // في النظام الفعلي، نأخذ inspector_id من الجلسة
    $inspector_id = $_GET['inspector_id'] ?? 1;
    
    // إحصائيات عامة
    $stats = [];
    
    // إجمالي المهام
    $totalQuery = "SELECT COUNT(*) as total FROM inspection_requests WHERE inspector_id = :inspector_id";
    $totalStmt = $db->prepare($totalQuery);
    $totalStmt->execute(['inspector_id' => $inspector_id]);
    $stats['total_tasks'] = $totalStmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    // المهام المكتملة
    $completedQuery = "SELECT COUNT(*) as completed FROM inspection_requests WHERE inspector_id = :inspector_id AND status = 'completed'";
    $completedStmt = $db->prepare($completedQuery);
    $completedStmt->execute(['inspector_id' => $inspector_id]);
    $stats['completed_tasks'] = $completedStmt->fetch(PDO::FETCH_ASSOC)['completed'];
    
    // المهام قيد التنفيذ
    $progressQuery = "SELECT COUNT(*) as in_progress FROM inspection_requests WHERE inspector_id = :inspector_id AND status IN ('assigned', 'in_progress')";
    $progressStmt = $db->prepare($progressQuery);
    $progressStmt->execute(['inspector_id' => $inspector_id]);
    $stats['in_progress_tasks'] = $progressStmt->fetch(PDO::FETCH_ASSOC)['in_progress'];
    
    // المهام الجديدة
    $newQuery = "SELECT COUNT(*) as new FROM inspection_requests WHERE inspector_id = :inspector_id AND status = 'assigned' AND inspected_at IS NULL";
    $newStmt = $db->prepare($newQuery);
    $newStmt->execute(['inspector_id' => $inspector_id]);
    $stats['new_tasks'] = $newStmt->fetch(PDO::FETCH_ASSOC)['new'];
    
    // متوسط التقييم
    $ratingQuery = "SELECT rating_avg FROM inspectors WHERE id = :inspector_id";
    $ratingStmt = $db->prepare($ratingQuery);
    $ratingStmt->execute(['inspector_id' => $inspector_id]);
    $stats['avg_rating'] = $ratingStmt->fetch(PDO::FETCH_ASSOC)['rating_avg'] ?? 0;
    
    // مهام اليوم
    $todayQuery = "SELECT COUNT(*) as today FROM inspection_requests WHERE inspector_id = :inspector_id AND DATE(created_at) = CURDATE()";
    $todayStmt = $db->prepare($todayQuery);
    $todayStmt->execute(['inspector_id' => $inspector_id]);
    $stats['today_tasks'] = $todayStmt->fetch(PDO::FETCH_ASSOC)['today'];
    
    // مهام هذا الأسبوع
    $weekQuery = "SELECT COUNT(*) as week FROM inspection_requests WHERE inspector_id = :inspector_id AND YEARWEEK(created_at) = YEARWEEK(CURDATE())";
    $weekStmt = $db->prepare($weekQuery);
    $weekStmt->execute(['inspector_id' => $inspector_id]);
    $stats['week_tasks'] = $weekStmt->fetch(PDO::FETCH_ASSOC)['week'];
    
    // مهام هذا الشهر
    $monthQuery = "SELECT COUNT(*) as month FROM inspection_requests WHERE inspector_id = :inspector_id AND MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE())";
    $monthStmt = $db->prepare($monthQuery);
    $monthStmt->execute(['inspector_id' => $inspector_id]);
    $stats['month_tasks'] = $monthStmt->fetch(PDO::FETCH_ASSOC)['month'];
    
    // آخر 5 مهام
    $recentQuery = "SELECT 
                        ir.id,
                        ir.request_number,
                        ir.status,
                        ir.created_at,
                        CONCAT(u.first_name, ' ', u.last_name) as client_name,
                        cc.brand,
                        cc.model,
                        cc.year,
                        cc.plate_number,
                        it.name as inspection_type
                    FROM inspection_requests ir
                    JOIN clients c ON ir.client_id = c.id
                    JOIN users u ON c.user_id = u.id
                    JOIN client_cars cc ON ir.car_id = cc.id
                    JOIN inspection_types it ON ir.inspection_type_id = it.id
                    WHERE ir.inspector_id = :inspector_id
                    ORDER BY ir.created_at DESC
                    LIMIT 5";
    $recentStmt = $db->prepare($recentQuery);
    $recentStmt->execute(['inspector_id' => $inspector_id]);
    $stats['recent_tasks'] = $recentStmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'data' => $stats
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>