<?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 = '';

// Get user's account
$stmt = $pdo->prepare("SELECT account_id, account_number, balance FROM accounts WHERE user_id = ?");
$stmt->execute([$userId]);
$account = $stmt->fetch();

if (!$account) {
    die('Account not found.');
}

// List of Major US Banks
$us_banks = [
    'JPMorgan Chase Bank',
    'Bank of America',
    'Wells Fargo',
    'Citibank',
    'U.S. Bank',
    'PNC Bank',
    'Truist Bank',
    'Goldman Sachs Bank',
    'Capital One',
    'TD Bank',
    'HSBC Bank USA',
    'Fifth Third Bank',
    'M&T Bank',
    'KeyBank',
    'Huntington National Bank',
    'Regions Bank',
    'Citizens Bank',
    'First Citizens Bank',
    'Ally Bank',
    'Synchrony Bank',
    'Discover Bank',
    'American Express National Bank',
    'Charles Schwab Bank',
    'State Street Bank',
    'Northern Trust',
    'Bank of New York Mellon',
    'Comerica Bank',
    'Zions Bancorporation',
    'Western Alliance Bank',
    'East West Bank',
    'Bank of Hawaii',
    'First Republic Bank',
    'Signature Bank',
    'Silvergate Bank',
    'Silicon Valley Bank'
];

// Handle withdrawal request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['request_withdrawal'])) {
    $amount = floatval($_POST['amount']);
    $bank_name = trim($_POST['bank_name'] ?? '');
    $account_number = trim($_POST['account_number'] ?? '');
    $account_holder_name = trim($_POST['account_holder_name'] ?? '');
    $routing_number = trim($_POST['routing_number'] ?? '');
    $description = trim($_POST['description'] ?? '');

    if ($amount < 100) {
        $error = "Minimum withdrawal amount is $100.";
    } elseif ($amount > 50000) {
        $error = "Maximum withdrawal amount is $50,000 per transaction.";
    } elseif ($amount > $account['balance']) {
        $error = "Insufficient balance. Your current balance is $" . number_format($account['balance'], 2);
    } elseif (empty($bank_name)) {
        $error = "Please select a bank.";
    } elseif (empty($account_number)) {
        $error = "Please enter the account number.";
    } elseif (empty($account_holder_name)) {
        $error = "Please enter the account holder name.";
    } elseif (!preg_match('/^\d{9}$/', $routing_number)) {
        $error = "Routing number must be 9 digits.";
    } else {
        try {
            // Create pending transaction record with bank details
            $stmt = $pdo->prepare("
                INSERT INTO pending_transactions (
                    user_id, account_id, transaction_type, amount, description, 
                    recipient_bank, recipient_account, recipient_name, routing_number,
                    sms_step, expires_at
                ) VALUES (?, ?, 'withdrawal', ?, ?, ?, ?, ?, ?, 'step1_pending', DATE_ADD(NOW(), INTERVAL 24 HOUR))
            ");
            $stmt->execute([
                $userId,
                $account['account_id'],
                $amount,
                $description,
                $bank_name,
                $account_number,
                $account_holder_name,
                $routing_number
            ]);

            $pending_id = $pdo->lastInsertId();

            $_SESSION['withdrawal_success'] = "Withdrawal request submitted successfully! Please wait for admin to send verification codes.";
            header("Location: pending-withdrawals.php");
            exit();

        } catch (Exception $e) {
            $error = "Failed to submit withdrawal request: " . $e->getMessage();
        }
    }
}

