<?php
// api/dashboard-stats.php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

$host = 'localhost';
$dbname = 'digitals_autotester_db';
$username = 'digitals';
$password = 'bassam.bassam';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // إحصائيات المستخدمين
    $users = $pdo->query("
        SELECT 
            COUNT(*) as total,
            SUM(role = 'admin') as admins,
            SUM(role = 'supervisor') as supervisors,
            SUM(role = 'inspector') as inspectors,
            SUM(role = 'client') as clients
        FROM users
    ")->fetch();
    
    // إحصائيات الفحوصات
    $inspections = $pdo->query("
        SELECT 
            COUNT(*) as total,
            SUM(status = 'pending') as pending,
            SUM(status = 'in_progress' OR status = 'assigned') as in_progress,
            SUM(status = 'completed') as completed,
            SUM(status = 'cancelled' OR status = 'rejected') as cancelled,
            SUM(DATE(created_at) = CURDATE()) as today,
            SUM(created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)) as week,
            SUM(created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)) as month,
            COALESCE(SUM(total_amount), 0) as revenue
        FROM inspection_requests
    ")->fetch();
    
    // مواعيد اليوم
    $appointments = $pdo->query("
        SELECT COUNT(*) as total 
        FROM inspection_requests 
        WHERE DATE(scheduled_date) = CURDATE()
    ")->fetch();
    
    echo json_encode([
        'success' => true,
        'data' => [
            'totalUsers' => (int)$users['total'],
            'totalAdmins' => (int)$users['admins'],
            'totalSupervisors' => (int)$users['supervisors'],
            'totalInspectors' => (int)$users['inspectors'],
            'totalClients' => (int)$users['clients'],
            'totalInspections' => (int)$inspections['total'],
            'pendingInspections' => (int)$inspections['pending'],
            'inProgressInspections' => (int)$inspections['in_progress'],
            'completedInspections' => (int)$inspections['completed'],
            'cancelledInspections' => (int)$inspections['cancelled'],
            'todayInspections' => (int)$inspections['today'],
            'weekInspections' => (int)$inspections['week'],
            'monthInspections' => (int)$inspections['month'],
            'totalRevenue' => (float)$inspections['revenue'],
            'todayAppointments' => (int)$appointments['total']
        ]
    ]);
    
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>