<?php
// المسار: /api/supervisor/inspection_requests_new.php

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

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// إعدادات الاتصال بقاعدة البيانات
$host = "localhost";
$dbname = "digitals_autotester_db";
$username = "digitals";
$password = "bassam.bassam";

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $status = isset($_GET['status']) ? $_GET['status'] : 'all';
    $table = isset($_GET['table']) ? $_GET['table'] : 'inspection_requests_new';
    
    // بناء الاستعلام حسب الجدول المطلوب
    if ($table === 'inspection_requested') {
        if ($status === 'pending') {
            $query = "SELECT * FROM inspection_requests_new WHERE status = 'pending' OR status IS NULL ORDER BY id DESC";
        } else {
            $query = "SELECT * FROM inspection_requests_new ORDER BY id DESC";
        }
    } else {
        // جدول inspection_requests_new
        if ($status === 'pending') {
            $query = "SELECT * FROM inspection_requests_new WHERE status = 'pending' ORDER BY id DESC";
        } else {
            $query = "SELECT * FROM inspection_requests_new ORDER BY id DESC";
        }
    }
    
    $stmt = $pdo->prepare($query);
    $stmt->execute();
    $requests = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'data' => $requests,
        'count' => count($requests),
        'table' => $table
    ], JSON_UNESCAPED_UNICODE);
    
} catch(PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
}
?>