<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');

require_once __DIR__ . '/../../database.php';

try {
    $database = new Database();
    $db = $database->getConnection();
    
    if (!$db) {
        throw new Exception("فشل الاتصال بقاعدة البيانات");
    }
    
    $status = $_GET['status'] ?? 'pending';
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 50;
    
    $query = "SELECT 
                ir.id,
                ir.request_number,
                ir.status,
                ir.created_at,
                ir.total_price,
                CONCAT(u.first_name, ' ', u.last_name) as client_name,
                u.phone,
                u.email,
                cc.brand,
                cc.model,
                cc.year,
                cc.plate_number,
                it.name as inspection_name,
                it.price as inspection_price
              FROM inspection_requests ir
              JOIN clients c ON ir.client_id = c.id
              JOIN users u ON c.user_id = u.id
              JOIN client_cars cc ON ir.car_id = cc.id
              JOIN inspection_types it ON ir.inspection_type_id = it.id
              WHERE ir.status = :status
              ORDER BY ir.created_at DESC
              LIMIT :limit";
    
    $stmt = $db->prepare($query);
    $stmt->bindValue(':status', $status);
    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->execute();
    
    $requests = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // جلب عدد الطلبات لكل حالة
    $countQuery = "SELECT 
                    COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending_count,
                    COUNT(CASE WHEN status = 'assigned' THEN 1 END) as assigned_count,
                    COUNT(CASE WHEN status = 'in_progress' THEN 1 END) as progress_count,
                    COUNT(CASE WHEN status = 'reviewed' THEN 1 END) as reviewed_count,
                    COUNT(CASE WHEN status = 'completed' THEN 1 END) as completed_count,
                    COUNT(CASE WHEN status = 'cancelled' THEN 1 END) as cancelled_count
                   FROM inspection_requests";
    $countStmt = $db->prepare($countQuery);
    $countStmt->execute();
    $counts = $countStmt->fetch(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'data' => $requests,
        'counts' => $counts
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>