<?php
require 'connection.php';
session_start();

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

$user_id = $_SESSION['user_id'] ?? 0;

if ($_SERVER['REQUEST_METHOD'] === '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)
    if (!preg_match('/^[0-9]+$/', $pin)) {
        echo json_encode(['valid' => false, 'message' => 'Invalid PIN format']);
        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);
        
        // Check if PIN belongs to current user
        if ($pin_data['allcote_user'] == $user_id) {
            // Get package_id from PIN if available
            $package_id = isset($pin_data['package_id']) ? $pin_data['package_id'] : null;
            
            echo json_encode([
                'valid' => true,
                'data' => $pin_data,
                'package_id' => $package_id,
                'message' => 'Valid PIN'
            ]);
        } else {
            echo json_encode([
                'valid' => false,
                'message' => 'This PIN does not belong to you'
            ]);
        }
    } 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'
            ]);
        }
    }
} else {
    echo json_encode(['valid' => false, 'message' => 'Invalid request method']);
}
?>