<?php
/**
 * جلب بيانات لوحة تحكم الفاحص
 * endpoint: GET /api/inspector/get_dashboard.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'];

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // جلب المهام الحالية
    $stmt = $db->prepare("
        SELECT 
            ir.*,
            c.brand, c.model, c.year, c.plate_number,
            cl.name as client_name, cl.phone as client_phone
        FROM inspection_requests ir
        LEFT JOIN client_cars c ON ir.car_id = c.id
        LEFT JOIN clients cl ON ir.client_id = cl.id
        WHERE ir.inspector_id = :inspector_id
        ORDER BY ir.created_at DESC
        LIMIT 10
    ");
    $stmt->execute([':inspector_id' => $inspectorId]);
    $tasks = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // جلب عدد الإشعارات غير المقروءة
    $stmt = $db->prepare("
        SELECT COUNT(*) as unread_count 
        FROM notifications 
        WHERE user_id = :user_id AND is_read = 0
    ");
    $stmt->execute([':user_id' => $user['user_id']]);
    $unreadCount = $stmt->fetch(PDO::FETCH_ASSOC)['unread_count'];
    
    // جلب إحصائيات الأداء
    $stmt = $db->prepare("
        SELECT 
            COUNT(*) as total,
            SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed,
            SUM(CASE WHEN status = 'pending_approval' THEN 1 ELSE 0 END) as pending,
            SUM(CASE WHEN status = 'in_progress' THEN 1 ELSE 0 END) as in_progress,
            AVG(accuracy) as avg_accuracy
        FROM inspection_requests 
        WHERE inspector_id = :inspector_id
        AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
    ");
    $stmt->execute([':inspector_id' => $inspectorId]);
    $performance = $stmt->fetch(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'tasks' => $tasks,
        'unread_notifications' => (int)$unreadCount,
        'performance' => [
            'total' => (int)($performance['total'] ?? 0),
            'completed' => (int)($performance['completed'] ?? 0),
            'pending' => (int)($performance['pending'] ?? 0),
            'in_progress' => (int)($performance['in_progress'] ?? 0),
            'accuracy' => round($performance['avg_accuracy'] ?? 0, 1)
        ]
    ]);
    
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'خطأ في قاعدة البيانات: ' . $e->getMessage()]);
}
?>