<?php
/**
 * جلب ملخص جميع الطلبات
 * api/admin/get_all_requests_summary.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';

validateAdminToken();

try {
    $database = new Database();
    $db = $database->getConnection();
    
    $tables = [
        'permission_requests' => 'طلبات الصلاحيات',
        'registration_requests' => 'طلبات التسجيل',
        'supervisors_requests' => 'طلبات المشرفين',
        'trainees_requests' => 'طلبات المتدربين',
        'job_applications' => 'طلبات التوظيف',
        'inspectors_requests' => 'طلبات الفاحصين',
        'companies_requests' => 'طلبات الشركات',
        'clients_requests' => 'طلبات العملاء',
        'administrative_requests' => 'الطلبات الإدارية'
    ];
    
    $summary = [];
    $totalPending = 0;
    
    foreach ($tables as $table => $label) {
        $stmt = $db->query("
            SELECT 
                COUNT(*) as total,
                SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
                SUM(CASE WHEN status = 'approved' THEN 1 ELSE 0 END) as approved,
                SUM(CASE WHEN status = 'rejected' THEN 1 ELSE 0 END) as rejected
            FROM $table
        ");
        $stats = $stmt->fetch(PDO::FETCH_ASSOC);
        $summary[$table] = [
            'label' => $label,
            'total' => (int)$stats['total'],
            'pending' => (int)$stats['pending'],
            'approved' => (int)$stats['approved'],
            'rejected' => (int)$stats['rejected']
        ];
        $totalPending += (int)$stats['pending'];
    }
    
    // جلب آخر 10 طلبات من جميع الجداول
    $recentRequests = [];
    foreach ($tables as $table => $label) {
        $stmt = $db->query("
            SELECT id, status, created_at, '$table' as source, '$label' as source_label 
            FROM $table 
            ORDER BY created_at DESC 
            LIMIT 5
        ");
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $recentRequests = array_merge($recentRequests, $rows);
    }
    
    // ترتيب حسب التاريخ
    usort($recentRequests, function($a, $b) {
        return strtotime($b['created_at']) - strtotime($a['created_at']);
    });
    $recentRequests = array_slice($recentRequests, 0, 20);
    
    echo json_encode([
        'success' => true,
        'summary' => $summary,
        'total_pending' => $totalPending,
        'recent_requests' => $recentRequests,
        'timestamp' => date('Y-m-d H:i:s')
    ]);
    
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'خطأ في قاعدة البيانات: ' . $e->getMessage()]);
}
?>