<?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 = $_GET['inspector_id'] ?? 1;
    $period = $_GET['period'] ?? 'month'; // day, week, month, year
    $year = $_GET['year'] ?? date('Y');
    $month = $_GET['month'] ?? date('m');
    
    // تحديد نطاق التاريخ حسب الفترة
    $dateCondition = "";
    switch ($period) {
        case 'day':
            $dateCondition = "AND DATE(ir.created_at) = CURDATE()";
            break;
        case 'week':
            $dateCondition = "AND YEARWEEK(ir.created_at) = YEARWEEK(CURDATE())";
            break;
        case 'month':
            $dateCondition = "AND MONTH(ir.created_at) = :month AND YEAR(ir.created_at) = :year";
            break;
        case 'year':
            $dateCondition = "AND YEAR(ir.created_at) = :year";
            break;
    }
    
    $params = ['inspector_id' => $inspector_id];
    if ($period === 'month' || $period === 'year') {
        $params['year'] = $year;
        if ($period === 'month') {
            $params['month'] = $month;
        }
    }
    
    // إحصائيات عامة
    $statsQuery = "SELECT 
                    COUNT(*) as total_tasks,
                    COUNT(CASE WHEN ir.status = 'completed' THEN 1 END) as completed_tasks,
                    COUNT(CASE WHEN ir.status = 'in_progress' THEN 1 END) as in_progress_tasks,
                    COUNT(CASE WHEN DATE(ir.created_at) = CURDATE() THEN 1 END) as today_tasks,
                    AVG(CASE WHEN ir.status = 'completed' THEN TIMESTAMPDIFF(MINUTE, ir.started_at, ir.completed_at) END) as avg_completion_time
                   FROM inspection_requests ir
                   WHERE ir.inspector_id = :inspector_id
                   $dateCondition";
    
    $statsStmt = $db->prepare($statsQuery);
    $statsStmt->execute($params);
    $stats = $statsStmt->fetch(PDO::FETCH_ASSOC);
    
    // توزيع نتائج الفحص
    $resultsQuery = "SELECT 
                        cp.status,
                        COUNT(*) as count
                     FROM inspection_checkpoints cp
                     JOIN inspection_requests ir ON cp.request_id = ir.id
                     WHERE ir.inspector_id = :inspector_id
                     $dateCondition
                     GROUP BY cp.status";
    $resultsStmt = $db->prepare($resultsQuery);
    $resultsStmt->execute($params);
    $results = $resultsStmt->fetchAll(PDO::FETCH_ASSOC);
    
    // تفاصيل المهام
    $tasksQuery = "SELECT 
                        ir.id,
                        ir.request_number,
                        ir.status,
                        ir.created_at,
                        ir.completed_at,
                        TIMESTAMPDIFF(MINUTE, ir.started_at, ir.completed_at) as completion_time,
                        CONCAT(u.first_name, ' ', u.last_name) as client_name,
                        cc.brand,
                        cc.model,
                        cc.year,
                        it.name as inspection_type,
                        (SELECT COUNT(*) FROM inspection_checkpoints WHERE request_id = ir.id AND status = 'pass') as pass_count,
                        (SELECT COUNT(*) FROM inspection_checkpoints WHERE request_id = ir.id AND status = 'fail') as fail_count,
                        (SELECT COUNT(*) FROM inspection_checkpoints WHERE request_id = ir.id AND status = 'warning') as warning_count
                    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
                    $dateCondition
                    ORDER BY ir.created_at DESC";
    
    $tasksStmt = $db->prepare($tasksQuery);
    $tasksStmt->execute($params);
    $tasks = $tasksStmt->fetchAll(PDO::FETCH_ASSOC);
    
    // أداء يومي
    $dailyQuery = "SELECT 
                        DATE(ir.created_at) as date,
                        COUNT(*) as tasks_count,
                        COUNT(CASE WHEN ir.status = 'completed' THEN 1 END) as completed_count,
                        AVG(TIMESTAMPDIFF(MINUTE, ir.started_at, ir.completed_at)) as avg_time
                   FROM inspection_requests ir
                   WHERE ir.inspector_id = :inspector_id
                     AND ir.created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
                   GROUP BY DATE(ir.created_at)
                   ORDER BY date DESC";
    
    $dailyStmt = $db->prepare($dailyQuery);
    $dailyStmt->execute(['inspector_id' => $inspector_id]);
    $daily = $dailyStmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'data' => [
            'stats' => $stats,
            'results_distribution' => $results,
            'tasks' => $tasks,
            'daily_performance' => $daily
        ]
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>