<?php
require_once '../includes/session.php';
require_once '../includes/db.php';
require_once '../includes/mailer.php';
require_once '../includes/functions.php'; // for renderLayout

if (session_status() === PHP_SESSION_NONE) session_start();

$user_id     = $_SESSION['user_id'] ?? null;
$transfer_id = $_SESSION['transfer_id'] ?? null;

if (!$user_id || !$transfer_id) {
    header("Location: /user/dashboard.php");
    exit;
}

$conn = db();
$step_error = '';
$show_messages = isset($_GET['show_messages']) && $_GET['show_messages'] == 1;

// =======================
// Get next token for this user
// =======================
$stmt = $conn->prepare("
    SELECT * FROM user_tokens 
    WHERE user_id = ? AND used = 0 
    ORDER BY token_number ASC LIMIT 1
");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$token = $result->fetch_assoc();
$stmt->close();

// If no token exists yet → pending
$token_exists = true;
if (!$token) {
    $token_exists = false;
    $token = [
        'token_number' => 1,
        'reason' => 'Pending approval from admin'
    ];
}

// =======================
// Handle token submission
// =======================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $token_exists) {
    $input_token = trim($_POST['token']);

    if (strtoupper($input_token) === $token['token_value']) {

        // Mark token as used
        $stmt = $conn->prepare("UPDATE user_tokens SET used = 1 WHERE id = ?");
        $stmt->bind_param("i", $token['id']);
        $stmt->execute();
        $stmt->close();

        // Save session data
        $_SESSION['current_step']   = $token['token_number'];
        $_SESSION['current_reason'] = $token['reason'];

        // Check remaining tokens
        $stmt = $conn->prepare("
            SELECT COUNT(*) AS cnt FROM user_tokens
            WHERE user_id = ? AND used = 0
        ");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $remaining = $stmt->get_result()->fetch_assoc()['cnt'];
        $stmt->close();

        $_SESSION['is_last_step'] = ($remaining == 0);

        header("Location: token.php?show_messages=1");
        exit;

    } else {
        $step_error = "Invalid token. Please try again.";
    }
}

// =======================
// Progressive messages
// =======================
$messages = [];
if ($show_messages) {
    $current_step   = $_SESSION['current_step'];
    $current_reason = $_SESSION['current_reason'];
    $is_last_step   = $_SESSION['is_last_step'] ?? false;

    $messages = [
        "Token is being verified and processed...",
        "Thank you for bankug with us...",
        "Token is being verified, please wait...",
        "Applying token validation...",
        "$current_reason verification completed"
    ];
}

// =======================
// Render with system layout
// =======================
ob_start();
?>

<div style="max-width:500px; margin:auto; text-align:center; font-family:Arial; padding:20px;">

<?php if (!$show_messages): ?>

    <h2 style="color: red;">Transaction could not be processed</h2>

    <p style="color:blue; font-weight:bold;">
        <span style="color: green;">
    Reason: <?= htmlspecialchars($token['reason']) ?> Required
</span>

    </p>

    <?php if ($step_error): ?>
        <p style="color:red"><?= htmlspecialchars($step_error) ?></p>
    <?php endif; ?>

    <?php if ($token_exists): ?>
        <form method="POST">
          <br>  <label>Enter Token:</label><br>
            <input type="text" name="token" maxlength="6" required>
            <br><br>
            <button type="submit">Verify</button>
        </form>
    <?php else: ?>
        <p><strong>Status:</strong> Waiting for approval...</p>
        <meta http-equiv="refresh" content="15">
    <?php endif; ?>

<?php else: ?>

    <h2>Processing <?= htmlspecialchars($current_reason) ?>...</h2>

    <p style="color:green; font-weight:bold;">
        Please wait......
    </p>

    <div id="messageBox" style="font-weight:bold; color:blue; margin-top:20px;"></div>

<?php endif; ?>

</div>

<?php if ($show_messages): ?>
<script>
const messages = <?= json_encode($messages) ?>;
const messageBox = document.getElementById('messageBox');
let index = 0;

function showNextMessage() {
    if (index < messages.length) {
        messageBox.textContent = messages[index];
        index++;
        setTimeout(showNextMessage, 5000);
    } else {
        <?php if ($is_last_step): ?>
            window.location.href = "complete_transfer.php?transfer_id=<?= $transfer_id ?>";
        <?php else: ?>
            window.location.href = "token.php";
        <?php endif; ?>
    }
}

window.onload = showNextMessage;
</script>
<?php endif; ?>

<?php
$content = ob_get_clean();
renderLayout("Token Verification", $content, $conn);
?>