<?php
/**
 * API: جلب آخر الطلبات للمشرف
 * GET /api/supervisor/get_recent_requests.php?supervisor_id=1&limit=5
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');

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

$supervisor_id = isset($_GET['supervisor_id']) ? intval($_GET['supervisor_id']) : 0;
$limit = isset($_GET['limit']) ? intval($_GET['limit']) : 5;

if (!$supervisor_id) {
    echo json_encode(['success' => false, 'message' => 'supervisor_id مطلوب']);
    exit();
}

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // جلب مناطق المشرف
    $areaStmt = $pdo->prepare("SELECT city FROM supervisor_areas WHERE supervisor_id = ?");
    $areaStmt->execute([$supervisor_id]);
    $areas = $areaStmt->fetchAll(PDO::FETCH_COLUMN);
    
    // بناء الاستعلام من جدول inspection_requests_new
    $sql = "SELECT 
                id,
                request_number,
                full_name,
                phone,
                email,
                city,
                address,
                car_brand,
                car_model,
                car_year,
                car_color,
                plate_number,
                service_type,
                service_name,
                service_price,
                advance_amount,
                remaining_amount,
                appointment_date,
                appointment_time,
                center_name,
                status,
                payment_status,
                created_at,
                updated_at
            FROM inspection_requests_new 
            WHERE 1=1";
    
    $params = [];
    
    // تصفية حسب مناطق المشرف
    if (!empty($areas)) {
        $placeholders = implode(',', array_fill(0, count($areas), '?'));
        $sql .= " AND city IN ($placeholders)";
        $params = array_merge($params, $areas);
    }
    
    $sql .= " ORDER BY created_at DESC LIMIT ?";
    $params[] = $limit;
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $requests = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'data' => $requests,
        'total' => count($requests),
        'table' => 'inspection_requests_new'
    ], JSON_UNESCAPED_UNICODE);
    
} catch(PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>