<?php
session_start();
require_once '../includes/db.php';
require_once '../includes/functions.php';
require_once '../includes/session_manager.php';

redirectIfNotLoggedIn();

$userId = $_SESSION['user_id'];
$error = '';
$success = '';
$step = 1;

// Get pending ID
$pending_id = $_GET['id'] ?? 0;
if (!$pending_id) {
    header("Location: pending-withdrawals.php");
    exit();
}

// Fetch pending transaction
$stmt = $pdo->prepare("
    SELECT pt.*, a.account_number, a.balance 
    FROM pending_transactions pt
    JOIN accounts a ON pt.account_id = a.account_id
    WHERE pt.pending_id = ? AND pt.user_id = ? AND pt.transaction_type = 'withdrawal'
");
$stmt->execute([$pending_id, $userId]);
$pending = $stmt->fetch();

if (!$pending) {
    header("Location: pending-withdrawals.php");
    exit();
}

// Determine current step based on database status
if ($pending['sms_step'] == 'step1_sent')
    $step = 1;
elseif ($pending['sms_step'] == 'step2_sent')
    $step = 2;
elseif ($pending['sms_step'] == 'step3_sent')
    $step = 3;
elseif (in_array($pending['sms_step'], ['step1_verified', 'step2_verified', 'step3_verified', 'ready_for_admin'])) {
    $step = 4; // Already verified or waiting for admin
}

// Handle code verification
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['verify_code'])) {
    $entered_code = trim($_POST['code']);
    $current_step = intval($_POST['step']);

    if ($current_step == 1 && $pending['sms_step'] == 'step1_sent') {
        if ($entered_code == $pending['sms_code_1']) {
            $stmt = $pdo->prepare("UPDATE pending_transactions SET sms_step = 'step1_verified', sms1_verified_at = NOW() WHERE pending_id = ?");
            $stmt->execute([$pending_id]);

            $success = "✅ Code 1 verified successfully! Waiting for admin to send Code 2.";
            $pending['sms_step'] = 'step1_verified';
            $step = 2;
        } else {
            $error = "❌ Invalid verification code. Please try again.";
        }
    } elseif ($current_step == 2 && $pending['sms_step'] == 'step2_sent') {
        if ($entered_code == $pending['sms_code_2']) {
            $stmt = $pdo->prepare("UPDATE pending_transactions SET sms_step = 'step2_verified', sms2_verified_at = NOW() WHERE pending_id = ?");
            $stmt->execute([$pending_id]);

            $success = "✅✅ Code 2 verified successfully! Waiting for admin to send Code 3.";
            $pending['sms_step'] = 'step2_verified';
            $step = 3;
        } else {
            $error = "❌ Invalid verification code. Please try again.";
        }
    } elseif ($current_step == 3 && $pending['sms_step'] == 'step3_sent') {
        if ($entered_code == $pending['sms_code_3']) {
            $stmt = $pdo->prepare("UPDATE pending_transactions SET sms_step = 'step3_verified', sms3_verified_at = NOW() WHERE pending_id = ?");
            $stmt->execute([$pending_id]);

            $success = "✅✅✅ All 3 codes verified! Your withdrawal is now pending admin approval.";
            $pending['sms_step'] = 'step3_verified';
            $step = 4;
        } else {
            $error = "❌ Invalid verification code. Please try again.";
        }
    }
}

