<?php
// api/get-requests.php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

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);
} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'خطأ في الاتصال بقاعدة البيانات',
        'error' => $e->getMessage()
    ]);
    exit;
}

// استقبال المعاملات
$status = isset($_GET['status']) ? $_GET['status'] : 'pending';

try {
    // استعلام بسيط بدون LEFT JOIN معقدة
    $query = "SELECT * FROM inspection_requests";
    
    if ($status !== 'all') {
        $query .= " WHERE status = :status";
    }
    
    $query .= " ORDER BY id DESC";
    
    $stmt = $pdo->prepare($query);
    
    if ($status !== 'all') {
        $stmt->bindParam(':status', $status);
    }
    
    $stmt->execute();
    $requests = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'data' => $requests,
        'count' => count($requests)
    ]);
    
} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'خطأ في تنفيذ الاستعلام',
        'error' => $e->getMessage()
    ]);
}
?>