<?php
// guest_validate_pin.php - For non-logged-in users with Aadhaar validation
require_once 'db/connection.php';

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

// Rate limiting to prevent abuse
session_start();
$ip = $_SERVER['REMOTE_ADDR'];
$time = time();
$limit = 5; // Max attempts per minute
$attempts_key = 'pin_attempts_' . $ip;

// Check rate limit
if (isset($_SESSION[$attempts_key])) {
    $attempts = $_SESSION[$attempts_key];
    if ($attempts['count'] >= $limit && ($time - $attempts['time']) < 60) {
        echo json_encode(['valid' => false, 'message' => 'Too many attempts. Please try again later.']);
        exit();
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $pin = isset($_POST['pin']) ? mysqli_real_escape_string($conn, trim($_POST['pin'])) : '';
    
    if (empty($pin)) {
        echo json_encode(['valid' => false, 'message' => 'PIN is required']);
        exit();
    }
    
    // Validate PIN format (numeric, 4-20 digits - based on your DB which uses bigint)
    if (!preg_match('/^[0-9]{4,20}$/', $pin)) {
        echo json_encode(['valid' => false, 'message' => 'Invalid PIN format. PIN must be numeric.']);
        exit();
    }
    
    // Check if PIN exists and is unused
    $query = mysqli_query($conn, "SELECT * FROM pin WHERE pin_value = '$pin' AND status = '0'");
    
    if (mysqli_num_rows($query) > 0) {
        $pin_data = mysqli_fetch_assoc($query);
        
        // Get package ID from PIN (if available) or determine based on PIN owner
        $package_id = isset($pin_data['package_id']) ? $pin_data['package_id'] : null;
        
        // If package_id is not set in pin table, we can determine based on allcote_user or default
        if (!$package_id) {
            // Default to 2500 (Starter) or 3500 (Pro) based on some logic
            // For now, we'll let the registration form handle package selection
            $package_id = 0; // Will be selected in form
        }
        
        echo json_encode([
            'valid' => true,
            'data' => $pin_data,
            'package_id' => $package_id,
            'message' => 'Valid PIN'
        ]);
        
        // Reset attempts on success
        unset($_SESSION[$attempts_key]);
        
    } else {
        // Check if PIN exists but is used
        $used_check = mysqli_query($conn, "SELECT * FROM pin WHERE pin_value = '$pin' AND status = '1'");
        if (mysqli_num_rows($used_check) > 0) {
            echo json_encode(['valid' => false, 'message' => 'This PIN has already been used']);
        } else {
            echo json_encode(['valid' => false, 'message' => 'Invalid PIN']);
        }
        
        // Update attempt counter
        if (!isset($_SESSION[$attempts_key])) {
            $_SESSION[$attempts_key] = ['count' => 1, 'time' => $time];
        } else {
            $_SESSION[$attempts_key]['count']++;
        }
    }
} else {
    echo json_encode(['valid' => false, 'message' => 'Invalid request method']);
}
?>