<?php
require_once 'connection.php';
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['pin'])) {
    $pin = trim($_POST['pin']);
    

    $ip = $_SERVER['REMOTE_ADDR'];
    $key = 'pin_check_' . md5($ip);
    
    if (!isset($_SESSION[$key])) {
        $_SESSION[$key] = [];
    }
    
    // Clean old attempts (last 1 minute)
    $_SESSION[$key] = array_filter($_SESSION[$key], function($time) {
        return (time() - $time) < 60;
    });
    
    if (count($_SESSION[$key]) > 30) { // Max 30 checks per minute
        echo json_encode(['valid' => false, 'message' => 'Too many requests']);
        exit();
    }
    
    $_SESSION[$key][] = time();
    
    // Validate PIN
    $stmt = $conn->prepare("SELECT * FROM pin WHERE pin_value = ? AND status = '0'");
    $stmt->bind_param("s", $pin);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $pin_data = $result->fetch_assoc();
        echo json_encode([
            'valid' => true,
            'message' => 'Valid PIN'
        ]);
    } else {
        echo json_encode(['valid' => false, 'message' => 'Invalid or already used PIN']);
    }
} else {
    echo json_encode(['valid' => false, 'message' => 'Invalid request']);
}
?>