// Get user's pending withdrawals
$pendingWithdrawals = $pdo->prepare("
    SELECT * FROM pending_transactions 
    WHERE user_id = ? AND transaction_type = 'withdrawal' 
    AND sms_step NOT IN ('approved', 'rejected', 'cancelled')
    ORDER BY created_at DESC
");
$pendingWithdrawals->execute([$userId]);
$pendingWithdrawals = $pendingWithdrawals->fetchAll();

// Get user's completed withdrawals
$completedWithdrawals = $pdo->prepare("
    SELECT * FROM pending_transactions 
    WHERE user_id = ? AND transaction_type = 'withdrawal' 
    AND sms_step IN ('approved', 'rejected')
    ORDER BY created_at DESC LIMIT 10
");
$completedWithdrawals->execute([$userId]);
$completedWithdrawals = $completedWithdrawals->fetchAll();

// Get user info for sidebar
$stmt = $pdo->prepare("SELECT u.*, a.account_number, a.balance 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>Withdraw Funds - 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;
        }

        :root {
            --primary-navy: #0a2540;
            --primary-dark: #0a1c2f;
            --primary-blue: #1a4d8c;
            --success-green: #2e7d32;
            --error-red: #dc3545;
            --warning-orange: #f39c12;
            --gray-50: #f8f9fc;
            --gray-100: #f1f3f9;
            --gray-200: #e9ecef;
            --gray-600: #6c757d;
            --gray-700: #495057;
            --white: #ffffff;
            --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.08);
            --shadow-md: 0 4px 12px rgba(0, 0, 0, 0.05);
            --shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.08);
            --transition: all 0.3s ease;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: var(--gray-50);
            color: var(--gray-700);
        }

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

        .sidebar {
            width: 280px;
            background: var(--white);
            border-right: 1px solid var(--gray-200);
            position: fixed;
            left: 0;
            top: 0;
            bottom: 0;
            overflow-y: auto;
            transition: transform 0.3s ease;
            z-index: 100;
        }

        .sidebar-header {
            padding: 24px;
            border-bottom: 1px solid var(--gray-200);
            text-align: center;
        }

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

        .logo-icon {
            width: 40px;
            height: 40px;
            background: var(--primary-navy);
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

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

        .logo-text {
            font-size: 22px;
            font-weight: 700;
            color: var(--primary-navy);
        }

        .profile-section {
            padding: 24px;
            text-align: center;
            border-bottom: 1px solid var(--gray-200);
        }

        .profile-avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            margin: 0 auto 12px;
            background: linear-gradient(135deg, var(--primary-navy), var(--primary-blue));
            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;
        }

        .profile-section p {
            font-size: 12px;
            color: var(--gray-500);
        }

        .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: var(--gray-700);
            transition: var(--transition);
            font-weight: 500;
            font-size: 14px;
        }

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

        .nav-link:hover {
            background: var(--gray-100);
            color: var(--primary-blue);
        }

        .nav-link.active {
            background: var(--primary-navy);
            color: white;
        }

        .logout-section {
            padding: 16px;
            border-top: 1px solid var(--gray-200);
            margin-top: auto;
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: var(--white);
        }

        .logout-btn {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            border-radius: 12px;
            text-decoration: none;
            color: var(--error-red);
            font-weight: 500;
        }

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

        .top-header {
            background: var(--white);
            border-bottom: 1px solid var(--gray-200);
            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: var(--gray-700);
        }

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

        .notification-btn {
            background: none;
            border: none;
            font-size: 20px;
            color: var(--gray-600);
            cursor: pointer;
        }

        .content-area {
            padding: 32px;
        }

        .card {
            background: var(--white);
            border-radius: 20px;
            border: 1px solid var(--gray-200);
            padding: 24px;
            margin-bottom: 24px;
        }

        .card h2 {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .balance-card {
            background: linear-gradient(135deg, var(--primary-navy), var(--primary-dark));
            border-radius: 20px;
            padding: 24px;
            margin-bottom: 24px;
            color: white;
        }

        .balance-amount {
            font-size: 36px;
            font-weight: 700;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            font-size: 13px;
            font-weight: 500;
            color: var(--gray-600);
            margin-bottom: 8px;
        }

        .form-group label .required {
            color: var(--error-red);
            margin-left: 4px;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 12px 16px;
            border: 1.5px solid var(--gray-200);
            border-radius: 12px;
            font-size: 14px;
            transition: var(--transition);
            outline: none;
            font-family: 'Inter', sans-serif;
        }

        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            border-color: var(--primary-blue);
            box-shadow: 0 0 0 3px rgba(26, 77, 140, 0.1);
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        .btn-primary {
            padding: 14px 24px;
            background: var(--primary-navy);
            color: white;
            border: none;
            border-radius: 12px;
            font-weight: 600;
            cursor: pointer;
            transition: var(--transition);
            width: 100%;
            font-size: 16px;
        }

        .btn-primary:hover {
            background: var(--primary-dark);
            transform: translateY(-1px);
        }

        .btn-secondary {
            padding: 8px 16px;
            background: var(--gray-100);
            color: var(--gray-700);
            border: none;
            border-radius: 8px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
            font-size: 13px;
        }

        .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 var(--success-green);
            color: var(--success-green);
        }

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

        .table-container {
            background: var(--white);
            border-radius: 20px;
            border: 1px solid var(--gray-200);
            overflow-x: auto;
            margin-top: 20px;
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
            min-width: 500px;
        }

        .data-table th,
        .data-table td {
            padding: 16px 20px;
            text-align: left;
            border-bottom: 1px solid var(--gray-200);
        }

        .data-table th {
            background: var(--gray-50);
            font-weight: 600;
            font-size: 12px;
            text-transform: uppercase;
            color: var(--gray-600);
        }

        .data-table td {
            font-size: 13px;
        }

        .status-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
        }

        .status-pending {
            background: rgba(243, 156, 18, 0.1);
            color: var(--warning-orange);
        }

        .status-completed {
            background: rgba(46, 125, 50, 0.1);
            color: var(--success-green);
        }

        .status-rejected {
            background: rgba(220, 53, 69, 0.1);
            color: var(--error-red);
        }

        .info-note {
            background: #e8f4f8;
            padding: 12px;
            border-radius: 10px;
            font-size: 12px;
            color: var(--primary-blue);
            margin-top: 16px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .info-note i {
            font-size: 16px;
        }

        .routing-hint {
            font-size: 11px;
            color: var(--gray-500);
            margin-top: 4px;
        }

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

        @media (max-width: 1024px) {
            .sidebar {
                transform: translateX(-100%);
                z-index: 1000;
            }

            .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;
            }

            .balance-amount {
                font-size: 28px;
            }

            .form-row {
                grid-template-columns: 1fr;
                gap: 16px;
            }

            .card {
                padding: 20px;
            }
        }

        @media (max-width: 480px) {
            .balance-amount {
                font-size: 24px;
            }

            .btn-primary {
                padding: 12px;
                font-size: 14px;
            }
        }

        /* Searchable dropdown styles */
        .dropdown-wrapper {
            position: relative;
            width: 100%;
        }

        .dropdown-search {
            width: 100%;
            padding: 12px 16px;
            border: 1.5px solid var(--gray-200);
            border-radius: 12px;
            font-size: 14px;
            cursor: pointer;
            background: white;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .dropdown-search:focus {
            border-color: var(--primary-blue);
            outline: none;
        }

        .dropdown-list {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border: 1px solid var(--gray-200);
            border-radius: 12px;
            max-height: 250px;
            overflow-y: auto;
            z-index: 100;
            display: none;
            margin-top: 4px;
            box-shadow: var(--shadow-md);
        }

        .dropdown-list.show {
            display: block;
        }

        .dropdown-item {
            padding: 10px 16px;
            cursor: pointer;
            transition: background 0.2s;
            font-size: 13px;
        }

        .dropdown-item:hover {
            background: var(--gray-100);
        }

        .dropdown-search-input {
            width: 100%;
            padding: 10px 12px;
            border: none;
            border-bottom: 1px solid var(--gray-200);
            outline: none;
            font-size: 13px;
            margin-bottom: 8px;
        }
    </style>
    <link rel="stylesheet" href="../assets/css/nexus-theme.css">
</head>

<body>
    <div class="dashboard-wrapper">
        <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 active"><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"><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 class="main-content">
            <header class="top-header">
                <button class="hamburger" id="hamburger"><i class="fas fa-bars"></i></button>
                <div class="page-title">
                    <h1>Withdraw Funds</h1>
                </div>
                <div class="user-menu">
                    <button class="notification-btn"><i class="fas fa-bell"></i></button>
                </div>
            </header>

            <div class="content-area">
                <?php if ($error): ?>
                    <div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> <?= $error ?></div>
                <?php endif; ?>
                <?php if (isset($_SESSION['withdrawal_success'])): ?>
                    <div class="alert alert-success"><i class="fas fa-check-circle"></i>
                        <?= $_SESSION['withdrawal_success'] ?></div>
                    <?php unset($_SESSION['withdrawal_success']); ?>
                <?php endif; ?>

                <div class="balance-card">
                    <h3>Available Balance</h3>
                    <div class="balance-amount">$<?= number_format($account['balance'], 2) ?></div>
                </div>

                <div class="card">
                    <h2><i class="fas fa-university"></i> Withdraw to US Bank Account</h2>
                    <form method="POST" id="withdrawForm">
                        <div class="form-row">
                            <div class="form-group">
                                <label>Amount to Withdraw <span class="required">*</span></label>
                                <input type="number" name="amount" step="0.01" min="100" max="50000"
                                    placeholder="Enter amount" required>
                                <small style="color: var(--gray-500); display: block; margin-top: 4px;">Min: $100 | Max:
                                    $50,000 per transaction</small>
                            </div>
                        </div>

                        <div class="form-group">
                            <label>Select US Bank <span class="required">*</span></label>
                            <div class="dropdown-wrapper">
                                <div class="dropdown-search" id="bankDropdownBtn">
                                    <span id="selectedBank">Select a US bank...</span>
                                    <i class="fas fa-chevron-down"></i>
                                </div>
                                <div class="dropdown-list" id="bankDropdownList">
                                    <input type="text" class="dropdown-search-input" id="bankSearchInput"
                                        placeholder="Search bank...">
                                    <div id="bankItems">
                                        <?php foreach ($us_banks as $bank): ?>
                                            <div class="dropdown-item" data-bank="<?= htmlspecialchars($bank) ?>">
                                                <?= htmlspecialchars($bank) ?></div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                                <input type="hidden" name="bank_name" id="bank_name" required>
                            </div>
                        </div>

                        <div class="form-row">
                            <div class="form-group">
                                <label>Account Number <span class="required">*</span></label>
                                <input type="text" name="account_number" placeholder="Enter account number" required>
                            </div>
                            <div class="form-group">
                                <label>Routing Number (ABA) <span class="required">*</span></label>
                                <input type="text" name="routing_number" placeholder="9-digit routing number"
                                    pattern="[0-9]{9}" maxlength="9" required>
                                <div class="routing-hint">Must be 9 digits (e.g., 021000021 for Chase)</div>
                            </div>
                        </div>

                        <div class="form-group">
                            <label>Account Holder Name <span class="required">*</span></label>
                            <input type="text" name="account_holder_name" placeholder="Enter account holder name"
                                required>
                        </div>

                        <div class="form-group">
                            <label>Remark / Description</label>
                            <textarea name="description" rows="3"
                                placeholder="Add a remark or reason for withdrawal..."></textarea>
                        </div>

                        <div class="info-note">
                            <i class="fas fa-info-circle"></i>
                            <span>Withdrawals require 3-step email verification. After submission, admin will send
                                verification codes to your email.</span>
                        </div>

                        <button type="submit" name="request_withdrawal" class="btn-primary">
                            <i class="fas fa-paper-plane"></i> Request Withdrawal
                        </button>
                    </form>
                </div>

                <div class="card">
                    <h2><i class="fas fa-clock"></i> Pending Withdrawal Requests</h2>
                    <?php if (empty($pendingWithdrawals)): ?>
                        <p style="color: var(--gray-500); text-align: center; padding: 20px;">No pending withdrawal requests
                        </p>
                    <?php else: ?>
                        <div class="table-container" style="margin-top: 0;">
                            <table class="data-table">
                                <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>Amount</th>
                                        <th>Bank</th>
                                        <th>Status</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($pendingWithdrawals as $pending): ?>
                                        <tr>
                                            <td><?= date('M d, Y h:i A', strtotime($pending['created_at'])) ?>54d
                                            <td>$<?= number_format($pending['amount'], 2) ?>54d
                                            <td><?= htmlspecialchars($pending['recipient_bank'] ?? 'N/A') ?>54d
                                            <td>
                                                <?php
                                                $status_text = '';
                                                if ($pending['sms_step'] == 'step1_pending')
                                                    $status_text = 'Waiting for Admin';
                                                elseif ($pending['sms_step'] == 'step1_sent')
                                                    $status_text = 'Awaiting Code 1';
                                                elseif ($pending['sms_step'] == 'step1_verified')
                                                    $status_text = 'Step 1 Verified';
                                                elseif ($pending['sms_step'] == 'step2_sent')
                                                    $status_text = 'Awaiting Code 2';
                                                elseif ($pending['sms_step'] == 'step2_verified')
                                                    $status_text = 'Step 2 Verified';
                                                elseif ($pending['sms_step'] == 'step3_sent')
                                                    $status_text = 'Awaiting Code 3';
                                                elseif ($pending['sms_step'] == 'step3_verified')
                                                    $status_text = 'Ready for Approval';
                                                elseif ($pending['sms_step'] == 'ready_for_admin')
                                                    $status_text = 'Pending Admin';
                                                ?>
                                                <span class="status-badge status-pending"><?= $status_text ?></span>
                                                54d
                                            <td><a href="verify-withdrawal.php?id=<?= $pending['pending_id'] ?>"
                                                    class="btn-secondary"><i class="fas fa-arrow-right"></i> Verify</a>54d
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>

                <div class="card">
                    <h2><i class="fas fa-history"></i> Recent Withdrawals</h2>
                    <?php if (empty($completedWithdrawals)): ?>
                        <p style="color: var(--gray-500); text-align: center; padding: 20px;">No withdrawal history</p>
                    <?php else: ?>
                        <div class="table-container" style="margin-top: 0;">
                            <table class="data-table">
                                <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>Amount</th>
                                        <th>Bank</th>
                                        <th>Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($completedWithdrawals as $completed): ?>
                                        <tr>
                                            <td><?= date('M d, Y', strtotime($completed['created_at'])) ?>54d
                                            <td>$<?= number_format($completed['amount'], 2) ?>54d
                                            <td><?= htmlspecialchars($completed['recipient_bank'] ?? 'N/A') ?>54d
                                            <td>
                                                <span
                                                    class="status-badge <?= $completed['sms_step'] == 'approved' ? 'status-completed' : 'status-rejected' ?>">
                                                    <?= ucfirst($completed['sms_step']) ?>
                                                </span>
                                                54d
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?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'));

        // Searchable Bank Dropdown
        const bankDropdownBtn = document.getElementById('bankDropdownBtn');
        const bankDropdownList = document.getElementById('bankDropdownList');
        const bankSearchInput = document.getElementById('bankSearchInput');
        const bankItems = document.getElementById('bankItems');
        const selectedBankSpan = document.getElementById('selectedBank');
        const bankNameInput = document.getElementById('bank_name');

        // Toggle dropdown
        bankDropdownBtn.addEventListener('click', function (e) {
            e.stopPropagation();
            bankDropdownList.classList.toggle('show');
            if (bankDropdownList.classList.contains('show')) {
                bankSearchInput.focus();
            }
        });

        // Search filter
        bankSearchInput.addEventListener('input', function () {
            const searchTerm = this.value.toLowerCase();
            const items = bankItems.querySelectorAll('.dropdown-item');
            items.forEach(item => {
                const bankName = item.getAttribute('data-bank').toLowerCase();
                if (bankName.includes(searchTerm)) {
                    item.style.display = 'block';
                } else {
                    item.style.display = 'none';
                }
            });
        });

        // Select bank
        document.querySelectorAll('.dropdown-item').forEach(item => {
            item.addEventListener('click', function () {
                const bankName = this.getAttribute('data-bank');
                selectedBankSpan.textContent = bankName;
                bankNameInput.value = bankName;
                bankDropdownList.classList.remove('show');
            });
        });

        // Close dropdown when clicking outside
        document.addEventListener('click', function (e) {
            if (!bankDropdownBtn.contains(e.target) && !bankDropdownList.contains(e.target)) {
                bankDropdownList.classList.remove('show');
            }
        });

        // Routing number validation - only allow numbers, enforce 9 digits
        const routingInput = document.querySelector('input[name="routing_number"]');
        if (routingInput) {
            routingInput.addEventListener('input', function () {
                this.value = this.value.replace(/[^0-9]/g, '').slice(0, 9);
                if (this.value.length === 9) {
                    this.style.borderColor = '#2e7d32';
                } else if (this.value.length > 0) {
                    this.style.borderColor = '#dc3545';
                } else {
                    this.style.borderColor = '#e9ecef';
                }
            });
        }

        // Amount validation
        const amountInput = document.querySelector('input[name="amount"]');
        if (amountInput) {
            amountInput.addEventListener('input', function () {
                let value = parseFloat(this.value);
                if (value < 100) {
                    this.setCustomValidity('Minimum withdrawal amount is $100');
                } else if (value > 50000) {
                    this.setCustomValidity('Maximum withdrawal amount is $50,000');
                } else {
                    this.setCustomValidity('');
                }
            });
        }
    </script>
</body>

</html>