<?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';

$database = new Database();
$db = $database->getConnection();

try {
    $stats = [];
    
    // إجمالي الفاحصين
    $query = "SELECT COUNT(*) as total FROM inspectors WHERE role = 'inspector'";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $stats['total_inspectors'] = $stmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0;
    
    // الفحوصات المنتظرة
    $query = "SELECT COUNT(*) as total FROM inspection_requests WHERE status = 'pending' OR status = 'pending_approval'";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $stats['pending_reviews'] = $stmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0;
    
    // طلبات الصلاحيات
    $query = "SELECT COUNT(*) as total FROM permission_requests WHERE status = 'pending'";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $stats['permission_requests'] = $stmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0;
    
    echo json_encode([
        'success' => true,
        'data' => $stats
    ]);
} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}