<?php
/**
 * API: جلب فحوصات اليوم للمشرف من inspection_requests_new
 * GET /api/supervisor/get_today_inspections.php?supervisor_id=1
 */

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

$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);
    
    $today = date('Y-m-d');
    
    $sql = "SELECT 
                id,
                request_number,
                full_name,
                phone,
                car_brand,
                car_model,
                service_type,
                appointment_date,
                appointment_time,
                status
            FROM inspection_requests_new 
            WHERE appointment_date = ?
            AND (status = 'assigned' OR status = 'pending')";
    
    $params = [$today];
    
    if (!empty($areas)) {
        $placeholders = implode(',', array_fill(0, count($areas), '?'));
        $sql .= " AND city IN ($placeholders)";
        $params = array_merge($params, $areas);
    }
    
    $sql .= " ORDER BY appointment_time ASC";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $inspections = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'data' => $inspections,
        'total' => count($inspections)
    ], JSON_UNESCAPED_UNICODE);
    
} catch(PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>