// Get user info for sidebar
$stmt = $pdo->prepare("SELECT u.*, a.account_number FROM users u JOIN accounts a ON u.user_id = a.user_id WHERE u.user_id = ?");
$stmt->execute([$userId]);
$user = $stmt->fetch();
$profilePic = $user['profile_picture'] ? '../uploads/' . $user['profile_picture'] : '../assets/images/default-avatars.png';
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title>Verify Withdrawal - Oakshire Finance</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,300;400;500;600;700;800&display=swap"
        rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: #f8f9fc;
            color: #212529;
        }

        /* Layout */
        .dashboard-wrapper {
            display: flex;
            min-height: 100vh;
        }

        /* Sidebar */
        .sidebar {
            width: 280px;
            background: white;
            border-right: 1px solid #e9ecef;
            position: fixed;
            left: 0;
            top: 0;
            bottom: 0;
            overflow-y: auto;
            transition: transform 0.3s ease;
            z-index: 100;
        }

        .sidebar-header {
            padding: 24px;
            text-align: center;
            border-bottom: 1px solid #e9ecef;
        }

        .logo {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            text-decoration: none;
        }

        .logo-icon {
            width: 40px;
            height: 40px;
            background: #0a2540;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .logo-icon i {
            color: white;
            font-size: 20px;
        }

        .logo-text {
            font-size: 22px;
            font-weight: 700;
            color: #0a2540;
        }

        .profile-section {
            padding: 24px;
            text-align: center;
            border-bottom: 1px solid #e9ecef;
        }

        .profile-avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            margin: 0 auto 12px;
            background: linear-gradient(135deg, #0a2540, #1a4d8c);
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
        }

        .profile-avatar img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .profile-section h5 {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 4px;
            color: #212529;
        }

        .profile-section p {
            font-size: 12px;
            color: #6c757d;
        }

        .nav-menu {
            padding: 16px;
        }

        .nav-item {
            margin-bottom: 4px;
        }

        .nav-link {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            border-radius: 12px;
            text-decoration: none;
            color: #495057;
            transition: all 0.3s;
            font-weight: 500;
            font-size: 14px;
        }

        .nav-link i {
            width: 20px;
            font-size: 18px;
        }

        .nav-link:hover {
            background: #f1f3f9;
            color: #1a4d8c;
        }

        .nav-link.active {
            background: #0a2540;
            color: white;
        }

        .logout-section {
            padding: 16px;
            border-top: 1px solid #e9ecef;
            margin-top: auto;
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: white;
        }

        .logout-btn {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            border-radius: 12px;
            text-decoration: none;
            color: #dc3545;
            font-weight: 500;
        }

        /* Main Content */
        .main-content {
            flex: 1;
            margin-left: 280px;
            min-height: 100vh;
        }

        .top-header {
            background: white;
            border-bottom: 1px solid #e9ecef;
            padding: 16px 32px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 99;
        }

        .page-title h1 {
            font-size: 24px;
            font-weight: 700;
            color: #212529;
        }

        .user-menu {
            display: flex;
            align-items: center;
            gap: 24px;
        }

        .notification-btn {
            background: none;
            border: none;
            font-size: 20px;
            color: #6c757d;
            cursor: pointer;
        }

        /* Content Area */
        .content-area {
            padding: 32px;
        }

        /* Card */
        .card {
            background: white;
            border-radius: 24px;
            border: 1px solid #e9ecef;
            padding: 32px;
            max-width: 600px;
            margin: 0 auto;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
        }

        /* Step Indicator */
        .step-indicator {
            display: flex;
            justify-content: space-between;
            margin-bottom: 32px;
            position: relative;
        }

        .step {
            text-align: center;
            flex: 1;
            position: relative;
            z-index: 2;
        }

        .step-number {
            width: 40px;
            height: 40px;
            background: #e9ecef;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 8px;
            font-weight: 600;
            color: #6c757d;
            transition: all 0.3s;
        }

        .step.active .step-number {
            background: #0a2540;
            color: white;
            box-shadow: 0 4px 12px rgba(10, 37, 64, 0.2);
        }

        .step.completed .step-number {
            background: #2e7d32;
            color: white;
        }

        .step.completed .step-number i {
            font-size: 18px;
        }

        .step-label {
            font-size: 12px;
            color: #6c757d;
        }

        .step.active .step-label {
            color: #0a2540;
            font-weight: 600;
        }

        /* Info Box */
        .info-box {
            background: #f8f9fc;
            padding: 20px;
            border-radius: 16px;
            margin-bottom: 24px;
            border: 1px solid #e9ecef;
        }

        .info-box p {
            margin: 8px 0;
            font-size: 14px;
        }

        .info-box strong {
            color: #0a2540;
        }

        /* Alert Messages */
        .alert {
            padding: 14px 16px;
            border-radius: 12px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 14px;
        }

        .alert-success {
            background: rgba(46, 125, 50, 0.1);
            border-left: 3px solid #2e7d32;
            color: #2e7d32;
        }

        .alert-danger {
            background: rgba(220, 53, 69, 0.1);
            border-left: 3px solid #dc3545;
            color: #dc3545;
        }

        .alert-info {
            background: rgba(23, 162, 184, 0.1);
            border-left: 3px solid #17a2b8;
            color: #17a2b8;
        }

        /* Form */
        .form-group {
            margin-bottom: 24px;
        }

        .form-group label {
            display: block;
            font-size: 14px;
            font-weight: 600;
            color: #212529;
            margin-bottom: 12px;
        }

        .code-input-wrapper {
            position: relative;
        }

        .code-input-wrapper input {
            width: 100%;
            padding: 18px 20px;
            border: 2px solid #e9ecef;
            border-radius: 16px;
            font-size: 32px;
            text-align: center;
            letter-spacing: 12px;
            font-family: monospace;
            font-weight: 700;
            transition: all 0.3s;
            background: white;
        }

        .code-input-wrapper input:focus {
            border-color: #1a4d8c;
            outline: none;
            box-shadow: 0 0 0 3px rgba(26, 77, 140, 0.1);
        }

        .code-input-wrapper input::placeholder {
            letter-spacing: 0;
            font-size: 14px;
            font-weight: normal;
            color: #adb5bd;
        }

        .btn-primary {
            width: 100%;
            padding: 16px;
            background: #0a2540;
            color: white;
            border: none;
            border-radius: 12px;
            font-weight: 600;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }

        .btn-primary:hover {
            background: #0a1c2f;
            transform: translateY(-2px);
        }

        .btn-secondary {
            display: block;
            width: 100%;
            padding: 14px;
            background: #f8f9fc;
            color: #6c757d;
            text-decoration: none;
            border-radius: 12px;
            font-size: 14px;
            text-align: center;
            margin-top: 16px;
            border: 1px solid #e9ecef;
            transition: all 0.3s;
        }

        .btn-secondary:hover {
            background: #e9ecef;
        }

        /* Helper Text */
        .helper-text {
            text-align: center;
            margin-top: 16px;
            font-size: 13px;
            color: #6c757d;
        }

        .helper-text i {
            margin-right: 6px;
        }

        /* Hamburger Menu */
        .hamburger {
            display: none;
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
        }

        /* Mobile Responsive */
        @media (max-width: 1024px) {
            .sidebar {
                transform: translateX(-100%);
                z-index: 1000;
                transition: transform 0.3s ease;
            }

            .sidebar.mobile-open {
                transform: translateX(0);
            }

            .main-content {
                margin-left: 0;
            }

            .hamburger {
                display: block;
            }
        }

        @media (max-width: 768px) {
            .content-area {
                padding: 20px;
            }

            .top-header {
                padding: 12px 20px;
            }

            .page-title h1 {
                font-size: 20px;
            }

            .card {
                padding: 24px;
                margin: 0;
            }

            .step-number {
                width: 32px;
                height: 32px;
                font-size: 12px;
            }

            .step-label {
                font-size: 10px;
            }

            .code-input-wrapper input {
                padding: 14px 16px;
                font-size: 24px;
                letter-spacing: 6px;
            }

            .info-box p {
                font-size: 12px;
            }
        }

        @media (max-width: 480px) {
            .code-input-wrapper input {
                font-size: 18px;
                letter-spacing: 4px;
                padding: 12px;
            }

            .step-number {
                width: 28px;
                height: 28px;
                font-size: 10px;
            }

            .step-label {
                font-size: 8px;
            }

            .btn-primary {
                padding: 14px;
                font-size: 14px;
            }
        }
    </style>
    <link rel="stylesheet" href="../assets/css/nexus-theme.css">
