<?php
/**
 * CUSTOMER DASHBOARD PAGE
 * File: customer/index.php
 * UPDATED WITH NEW WALLET SYSTEM
 */

require_once '../app/Core/init.php';

// Require customer authentication
Auth::requireCustomer();

// Initialize models
$customerModel = new Customer();
$walletModel = new Wallet();
$favouriteModel = new Favourite();
$walletTransactionModel = new WalletTransaction();

// Get current user ID
$user_id = Auth::id();

// Get customer data
$customer_data = $customerModel->findByUserId($user_id);

if (!$customer_data) {
    flash('error', 'Customer profile not found.', 'danger');
    redirect('profile.php');
}

$customer_id = $customer_data['id'];
$db = Database::getInstance();



// Get customer wallet
// $wallet = $db->fetch("SELECT * FROM wallets WHERE user_id = ?", [Auth::id()]);
// if (!$wallet) {
//     // Create wallet if doesn't exist
//     $db->execute("INSERT INTO wallets (user_id, user_type) VALUES (?, 'customer')", [Auth::id()]);
//     $wallet = $db->fetch("SELECT * FROM wallets WHERE user_id = ?", [Auth::id()]);
// }


// Get wallet
$wallet = $db->fetch("SELECT * FROM wallets WHERE user_id = ?", [Auth::id()]);
if (!$wallet) {
    $db->execute("INSERT INTO wallets (user_id, user_type) VALUES (?, 'customer')", [Auth::id()]);
    $wallet = $db->fetch("SELECT * FROM wallets WHERE user_id = ?", [Auth::id()]);
}



// Get wallet
$wallet = $db->fetch("SELECT * FROM wallets WHERE user_id = ?", [Auth::id()]);
if (!$wallet) {
    $db->execute("INSERT INTO wallets (user_id, user_type) VALUES (?, 'customer')", [Auth::id()]);
    $wallet = $db->fetch("SELECT * FROM wallets WHERE user_id = ?", [Auth::id()]);
}

