<?php
/**
 * API: جلب الطلبات المعلقة للمشرف من inspection_requests_new
 * GET /api/supervisor/get_pending_requests.php?supervisor_id=1
 */

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;

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);
    
    $sql = "SELECT 
                id,
                request_number,
                full_name,
                phone,
                email,
                city,
                car_brand,
                car_model,
                service_type,
                service_name,
                appointment_date,
                appointment_time,
                status,
                created_at
            FROM inspection_requests_new 
            WHERE status IN ('pending', 'assigned')
            AND (status != 'completed' AND status != 'rejected')";
    
    $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";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $requests = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'data' => $requests,
        'total' => count($requests)
    ], JSON_UNESCAPED_UNICODE);
    
} catch(PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>