<?php
// Ensure no output before this
session_start();
include_once 'config/database.php';
include_once 'includes/functions.php';

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

// Enable error logging but don't display to users
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

try {
    // Debug session variables
    error_log("PIN verification - Session variables: " . print_r($_SESSION, true));

    // Check if user is logged in and at PIN step
    if (!isset($_SESSION['user_id'])) {
        throw new Exception("User not logged in");
    }
    
    if (!isset($_SESSION['auth_step']) || $_SESSION['auth_step'] !== 'pin') {
        throw new Exception("Invalid authentication step");
    }

    $database = new Database();
    $db = $database->getConnection();

    // Get JSON input
    $json = file_get_contents('php://input');
    $input = json_decode($json, true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception("Invalid JSON input");
    }

    $pin = $input['pin'] ?? '';

    if (empty($pin)) {
        throw new Exception("PIN is required");
    }

    // Get user data
    $stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        throw new Exception("User not found");
    }

    // Verify PIN
    if (!password_verify($pin, $user['pin'])) {
        error_log("PIN verification failed for user ID: " . $_SESSION['user_id']);
        throw new Exception("Invalid PIN");
    }

    // PIN is correct, complete authentication
    $_SESSION['auth_step'] = 'complete';
    $_SESSION['authenticated'] = true;
    $_SESSION['last_activity'] = time();

    error_log("PIN verification successful for user ID: " . $_SESSION['user_id']);

    echo json_encode([
        'success' => true,
        'message' => 'PIN verified successfully',
        'redirect' => 'customer/dashboard.php'
    ]);
    exit;

} catch (Exception $e) {
    error_log("PIN verification error: " . $e->getMessage());
    http_response_code(400); // Bad Request
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
    exit;
}