// Calculate CORRECT total withdrawn from APPROVED withdrawals
$withdrawn_result = $db->fetch("
    SELECT COALESCE(SUM(amount), 0) as total
    FROM withdrawal_requests
    WHERE user_id = ? AND status IN ('approved', 'paid')
", [$user_id]);

// Set total_withdrawn
$wallet['total_withdrawn'] = 0;
if ($withdrawn_result && isset($withdrawn_result['total'])) {
    $wallet['total_withdrawn'] = floatval($withdrawn_result['total']);
}

// Alternative: Update the wallets table total_withdrawn (RECOMMENDED)
// This keeps the wallet table in sync
if ($wallet['total_withdrawn'] != $withdrawn_result['total']) {
    $db->execute("
        UPDATE wallets 
        SET total_withdrawn = ?
        WHERE id = ?
    ", [floatval($withdrawn_result['total']), $wallet['id']]);
    
    $wallet['total_withdrawn'] = floatval($withdrawn_result['total']);
}

// Get pending withdrawals
$pending_withdrawals = $db->fetchAll("
    SELECT * FROM withdrawal_requests
    WHERE user_id = ? AND status = 'pending'
    ORDER BY created_at DESC
    LIMIT 5
", [$user_id]);

$pending_withdrawal_total = $db->fetch("
    SELECT COALESCE(SUM(amount), 0) as total
    FROM withdrawal_requests
    WHERE user_id = ? AND status = 'pending'
", [$user_id]);


// Get customer ID
$customer = $db->fetch("SELECT id FROM customers WHERE user_id = ?", [Auth::id()]);
$customer_id = isset($customer['id']) ? $customer['id'] : 0;

// Get total spent
$spent = $db->fetch("
    SELECT COALESCE(SUM(amount), 0) as total 
    FROM order_payment_breakdown 
    WHERE customer_id = ? AND type != 'security_deposit' AND status NOT IN ('refunded', 'cancelled')
", [$customer_id]);

if (!$spent || !is_array($spent)) {
    $spent = ['total' => 0];
}


// $today_date = date('Y-m-d');

// Get order statistics
$stats_sql = "SELECT 
              COUNT(*) as total_orders,
              SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_orders,
              SUM(CASE WHEN CURDATE() BETWEEN start_date AND end_date 
                       AND status NOT IN ('cancelled', 'completed', 'returned', 'pending') 
                  THEN 1 ELSE 0 END) as ongoing_orders,
              SUM(CASE WHEN status = 'completed' OR status = 'returned' THEN 1 ELSE 0 END) as completed_orders,
              SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) as cancelled_orders,
              SUM(CASE WHEN start_date > CURDATE() 
                       AND status NOT IN ('cancelled', 'completed', 'returned') 
                  THEN 1 ELSE 0 END) as future_orders,
              SUM(CASE WHEN payment_status = 'paid' THEN total_amount ELSE 0 END) as total_spent
              FROM orders 
              WHERE customer_id = ?";
              
$stats = $db->fetch($stats_sql, [$customer_id]);

// Get wallet statistics
$wallet_stats = WalletHelper::getDashboardStats($user_id);

// Get recent orders
$recent_orders_sql = "SELECT o.*, 
                      i.title as item_title,
                      i.main_image as item_image,
                      v.business_name as vendor_name
                      FROM orders o
                      LEFT JOIN items i ON o.item_id = i.id
                      LEFT JOIN vendors v ON o.vendor_id = v.id
                      WHERE o.customer_id = ?
                      ORDER BY o.created_at DESC
                      LIMIT 5";
$recent_orders = $db->fetchAll($recent_orders_sql, [$customer_id]);

if (!is_array($recent_orders)) {
    $recent_orders = [];
}

// Get recent wallet transactions
$recent_transactions = $walletTransactionModel->getByUserId($user_id, 5);

if (!is_array($recent_transactions)) {
    $recent_transactions = [];
}

// Get favourites count
$favourites_count = $favouriteModel->countByCustomer($customer_id);

// Get pending withdrawal requests (NULL SAFE)
$pending_withdrawals = $db->fetchAll("
    SELECT * FROM withdrawal_requests
    WHERE user_id = ? AND status = 'pending'
    ORDER BY created_at DESC
    LIMIT 5
", [$user_id]);

if (!is_array($pending_withdrawals)) {
    $pending_withdrawals = [];
}

// Calculate total pending amount (NULL SAFE)
$pending_withdrawal_total = $db->fetch("
    SELECT COALESCE(SUM(amount), 0) as total
    FROM withdrawal_requests
    WHERE user_id = ? AND status = 'pending'
", [$user_id]);

if (!$pending_withdrawal_total || !is_array($pending_withdrawal_total)) {
    $pending_withdrawal_total = ['total' => 0];
}

$page_title = "Home Dashboard";
$active_menu = "dashboard";

include '../templates/layouts/customer/head.php';
?>

<body class="fixed sidebar-mini">
    <div class="wrapper">
        <!-- Sidebar -->
        <nav class="sidebar">
            <div class="sidebar-header">
                <?php include '../templates/layouts/customer/navbar.php'; ?>
            </div>
        </nav>

        

        <!-- Page Content -->
        <div class="content-wrapper">

            <div class="main-content">
                <?php include '../templates/layouts/customer/header.php'; ?>
                
                <!-- Page Header -->
                <div class="page-header">
                    <div class="page-title">
                        <h1>Dashboard</h1>
                        <ul class="breadcrumb">
                            <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                            <li class="breadcrumb-item active">Dashboard</li>
                        </ul>
                    </div>
                </div>

<div class="container-fluid">
    <div class="row mb-4">
        <div class="col-12">
            <h1 class="h3 mb-0">Welcome back, <?php echo htmlspecialchars($customer_data['first_name']); ?>!</h1>
        </div>
    </div>


    <div class="row mb-4">
        <!-- Card 1: Available Balance - WITH WITHDRAW BUTTON -->
        <div class="col-md-3">
            <div class="card bg-success text-white">
                <div class="card-body">
                    <h6 class="mb-2">Available Balance</h6>
                    <h2 class="mb-0">₦<?php echo number_format($wallet['balance'], 2); ?></h2>
                    <small>Withdrawable</small>
                    <?php if (!empty($pending_withdrawals)): ?>
                        <!-- Show pending info -->
                        <div class="alert alert-warning text-dark mt-3 mb-0 p-2">
                            <small>
                                <i class="fas fa-clock"></i> 
                                <strong>₦<?php echo number_format($pending_withdrawal_total['total'], 2); ?></strong> pending
                            </small>
                        </div>
                    <?php else: ?>
                        <!-- Show withdraw button -->
                        <button class="btn btn-light btn-sm mt-2 w-100" 
                                onclick="openWithdrawModal()"
                                <?php if ($wallet['balance'] < 5000): ?>disabled<?php endif; ?>>
                            <i class="fas fa-money-bill-wave"></i> Withdraw Funds
                        </button>
                        <?php if ($wallet['balance'] < 5000): ?>
                            <small class="d-block mt-1" style="font-size: 0.7rem;">Minimum: ₦5000</small>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Card 2: Onhold Security -->
        <div class="col-md-3">
            <div class="card bg-warning text-white">
                <div class="card-body">
                    <h6 class="mb-2">Onhold Security</h6>
                    <h2 class="mb-0">₦<?php echo number_format($wallet['security_onhold'], 2); ?></h2>
                    <small>Active orders</small>
                </div>
            </div>
        </div>

        <!-- Card 3: Total Spent -->
        <div class="col-md-3">
            <div class="card">
                <div class="card-body">
                    <h6 class="text-muted mb-2">Total Spent</h6>
                    <h3 class="mb-0">₦<?php echo number_format($spent['total'], 2); ?></h3>
                    <small class="text-muted">Lifetime</small>
                </div>
            </div>
        </div>

        <!-- Card 4: Total Withdrawn -->
        <div class="col-md-3">
            <div class="card">
                <div class="card-body">
                    <h6 class="text-muted mb-2">Total Withdrawn</h6>
                    <h3 class="mb-0">₦<?php echo number_format($wallet['total_withdrawn'], 2); ?></h3>
                    <small class="text-muted">All time</small>
                </div>
            </div>
        </div>
        
    </div>



    <!-- Orders Statistics -->
    <div class="row mb-4">
        <div class="col-md-2">
            <div class="card">
                <div class="card-body text-center">
                    <h3 class="text-primary"><?php echo $stats['total_orders'] ?? 0; ?></h3>
                    <p class="text-muted mb-0">Total Orders</p>
                </div>
            </div>
        </div>

        <div class="col-md-2">
            <div class="card">
                <div class="card-body text-center">
                    <h3 class="text-warning"><?php echo $stats['pending_orders'] ?? 0; ?></h3>
                    <p class="text-muted mb-0">Pending Orders</p>
                </div>
            </div>
        </div>

        <div class="col-md-2">
            <div class="card">
                <div class="card-body text-center">
                    <h3 class="text-warning"><?php echo $stats['cancelled_orders'] ?? 0; ?></h3>
                    <p class="text-muted mb-0">Cancelled Orders</p>
                </div>
            </div>
        </div>

        <div class="col-md-2">
            <div class="card">
                <div class="card-body text-center">
                    <h3 class="text-warning"><?php echo $stats['future_orders'] ?? 0; ?></h3>
                    <p class="text-muted mb-0">Future Orders</p>
                </div>
            </div>
        </div>

        <div class="col-md-2">
            <div class="card">
                <div class="card-body text-center">
                    <h3 class="text-info"><?php echo $stats['ongoing_orders'] ?? 0; ?></h3>
                    <p class="text-muted mb-0">Ongoing Rentals</p>
                </div>
            </div>
        </div>

        <div class="col-md-2">
            <div class="card">
                <div class="card-body text-center">
                    <h3 class="text-success"><?php echo $stats['completed_orders'] ?? 0; ?></h3>
                    <p class="text-muted mb-0">Completed</p>
                </div>
            </div>
        </div>
    </div>

    <?php if (!empty($pending_withdrawals)): ?>
    <!-- Pending Withdrawals Alert Section -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card border-warning shadow-sm">
                <div class="card-header" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                    <div class="d-flex justify-content-between align-items-center">
                        <h5 class="mb-0 text-white">
                            <i class="fas fa-clock"></i> Pending Withdrawal Requests
                        </h5>
                        <span class="badge bg-white text-danger">
                            <?php echo count($pending_withdrawals); ?> Pending
                        </span>
                    </div>
                </div>
                <div class="card-body">
                    <!-- Info Alert -->
                    <div class="alert alert-info d-flex align-items-center mb-4">
                        <i class="fas fa-info-circle fa-2x me-3"></i>
                        <div>
                            <strong>Total Pending:</strong> 
                            ₦<?php echo number_format($pending_withdrawal_total['total'], 2); ?><br>
                            <small>Your withdrawal request is being reviewed. You'll be notified once processed.</small>
                        </div>
                    </div>
                    
                    <!-- Pending Withdrawals Table -->
                    <div class="table-responsive">
                        <table class="table table-hover align-middle">
                            <thead class="table-light">
                                <tr>
                                    <th>Date Requested</th>
                                    <th>Amount</th>
                                    <th>Bank Details</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($pending_withdrawals as $wd): ?>
                                    <tr>
                                        <td>
                                            <strong><?php echo date('M d, Y', strtotime($wd['created_at'])); ?></strong><br>
                                            <small class="text-muted"><?php echo date('h:i A', strtotime($wd['created_at'])); ?></small>
                                        </td>
                                        <td>
                                            <h5 class="mb-0 text-primary fw-bold">
                                                ₦<?php echo number_format($wd['amount'], 2); ?>
                                            </h5>
                                        </td>
                                        <td>
                                            <strong><?php echo htmlspecialchars($wd['bank_name']); ?></strong><br>
                                            <small class="text-muted">
                                                <?php echo htmlspecialchars($wd['account_number']); ?> - 
                                                <?php echo htmlspecialchars($wd['account_name']); ?>
                                            </small>
                                        </td>
                                        <td>
                                            <span class="badge bg-warning text-dark fs-6">
                                                <i class="fas fa-clock"></i> Awaiting Approval
                                            </span>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- View All Link -->
                    <div class="text-center mt-3">
                        <a href="withdrawals.php" class="btn btn-primary">
                            <i class="fas fa-list"></i> View All Withdrawal History
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <div class="row">
        <!-- Recent Orders -->
        <div class="col-md-8">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Recent Orders</h5>
                    <a href="orders.php" class="btn btn-sm btn-primary">View All</a>
                </div>
                <div class="card-body">
                    <?php if (empty($recent_orders)): ?>
                        <div class="text-center py-5">
                            <i class="fas fa-shopping-cart fa-3x text-muted mb-3"></i>
                            <p class="text-muted">No orders yet. Start renting!</p>
                            <a href="../items.php" class="btn btn-primary">Browse Items</a>
                        </div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>Order #/Item</th>
                                        <th>Vendor</th>
                                        <th>Amount</th>
                                        <th>Status</th>
                                        <th>Date</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($recent_orders as $order): ?>
                                        <tr>
                                            <td>
                                                <a href="order-details.php?id=<?php echo $order['id']; ?>">
                                                    <?php echo htmlspecialchars($order['order_number']); ?><br>
                                                </a>
                                                <div class="d-flex align-items-center">
                                                    <img src="<?= upload('items/' . $order['item_image']) ?>" 
                                                        style="width: 70px; object-fit: cover; border-radius: 5px;" 
                                                        class="me-2">
                                                    <span><?= htmlspecialchars($order['item_title']) ?></span>
                                                </div>
                                            </td>
                                            <td><?php echo htmlspecialchars($order['vendor_name']); ?></td>
                                            <td><?php echo format_money($order['total_amount']); ?></td>
                                            <td>
                                                <?php
                                                $badge_class = 'secondary';
                                                switch($order['status']) {
                                                    case 'pending': $badge_class = 'warning'; break;
                                                    case 'confirmed': $badge_class = 'info'; break;
                                                    case 'ongoing': $badge_class = 'primary'; break;
                                                    case 'completed': $badge_class = 'success'; break;
                                                    case 'cancelled': $badge_class = 'danger'; break;
                                                }
                                                ?>
                                                <span class="badge bg-<?php echo $badge_class; ?>">
                                                    <?php echo ucfirst($order['status']); ?>
                                                </span>
                                            </td>
                                            <td><?php echo date('M d, Y', strtotime($order['created_at'])); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Recent Transactions & Quick Actions -->
        <div class="col-md-4">
            <!-- Recent Transactions -->
            <div class="card mb-3">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Recent Transactions</h5>
                    <a href="wallet.php" class="btn btn-sm btn-outline-primary">View All</a>
                </div>
                <div class="card-body">
                    <?php if (empty($recent_transactions)): ?>
                        <p class="text-muted text-center">No transactions yet</p>
                    <?php else: ?>
                        <?php foreach ($recent_transactions as $txn): ?>
                            <div class="mb-3 pb-3 border-bottom">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <strong class="<?php echo $txn['category'] === 'credit' ? 'text-success' : 'text-danger'; ?>">
                                            <?php echo WalletHelper::getTransactionTypeLabel($txn['transaction_type']); ?>
                                        </strong>
                                        <br>
                                        <small class="text-muted">
                                            <?php echo date('M d, H:i', strtotime($txn['created_at'])); ?>
                                        </small>
                                    </div>
                                    <div class="text-right">
                                        <strong class="<?php echo $txn['category'] === 'credit' ? 'text-success' : 'text-danger'; ?>">
                                            <?php echo $txn['category'] === 'credit' ? '+' : '-'; ?>
                                            <?php echo WalletHelper::formatMoney($txn['amount']); ?>
                                        </strong>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Quick Actions -->
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">Quick Actions</h5>
                </div>
                <div class="card-body">
                    <a href="../items.php" class="btn btn-primary btn-block mb-2">
                        <i class="fas fa-search"></i> Browse Items
                    </a>
                    <a href="orders.php" class="btn btn-outline-primary btn-block mb-2">
                        <i class="fas fa-list"></i> My Orders
                    </a>
                    <a href="wallet.php" class="btn btn-outline-success btn-block mb-2">
                        <i class="fas fa-wallet"></i> My Wallet
                    </a>
                    <a href="favourites.php" class="btn btn-outline-danger btn-block">
                        <i class="fas fa-heart"></i> Favourites (<?php echo $favourites_count; ?>)
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>


<!-- ================================================================
     WITHDRAWAL MODAL
     ================================================================ -->
<div class="modal fade" id="withdrawModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title">
                    <i class="fas fa-money-bill-wave me-2"></i> Withdraw Funds
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <!-- Available Balance Display -->
                <div class="alert alert-info mb-4">
                    <div class="d-flex justify-content-between align-items-center">
                        <span><strong>Available Balance:</strong></span>
                        <span class="fs-5 fw-bold">₦<?php echo number_format($wallet['balance'], 2); ?></span>
                    </div>
                </div>

                <form id="withdrawForm">
                    <!-- Withdrawal Amount -->
                    <div class="mb-3">
                        <label class="form-label fw-bold">Withdrawal Amount <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <span class="input-group-text">₦</span>
                            <input type="number" 
                                   class="form-control form-control-lg" 
                                   id="withdrawAmount" 
                                   name="amount" 
                                   placeholder="Enter amount"
                                   min="100"
                                   max="<?php echo $wallet['balance']; ?>"
                                   step="0.01"
                                   required>
                        </div>
                        <small class="text-muted">Minimum: ₦5,000 | Maximum: ₦<?php echo number_format($wallet['balance'], 2); ?></small>
                        <div class="invalid-feedback" id="amountError"></div>
                    </div>

                    <!-- Bank Details (Auto-filled from database) -->
                    <?php
                    $user_details = $db->fetch("
                        SELECT bank_name, account_name, account_number 
                        FROM users 
                        WHERE id = ?
                    ", [Auth::id()]);
                    ?>

                    <div class="mb-3">
                        <label class="form-label fw-bold">Bank Name</label>
                        <input type="text" 
                               class="form-control" 
                               value="<?php echo htmlspecialchars($user_details['bank_name'] ?? 'Not Set'); ?>" 
                               readonly>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold">Account Name</label>
                        <input type="text" 
                               class="form-control" 
                               value="<?php echo htmlspecialchars($user_details['account_name'] ?? 'Not Set'); ?>" 
                               readonly>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold">Account Number</label>
                        <input type="text" 
                               class="form-control" 
                               value="<?php echo htmlspecialchars($user_details['account_number'] ?? 'Not Set'); ?>" 
                               readonly>
                    </div>

                    <?php if (empty($user_details['bank_name']) || empty($user_details['account_number'])): ?>
                        <div class="alert alert-warning">
                            <i class="fas fa-exclamation-triangle"></i> 
                            Please <a href="profile.php" class="alert-link">update your bank details</a> before withdrawing.
                        </div>
                    <?php endif; ?>

                    <input type="hidden" name="wallet_id" value="<?php echo $wallet['id']; ?>">
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" 
                        class="btn btn-success" 
                        id="submitWithdrawBtn"
                        onclick="submitWithdrawal()"
                        <?php if (empty($user_details['bank_name']) || empty($user_details['account_number'])): ?>
                            disabled
                        <?php endif; ?>>
                    <i class="fas fa-paper-plane"></i> Submit Withdrawal Request
                </button>
            </div>
        </div>
    </div>
</div>

<!-- ================================================================
     WITHDRAWAL JAVASCRIPT
     ================================================================ -->
<script>
// Available balance from PHP
const AVAILABLE_BALANCE = <?php echo $wallet['balance']; ?>;

function openWithdrawModal() {
    // Check if balance is sufficient
    if (AVAILABLE_BALANCE < 5000) {
        alert('Insufficient balance. Minimum withdrawal is ₦5,000.00');
        return;
    }

    // Open modal
    const modal = new bootstrap.Modal(document.getElementById('withdrawModal'));
    modal.show();
}

function validateAmount() {
    const amountInput = document.getElementById('withdrawAmount');
    const amount = parseFloat(amountInput.value);
    const errorDiv = document.getElementById('amountError');
    
    // Clear previous errors
    amountInput.classList.remove('is-invalid');
    errorDiv.textContent = '';
    
    if (!amount || amount <= 0) {
        amountInput.classList.add('is-invalid');
        errorDiv.textContent = 'Please enter a valid amount';
        return false;
    }
    
    if (amount < 5000) {
        amountInput.classList.add('is-invalid');
        errorDiv.textContent = 'Minimum withdrawal is ₦5,000.00';
        return false;
    }
    
    if (amount > AVAILABLE_BALANCE) {
        amountInput.classList.add('is-invalid');
        errorDiv.textContent = 'Amount exceeds available balance of ₦' + AVAILABLE_BALANCE.toLocaleString('en-NG', {minimumFractionDigits: 2});
        return false;
    }
    
    return true;
}

function submitWithdrawal() {
    // Validate amount
    if (!validateAmount()) {
        return;
    }
    
    const amount = parseFloat(document.getElementById('withdrawAmount').value);
    
    // Confirm withdrawal
    if (!confirm(`Confirm withdrawal of ₦${amount.toLocaleString('en-NG', {minimumFractionDigits: 2})}?\n\nThis will be sent to your registered bank account.`)) {
        return;
    }
    
    const btn = document.getElementById('submitWithdrawBtn');
    const originalHTML = btn.innerHTML;
    
    // Disable button and show loading
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
    
    // Get form data
    const formData = new FormData(document.getElementById('withdrawForm'));
    
    // Submit withdrawal request
    fetch('../api/customer-withdraw.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('✓ ' + data.message);
            // Close modal and reload page
            bootstrap.Modal.getInstance(document.getElementById('withdrawModal')).hide();
            location.reload();
        } else {
            alert('✗ Error: ' + data.error);
            // Re-enable button
            btn.disabled = false;
            btn.innerHTML = originalHTML;
        }
    })
    .catch(error => {
        alert('✗ Failed to process withdrawal. Please try again.');
        // Re-enable button
        btn.disabled = false;
        btn.innerHTML = originalHTML;
    });
}

// Real-time validation on amount input
document.addEventListener('DOMContentLoaded', function() {
    const amountInput = document.getElementById('withdrawAmount');
    if (amountInput) {
        amountInput.addEventListener('input', validateAmount);
    }
});
</script>

<style>
/* Modal styling */
#withdrawModal .modal-content {
    border: none;
    box-shadow: 0 10px 40px rgba(0,0,0,0.2);
}

#withdrawModal .form-control:read-only {
    background-color: #f8f9fa;
    border-color: #dee2e6;
}

#withdrawModal .form-control-lg {
    font-size: 1.5rem;
    font-weight: bold;
}

#withdrawModal .alert-info {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border: none;
}
</style>

<?php include '../templates/layouts/customer/footer.php'; ?>