<?php
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/db.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
    exit;
}

$code = trim($_GET['code'] ?? '');

if (empty($code)) {
    echo json_encode(['status' => 'error', 'message' => 'No code provided.']);
    exit;
}

// Session-based rate limiting: max 20 checks per 10 minutes per IP
$client_ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
$rate_limit_key = 'sponsor_checks_' . md5($client_ip);

if (!isset($_SESSION)) {
    session_start();
}

if (!isset($_SESSION[$rate_limit_key])) {
    $_SESSION[$rate_limit_key] = ['count' => 0, 'first_attempt' => time()];
}

$rate_data = $_SESSION[$rate_limit_key];
$window_seconds = 600; // 10 minutes
$max_checks = 20;

// Reset window if expired
if ((time() - $rate_data['first_attempt']) > $window_seconds) {
    $_SESSION[$rate_limit_key] = ['count' => 0, 'first_attempt' => time()];
    $rate_data = $_SESSION[$rate_limit_key];
}

if ($rate_data['count'] >= $max_checks) {
    $remaining = $window_seconds - (time() - $rate_data['first_attempt']);
    echo json_encode([
        'status' => 'error',
        'message' => 'Too many verification attempts. Please try again in ' . ceil($remaining / 60) . ' minute(s).'
    ]);
    exit;
}

// Increment attempt count
$_SESSION[$rate_limit_key]['count']++;

try {
    $stmt = $pdo->prepare("SELECT first_name, last_name, username FROM users WHERE employee_code = ? OR username = ? LIMIT 1");
    $stmt->execute([$code, $code]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user) {
        $name = trim(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? ''));
        if (empty($name)) {
            $name = $user['username'];
        }
        echo json_encode([
            'status' => 'success',
            'name' => $name
        ]);
    } else {
        echo json_encode([
            'status' => 'error',
            'message' => 'Not found'
        ]);
    }
} catch (PDOException $e) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Database error.'
    ]);
}