</head>

<body>
    <div class="dashboard-wrapper">
        <!-- Sidebar -->
        <aside class="sidebar" id="sidebar">
            <div class="sidebar-header">
                <a href="dashboard.php" class="logo">
                    <div class="logo-icon"><i class="fas fa-building-columns"></i></div>
                    <span class="logo-text">Oakshire Finance</span>
                </a>
            </div>
            <div class="profile-section">
                <div class="profile-avatar"><img src="<?= $profilePic ?>" alt="Profile"></div>
                <h5><?= htmlspecialchars($user['full_name']) ?></h5>
                <p><?= htmlspecialchars($user['account_number']) ?></p>
            </div>
            <nav class="nav-menu">
                <div class="nav-item"><a href="dashboard.php" class="nav-link"><i class="fas fa-chart-line"></i>
                        Dashboard</a></div>
                <div class="nav-item"><a href="deposit.php" class="nav-link"><i class="fas fa-arrow-down"></i>
                        Deposit</a></div>
                <div class="nav-item"><a href="withdraw.php" class="nav-link"><i class="fas fa-arrow-up"></i>
                        Withdraw</a></div>
                <div class="nav-item"><a href="transfer.php" class="nav-link"><i class="fas fa-exchange-alt"></i>
                        Transfer</a></div>
                <div class="nav-item"><a href="pending-withdrawals.php" class="nav-link active"><i
                            class="fas fa-clock"></i> Pending Requests</a></div>
                <div class="nav-item"><a href="profile.php" class="nav-link"><i class="fas fa-user-circle"></i>
                        Settings</a></div>
            </nav>
            <div class="logout-section"><a href="../logout.php" class="logout-btn"><i class="fas fa-sign-out-alt"></i>
                    Logout</a></div>
        </aside>

        <!-- Main Content -->
        <main class="main-content">
            <header class="top-header">
                <button class="hamburger" id="hamburger"><i class="fas fa-bars"></i></button>
                <div class="page-title">
                    <h1>Verify Withdrawal</h1>
                </div>
                <div class="user-menu">
                    <button class="notification-btn"><i class="fas fa-bell"></i></button>
                </div>
            </header>

            <div class="content-area">
                <div class="card">
                    <!-- Step Indicator -->
                    <div class="step-indicator">
                        <div class="step <?= $step >= 1 ? ($step > 1 ? 'completed' : 'active') : '' ?>">
                            <div class="step-number"><?= $step > 1 ? '<i class="fas fa-check"></i>' : '1' ?></div>
                            <div class="step-label">Code 1</div>
                        </div>
                        <div class="step <?= $step >= 2 ? ($step > 2 ? 'completed' : 'active') : '' ?>">
                            <div class="step-number"><?= $step > 2 ? '<i class="fas fa-check"></i>' : '2' ?></div>
                            <div class="step-label">Code 2</div>
                        </div>
                        <div class="step <?= $step >= 3 ? ($step > 3 ? 'completed' : 'active') : '' ?>">
                            <div class="step-number"><?= $step > 3 ? '<i class="fas fa-check"></i>' : '3' ?></div>
                            <div class="step-label">Code 3</div>
                        </div>
                        <div class="step <?= $step >= 4 ? 'active' : '' ?>">
                            <div class="step-number">4</div>
                            <div class="step-label">Complete</div>
                        </div>
                    </div>

                    <!-- Error/Success Messages -->
                    <?php if ($error): ?>
                        <div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> <?= $error ?></div>
                    <?php endif; ?>
                    <?php if ($success): ?>
                        <div class="alert alert-success"><i class="fas fa-check-circle"></i> <?= $success ?></div>
                    <?php endif; ?>

                    <!-- Transaction Info -->
                    <div class="info-box">
                        <p><strong>📋 Transaction Details</strong></p>
                        <p>Amount: <strong
                                style="color: #0a2540; font-size: 18px;">$<?= number_format($pending['amount'], 2) ?></strong>
                        </p>
                        <p>Requested: <?= date('M d, Y h:i A', strtotime($pending['created_at'])) ?></p>
                        <p>Status:
                            <?php
                            if ($pending['sms_step'] == 'step1_sent')
                                echo "<span style='color: #17a2b8;'>📧 Code 1 sent to your email</span>";
                            elseif ($pending['sms_step'] == 'step2_sent')
                                echo "<span style='color: #17a2b8;'>📧 Code 2 sent to your email</span>";
                            elseif ($pending['sms_step'] == 'step3_sent')
                                echo "<span style='color: #17a2b8;'>📧 Code 3 sent to your email</span>";
                            elseif ($pending['sms_step'] == 'step1_verified')
                                echo "<span style='color: #2e7d32;'>✓ Code 1 Verified - Waiting for Code 2</span>";
                            elseif ($pending['sms_step'] == 'step2_verified')
                                echo "<span style='color: #2e7d32;'>✓✓ Codes 1-2 Verified - Waiting for Code 3</span>";
                            elseif ($pending['sms_step'] == 'step3_verified')
                                echo "<span style='color: #2e7d32;'>✓✓✓ All Codes Verified - Pending Admin Approval</span>";
                            ?>
                        </p>
                    </div>

                    <!-- Code Input Section -->
                    <?php if ($step == 1 && $pending['sms_step'] == 'step1_sent'): ?>
                        <form method="POST">
                            <input type="hidden" name="step" value="1">
                            <div class="form-group">
                                <label>Enter Verification Code #1</label>
                                <div class="code-input-wrapper">
                                    <input type="text" name="code" maxlength="6" pattern="[0-9]{6}"
                                        placeholder="Enter 6-digit code" required autofocus>
                                </div>
                                <div class="helper-text">
                                    <i class="fas fa-envelope"></i> Check your email for the 6-digit code sent by admin
                                </div>
                            </div>
                            <button type="submit" name="verify_code" class="btn-primary">
                                <i class="fas fa-check-circle"></i> Verify Code 1
                            </button>
                        </form>
                    <?php elseif ($step == 2 && $pending['sms_step'] == 'step2_sent'): ?>
                        <form method="POST">
                            <input type="hidden" name="step" value="2">
                            <div class="form-group">
                                <label>Enter Verification Code #2</label>
                                <div class="code-input-wrapper">
                                    <input type="text" name="code" maxlength="6" pattern="[0-9]{6}"
                                        placeholder="Enter 6-digit code" required autofocus>
                                </div>
                                <div class="helper-text">
                                    <i class="fas fa-envelope"></i> Check your email for the second verification code
                                </div>
                            </div>
                            <button type="submit" name="verify_code" class="btn-primary">
                                <i class="fas fa-check-circle"></i> Verify Code 2
                            </button>
                        </form>
                    <?php elseif ($step == 3 && $pending['sms_step'] == 'step3_sent'): ?>
                        <form method="POST">
                            <input type="hidden" name="step" value="3">
                            <div class="form-group">
                                <label>Enter Verification Code #3</label>
                                <div class="code-input-wrapper">
                                    <input type="text" name="code" maxlength="6" pattern="[0-9]{6}"
                                        placeholder="Enter 6-digit code" required autofocus>
                                </div>
                                <div class="helper-text">
                                    <i class="fas fa-envelope"></i> Check your email for the final verification code
                                </div>
                            </div>
                            <button type="submit" name="verify_code" class="btn-primary">
                                <i class="fas fa-check-circle"></i> Verify Code 3
                            </button>
                        </form>
                    <?php elseif (in_array($pending['sms_step'], ['step3_verified', 'ready_for_admin'])): ?>
                        <div class="alert alert-success">
                            <i class="fas fa-check-circle"></i>
                            <strong>All 3 codes verified!</strong><br>
                            Your withdrawal request has been submitted for admin approval. You will receive an email once
                            processed.
                        </div>
                        <a href="pending-withdrawals.php" class="btn-secondary">
                            <i class="fas fa-arrow-left"></i> Back to Pending Requests
                        </a>
                    <?php else: ?>
                        <div class="alert alert-info">
                            <i class="fas fa-clock"></i>
                            <strong>Waiting for Admin</strong><br>
                            The admin will send verification codes to your email one by one. Please check your email and
                            refresh this page.
                        </div>
                        <a href="verify-withdrawal.php?id=<?= $pending_id ?>" class="btn-secondary">
                            <i class="fas fa-sync-alt"></i> Refresh Status
                        </a>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>

    <script>
        // Mobile sidebar toggle
        const hamburger = document.getElementById('hamburger');
        const sidebar = document.getElementById('sidebar');
        if (hamburger) {
            hamburger.addEventListener('click', () => sidebar.classList.toggle('mobile-open'));
        }

        // Close sidebar when clicking outside on mobile
        document.addEventListener('click', (event) => {
            if (window.innerWidth <= 1024) {
                if (!sidebar.contains(event.target) && !hamburger.contains(event.target) && sidebar.classList.contains('mobile-open')) {
                    sidebar.classList.remove('mobile-open');
                }
            }
        });

        // Auto-refresh every 30 seconds to check for new codes
        setTimeout(function () {
            location.reload();
        }, 30000);

        // Allow only numbers in the code input
        const codeInput = document.querySelector('input[name="code"]');
        if (codeInput) {
            codeInput.addEventListener('input', function (e) {
                this.value = this.value.replace(/[^0-9]/g, '').slice(0, 6);
            });
        }
    </script>
</body>

</html>