<?php
include '../db.php';
include '../auth.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

// Check if request is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
    exit;
}

// Get POST data
$pin = trim($_POST['pin'] ?? '');
$action_type = $_POST['action_type'] ?? 'void'; // Default to void, can be extended for other actions

// Validate PIN
if (empty($pin)) {
    echo json_encode(['status' => 'error', 'message' => 'PIN is required']);
    exit;
}

// Validate PIN format
if (!preg_match('/^\d{4,10}$/', $pin)) {
    echo json_encode(['status' => 'error', 'message' => 'PIN must be 4-10 digits']);
    exit;
}

$user_id = $_SESSION['user_id'];

try {
    // Get user's PIN and PIN requirement settings
    $stmt = $conn->prepare("SELECT pin, pin_required_for_void FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        echo json_encode(['status' => 'error', 'message' => 'User not found']);
        exit;
    }
    
    $user = $result->fetch_assoc();
    
    // Check if PIN is required for this action
    $pin_required = false;
    if ($action_type === 'void') {
        $pin_required = $user['pin_required_for_void'];
    }
    // Future: Add other action types here
    // elseif ($action_type === 'discount') {
    //     $pin_required = $user['pin_required_for_discount'];
    // }
    
    // If PIN is not required for this action, return success
    if (!$pin_required) {
        echo json_encode(['status' => 'success', 'message' => 'PIN not required for this action']);
        exit;
    }
    
    // Check if user has a PIN set
    if (empty($user['pin'])) {
        echo json_encode(['status' => 'error', 'message' => 'No PIN set for this user. Please contact administrator.']);
        exit;
    }
    
    // Verify PIN
    if ($pin === $user['pin']) {
        echo json_encode(['status' => 'success', 'message' => 'PIN verified successfully']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Invalid PIN']);
    }
    
} catch (Exception $e) {
    error_log("PIN verification error: " . $e->getMessage());
    echo json_encode(['status' => 'error', 'message' => 'PIN verification failed. Please try again.']);
}
?>
