<?php
/**
 * جلب بيانات أداء الفاحص
 * endpoint: GET /api/inspector/get_performance.php
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit();
}

require_once '../config/database.php';
require_once 'includes/auth.php';

$user = validateToken();
$inspectorId = $user['inspector_id'];
$period = $_GET['period'] ?? 'month'; // week, month, year

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // تحديد الفترة الزمنية
    $dateCondition = "";
    switch ($period) {
        case 'week':
            $dateCondition = "AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
            break;
        case 'year':
            $dateCondition = "AND created_at >= DATE_SUB(NOW(), INTERVAL 1 YEAR)";
            break;
        default: // month
            $dateCondition = "AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)";
    }
    
    // الإحصائيات العامة
    $stmt = $db->prepare("
        SELECT 
            COUNT(*) as total_tasks,
            SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed_tasks,
            SUM(CASE WHEN status = 'pending_approval' THEN 1 ELSE 0 END) as pending_tasks,
            SUM(CASE WHEN status = 'in_progress' THEN 1 ELSE 0 END) as in_progress_tasks,
            SUM(CASE WHEN status = 'rework' THEN 1 ELSE 0 END) as rework_tasks,
            AVG(accuracy) as avg_accuracy,
            AVG(duration_minutes) as avg_duration
        FROM inspection_requests 
        WHERE inspector_id = :inspector_id
    ");
    $stmt->execute([':inspector_id' => $inspectorId]);
    $stats = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // الأداء الأسبوعي
    $stmt = $db->prepare("
        SELECT 
            DATE(created_at) as date,
            COUNT(*) as tasks_count,
            AVG(accuracy) as daily_accuracy
        FROM inspection_requests 
        WHERE inspector_id = :inspector_id 
            AND status = 'completed'
            AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
        GROUP BY DATE(created_at)
        ORDER BY date ASC
    ");
    $stmt->execute([':inspector_id' => $inspectorId]);
    $weeklyPerformance = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // توزيع أنواع الفحوصات
    $stmt = $db->prepare("
        SELECT 
            inspection_type,
            COUNT(*) as count
        FROM inspection_requests 
        WHERE inspector_id = :inspector_id
        GROUP BY inspection_type
    ");
    $stmt->execute([':inspector_id' => $inspectorId]);
    $inspectionTypes = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // نقاط XP والرتبة
    $stmt = $db->prepare("
        SELECT experience_points, rank 
        FROM inspectors 
        WHERE id = :inspector_id
    ");
    $stmt->execute([':inspector_id' => $inspectorId]);
    $rankData = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // حساب الرتبة التالية
    $currentXP = (int)($rankData['experience_points'] ?? 0);
    $nextRankXP = 500;
    $nextRankName = 'محترف';
    
    if ($currentXP < 200) {
        $nextRankXP = 200;
        $nextRankName = 'متدرب';
    } elseif ($currentXP < 500) {
        $nextRankXP = 500;
        $nextRankName = 'محترف';
    } elseif ($currentXP < 1000) {
        $nextRankXP = 1000;
        $nextRankName = 'متقدم';
    } elseif ($currentXP < 1500) {
        $nextRankXP = 1500;
        $nextRankName = 'خبير';
    } else {
        $nextRankXP = $currentXP;
        $nextRankName = 'أسطورة';
    }
    
    $xpProgress = min(100, round(($currentXP / $nextRankXP) * 100));
    
    echo json_encode([
        'success' => true,
        'stats' => [
            'total_tasks' => (int)($stats['total_tasks'] ?? 0),
            'completed_tasks' => (int)($stats['completed_tasks'] ?? 0),
            'pending_tasks' => (int)($stats['pending_tasks'] ?? 0),
            'in_progress_tasks' => (int)($stats['in_progress_tasks'] ?? 0),
            'rework_tasks' => (int)($stats['rework_tasks'] ?? 0),
            'completion_rate' => $stats['total_tasks'] > 0 
                ? round(($stats['completed_tasks'] / $stats['total_tasks']) * 100, 1) 
                : 0,
            'avg_accuracy' => round($stats['avg_accuracy'] ?? 0, 1),
            'avg_duration' => round($stats['avg_duration'] ?? 0),
            'experience_points' => $currentXP,
            'rank' => $rankData['rank'] ?? 'مبتدئ',
            'next_rank' => $nextRankName,
            'xp_progress' => $xpProgress,
            'xp_to_next' => max(0, $nextRankXP - $currentXP)
        ],
        'weekly_performance' => $weeklyPerformance,
        'inspection_types' => $inspectionTypes
    ]);
    
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'خطأ في قاعدة البيانات: ' . $e->getMessage()]);
}
?>