<?php
/**
 * API: التحقق من حالة طلب التسجيل
 * GET /api/client/endpoints/check_request_status.php?request_number=REG-20260324-XXXXXX
 */

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";

$requestNumber = isset($_GET['request_number']) ? $_GET['request_number'] : null;

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

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $query = "SELECT * FROM registration_requests WHERE request_number = :request_number";
    $stmt = $pdo->prepare($query);
    $stmt->execute([':request_number' => $requestNumber]);
    $request = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$request) {
        echo json_encode(['success' => false, 'message' => 'الطلب غير موجود']);
        exit;
    }
    
    $statusText = '';
    $statusClass = '';
    
    switch ($request['status']) {
        case 'pending':
            $statusText = 'قيد المراجعة';
            $statusClass = 'warning';
            break;
        case 'approved':
            $statusText = 'تم الموافقة';
            $statusClass = 'success';
            break;
        case 'rejected':
            $statusText = 'مرفوض';
            $statusClass = 'danger';
            break;
        default:
            $statusText = $request['status'];
            $statusClass = 'info';
    }
    
    echo json_encode([
        'success' => true,
        'data' => [
            'request_number' => $request['request_number'],
            'full_name' => $request['full_name'],
            'email' => $request['email'],
            'phone' => $request['phone'],
            'role' => $request['role'],
            'status' => $request['status'],
            'status_text' => $statusText,
            'status_class' => $statusClass,
            'created_at' => $request['created_at']
        ]
    ], JSON_UNESCAPED_UNICODE);
    
} catch(PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
}
?>