<?php 
// Include session handling
try {
    include_once 'services/session.php';
} catch (Exception $e) {
    die("Error including session.php: " . $e->getMessage());
}

// Check if user is logged in
if (!isset($_SESSION['user']) || empty($_SESSION['user'])) {
    header('Location: auth-login.php?error=session_expired');
    exit();
}

// Get user details
$user_role = $_SESSION['role_name'] ?? 'Customer';
$user_id = $_SESSION['user_id'] ?? 0;
$user_name = $_SESSION['full_name'] ?? $_SESSION['user'];

// Include database connection
try {
    require_once 'layouts/dbconn.php';
} catch (Exception $e) {
    die("Error including database connection: " . $e->getMessage());
}

// Test database connection
if (!isset($conn) || $conn->connect_error) {
    die("Database connection failed: " . ($conn->connect_error ?? 'Connection object not found'));
}

// Handle form submission
$success_message = '';
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $amount = $_POST['amount'] ?? 0;
    $currency = $_POST['currency'] ?? 'USD';
    $payment_method = $_POST['payment_method'] ?? 'CREDIT_CARD';
    
    // Validate amount
    if ($amount < 5) {
        $error_message = 'Minimum top-up amount is $5.00';
    } elseif ($amount > 1000) {
        $error_message = 'Maximum top-up amount is $1,000.00';
    } else {
        // Create topup record
        $topup_reference = 'TU_' . time() . '_' . $user_id;
        
        try {
            // Get or create wallet
            $stmt = $conn->prepare("SELECT wallet_id FROM wallets WHERE user_id = ? AND status = 'ACTIVE'");
            if (!$stmt) {
                throw new Exception("Prepare failed: " . $conn->error);
            }
            
            $stmt->bind_param("i", $user_id);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->num_rows === 0) {
                // Create new wallet
                $stmt = $conn->prepare("INSERT INTO wallets (user_id, balance_usd, balance_ssp, balance_kes, balance_ugx, status) VALUES (?, 0, 0, 0, 0, 'ACTIVE')");
                if (!$stmt) {
                    throw new Exception("Prepare failed: " . $conn->error);
                }
                $stmt->bind_param("i", $user_id);
                $stmt->execute();
                $wallet_id = $conn->insert_id;
            } else {
                $wallet = $result->fetch_assoc();
                $wallet_id = $wallet['wallet_id'];
            }
            
            // Insert topup record
            $stmt = $conn->prepare("INSERT INTO wallet_topups (wallet_id, amount, currency, payment_method, provider, provider_reference, status, net_amount, created_at) VALUES (?, ?, ?, ?, ?, ?, 'PENDING', ?, NOW())");
            if (!$stmt) {
                throw new Exception("Prepare failed: " . $conn->error);
            }
            
            $provider = $payment_method === 'MOBILE_MONEY' ? 'MTN_MOMO' : 'STRIPE';
            $stmt->bind_param("idssssd", $wallet_id, $amount, $currency, $payment_method, $provider, $topup_reference, $amount);
            $stmt->execute();
            
            // Redirect to payment processing
            $_SESSION['topup_reference'] = $topup_reference;
            $success_message = "Topup request created successfully! Reference: $topup_reference";
            
        } catch (Exception $e) {
            $error_message = 'Error processing top-up request: ' . $e->getMessage();
        }
    }
}

// Get current wallet balance
$wallet_balance = ['usd' => 0, 'ssp' => 0, 'kes' => 0, 'ugx' => 0];
try {
    $stmt = $conn->prepare("SELECT balance_usd, balance_ssp, balance_kes, balance_ugx FROM wallets WHERE user_id = ? AND status = 'ACTIVE'");
    if ($stmt) {
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result->num_rows > 0) {
            $balance = $result->fetch_assoc();
            $wallet_balance = [
                'usd' => $balance['balance_usd'],
                'ssp' => $balance['balance_ssp'],
                'kes' => $balance['balance_kes'],
                'ugx' => $balance['balance_ugx']
            ];
        }
    }
} catch (Exception $e) {
    // Log error silently in production
    error_log("Error getting wallet balance: " . $e->getMessage());
}

// Get recent topups
$recent_topups = [];
try {
    $stmt = $conn->prepare("
        SELECT wt.amount, wt.currency, wt.status, wt.created_at, wt.payment_method, wt.provider_reference
        FROM wallet_topups wt
        JOIN wallets w ON wt.wallet_id = w.wallet_id
        WHERE w.user_id = ?
        ORDER BY wt.created_at DESC
        LIMIT 5
    ");
    if ($stmt) {
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $recent_topups[] = $row;
        }
    }
} catch (Exception $e) {
    // Log error silently in production
    error_log("Error getting recent topups: " . $e->getMessage());
}
?>

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

<head>
    <?php 
    $title = "Top-up Wallet";
    if (file_exists('partials/title-meta.php')) {
        try {
            include_once 'partials/title-meta.php';
        } catch (Exception $e) {
            echo "<title>Top-up Wallet - ConnectPay</title>\n";
        }
    } else {
        echo "<title>Top-up Wallet - ConnectPay</title>\n";
    }
    ?>
    
    <?php 
    if (file_exists('partials/head-css.php')) {
        try {
            include_once 'partials/head-css.php';
        } catch (Exception $e) {
            echo '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">' . "\n";
            echo '<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">' . "\n";
        }
    } else {
        echo '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">' . "\n";
        echo '<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">' . "\n";
    }
    ?>
    
    <style>
        .wallet-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 2rem;
            margin-bottom: 2rem;
        }
        
        .payment-method-card {
            border: 2px solid #e9ecef;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .payment-method-card:hover {
            border-color: #007bff;
            background-color: #f8f9fa;
        }
        
        .payment-method-card.selected {
            border-color: #007bff;
            background-color: rgba(0, 123, 255, 0.1);
        }
        
        .amount-preset {
            border: 2px solid #e9ecef;
            border-radius: 8px;
            padding: 1rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .amount-preset:hover {
            border-color: #28a745;
            background-color: rgba(40, 167, 69, 0.1);
        }
        
        .amount-preset.selected {
            border-color: #28a745;
            background-color: rgba(40, 167, 69, 0.1);
            color: #28a745;
            font-weight: bold;
        }
        
        .currency-badge {
            background: rgba(255,255,255,0.2);
            padding: 0.3rem 0.8rem;
            border-radius: 20px;
            margin-right: 0.5rem;
            margin-bottom: 0.5rem;
            display: inline-block;
        }
        
        body {
            background-color: #f8f9fa;
        }
    </style>
</head>

<body>

<div id="wrapper">
    <?php 
    $pagetitle = "Top-up Wallet"; 
    if (file_exists('partials/menu.php')) {
        try {
            include_once 'partials/menu.php';
        } catch (Exception $e) {
            echo '<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
                    <div class="container">
                        <a class="navbar-brand" href="customer-dashboard.php">ConnectPay</a>
                        <span class="navbar-text">Welcome, ' . htmlspecialchars($user_name) . '</span>
                    </div>
                  </nav>';
        }
    } else {
        echo '<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
                <div class="container">
                    <a class="navbar-brand" href="customer-dashboard.php">ConnectPay</a>
                    <span class="navbar-text">Welcome, ' . htmlspecialchars($user_name) . '</span>
                </div>
              </nav>';
    }
    ?>

    <div class="content-page">
        <div class="content">
            <div class="container-fluid">
                
                <!-- Page Title -->
                <div class="row">
                    <div class="col-12">
                        <div class="page-title-box mb-4">
                            <h4 class="page-title">
                                <i class="fas fa-wallet me-2"></i>
                                Top-up Wallet
                            </h4>
                            <nav aria-label="breadcrumb">
                                <ol class="breadcrumb">
                                    <li class="breadcrumb-item"><a href="customer-dashboard.php">Dashboard</a></li>
                                    <li class="breadcrumb-item active">Top-up Wallet</li>
                                </ol>
                            </nav>
                        </div>
                    </div>
                </div>

                <!-- Success/Error Messages -->
                <?php if ($success_message): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="fas fa-check-circle me-2"></i>
                    <?php echo htmlspecialchars($success_message); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                <?php endif; ?>

                <?php if ($error_message): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="fas fa-exclamation-circle me-2"></i>
                    <?php echo htmlspecialchars($error_message); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                <?php endif; ?>

                <!-- Current Wallet Balance -->
                <div class="row">
                    <div class="col-12">
                        <div class="wallet-card">
                            <div class="row align-items-center">
                                <div class="col-md-8">
                                    <h3 class="mb-3">
                                        <i class="fas fa-wallet me-2"></i>
                                        Current Wallet Balance
                                    </h3>
                                    <div class="mb-3">
                                        <div class="currency-badge">
                                            <strong>USD $<?php echo number_format($wallet_balance['usd'], 2); ?></strong>
                                        </div>
                                        <?php if ($wallet_balance['ssp'] > 0): ?>
                                        <div class="currency-badge">
                                            SSP <?php echo number_format($wallet_balance['ssp'], 0); ?>
                                        </div>
                                        <?php endif; ?>
                                        <?php if ($wallet_balance['kes'] > 0): ?>
                                        <div class="currency-badge">
                                            KES <?php echo number_format($wallet_balance['kes'], 0); ?>
                                        </div>
                                        <?php endif; ?>
                                        <?php if ($wallet_balance['ugx'] > 0): ?>
                                        <div class="currency-badge">
                                            UGX <?php echo number_format($wallet_balance['ugx'], 0); ?>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <div class="col-md-4 text-md-end">
                                    <a href="wallet-overview.php" class="btn btn-light">
                                        <i class="fas fa-history me-1"></i>
                                        Transaction History
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Top-up Form -->
                <div class="row">
                    <div class="col-xl-8">
                        <div class="card">
                            <div class="card-header">
                                <h4 class="header-title">
                                    <i class="fas fa-plus-circle me-2"></i>
                                    Add Funds to Wallet
                                </h4>
                            </div>
                            <div class="card-body">
                                <form method="POST" id="topupForm">
                                    
                                    <!-- Amount Selection -->
                                    <div class="mb-4">
                                        <label class="form-label">Select Amount (USD)</label>
                                        <div class="row">
                                            <div class="col-6 col-md-3 mb-2">
                                                <div class="amount-preset" data-amount="10">
                                                    <h5 class="mb-1">$10</h5>
                                                    <small>Quick top-up</small>
                                                </div>
                                            </div>
                                            <div class="col-6 col-md-3 mb-2">
                                                <div class="amount-preset" data-amount="25">
                                                    <h5 class="mb-1">$25</h5>
                                                    <small>Popular</small>
                                                </div>
                                            </div>
                                            <div class="col-6 col-md-3 mb-2">
                                                <div class="amount-preset" data-amount="50">
                                                    <h5 class="mb-1">$50</h5>
                                                    <small>Best value</small>
                                                </div>
                                            </div>
                                            <div class="col-6 col-md-3 mb-2">
                                                <div class="amount-preset" data-amount="100">
                                                    <h5 class="mb-1">$100</h5>
                                                    <small>Business</small>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="mt-3">
                                            <label for="custom_amount" class="form-label">Or enter custom amount</label>
                                            <div class="input-group">
                                                <span class="input-group-text">$</span>
                                                <input type="number" class="form-control" id="custom_amount" name="amount" 
                                                       min="5" max="1000" step="0.01" placeholder="Enter amount" 
                                                       value="<?php echo htmlspecialchars($_POST['amount'] ?? ''); ?>">
                                            </div>
                                            <small class="text-muted">Minimum: $5.00 | Maximum: $1,000.00</small>
                                        </div>
                                    </div>

                                    <!-- Currency -->
                                    <div class="mb-4">
                                        <label class="form-label">Currency</label>
                                        <select class="form-select" name="currency">
                                            <option value="USD" <?php echo ($_POST['currency'] ?? 'USD') === 'USD' ? 'selected' : ''; ?>>USD - US Dollar</option>
                                            <option value="SSP" <?php echo ($_POST['currency'] ?? '') === 'SSP' ? 'selected' : ''; ?>>SSP - South Sudanese Pound</option>
                                            <option value="KES" <?php echo ($_POST['currency'] ?? '') === 'KES' ? 'selected' : ''; ?>>KES - Kenyan Shilling</option>
                                            <option value="UGX" <?php echo ($_POST['currency'] ?? '') === 'UGX' ? 'selected' : ''; ?>>UGX - Ugandan Shilling</option>
                                        </select>
                                    </div>

                                    <!-- Payment Method -->
                                    <div class="mb-4">
                                        <label class="form-label">Payment Method</label>
                                        
                                        <div class="payment-method-card" data-method="CREDIT_CARD">
                                            <div class="d-flex align-items-center">
                                                <div class="form-check me-3">
                                                    <input class="form-check-input" type="radio" name="payment_method" 
                                                           value="CREDIT_CARD" id="card_payment" checked>
                                                </div>
                                                <i class="fas fa-credit-card fa-2x text-primary me-3"></i>
                                                <div>
                                                    <h6 class="mb-1">Credit/Debit Card</h6>
                                                    <small class="text-muted">Visa, MasterCard, American Express</small>
                                                </div>
                                                <div class="ms-auto">
                                                    <span class="badge bg-success">Instant</span>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="payment-method-card" data-method="MOBILE_MONEY">
                                            <div class="d-flex align-items-center">
                                                <div class="form-check me-3">
                                                    <input class="form-check-input" type="radio" name="payment_method" 
                                                           value="MOBILE_MONEY" id="momo_payment">
                                                </div>
                                                <i class="fas fa-mobile-alt fa-2x text-warning me-3"></i>
                                                <div>
                                                    <h6 class="mb-1">Mobile Money</h6>
                                                    <small class="text-muted">MTN MoMo, Airtel Money, Orange Money</small>
                                                </div>
                                                <div class="ms-auto">
                                                    <span class="badge bg-warning">2-5 mins</span>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="payment-method-card" data-method="BANK_TRANSFER">
                                            <div class="d-flex align-items-center">
                                                <div class="form-check me-3">
                                                    <input class="form-check-input" type="radio" name="payment_method" 
                                                           value="BANK_TRANSFER" id="bank_payment">
                                                </div>
                                                <i class="fas fa-university fa-2x text-secondary me-3"></i>
                                                <div>
                                                    <h6 class="mb-1">Bank Transfer</h6>
                                                    <small class="text-muted">Direct bank transfer (local banks)</small>
                                                </div>
                                                <div class="ms-auto">
                                                    <span class="badge bg-secondary">1-3 days</span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Terms and Submit -->
                                    <div class="mb-4">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="terms_agree" required>
                                            <label class="form-check-label" for="terms_agree">
                                                I agree to the Terms of Service and Privacy Policy
                                            </label>
                                        </div>
                                    </div>

                                    <div class="d-grid gap-2 d-md-flex justify-content-md-between">
                                        <a href="customer-dashboard.php" class="btn btn-outline-secondary">
                                            <i class="fas fa-arrow-left me-1"></i>
                                            Back to Dashboard
                                        </a>
                                        <button type="submit" class="btn btn-primary" id="submitBtn">
                                            <i class="fas fa-credit-card me-2"></i>
                                            Process Top-up
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <!-- Recent Top-ups -->
                    <div class="col-xl-4">
                        <div class="card">
                            <div class="card-header">
                                <h4 class="header-title">
                                    <i class="fas fa-history me-2"></i>
                                    Recent Top-ups
                                </h4>
                            </div>
                            <div class="card-body">
                                <?php if (empty($recent_topups)): ?>
                                <div class="text-center py-3">
                                    <i class="fas fa-history fa-2x mb-2 text-muted"></i>
                                    <p class="text-muted">No top-ups yet</p>
                                    <small>Your recent top-up history will appear here</small>
                                </div>
                                <?php else: ?>
                                    <?php foreach ($recent_topups as $topup): ?>
                                    <div class="d-flex justify-content-between align-items-center mb-3 pb-3 border-bottom">
                                        <div>
                                            <h6 class="mb-1">
                                                <?php echo htmlspecialchars($topup['currency']); ?> <?php echo number_format($topup['amount'], 2); ?>
                                            </h6>
                                            <small class="text-muted d-block">
                                                <?php echo ucfirst(str_replace('_', ' ', strtolower($topup['payment_method']))); ?>
                                            </small>
                                            <small class="text-muted">
                                                <?php echo date('M j, Y g:i A', strtotime($topup['created_at'])); ?>
                                            </small>
                                        </div>
                                        <div class="text-end">
                                            <?php
                                            $statusClass = '';
                                            switch($topup['status']) {
                                                case 'COMPLETED': $statusClass = 'bg-success'; break;
                                                case 'PENDING': $statusClass = 'bg-warning'; break;
                                                case 'FAILED': $statusClass = 'bg-danger'; break;
                                                default: $statusClass = 'bg-secondary';
                                            }
                                            ?>
                                            <span class="badge <?php echo $statusClass; ?>">
                                                <?php echo ucfirst(strtolower($topup['status'])); ?>
                                            </span>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>

        <?php 
        if (file_exists('partials/footer.php')) {
            try {
                include_once 'partials/footer.php';
            } catch (Exception $e) {
                echo '<footer class="bg-light text-center py-3 mt-5"><p>&copy; 2024 ConnectPay Platform</p></footer>';
            }
        } else {
            echo '<footer class="bg-light text-center py-3 mt-5"><p>&copy; 2024 ConnectPay Platform</p></footer>';
        }
        ?>
    </div>
</div>

<?php 
if (file_exists('partials/footer-scripts.php')) {
    try {
        include_once 'partials/footer-scripts.php';
    } catch (Exception $e) {
        echo '<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>' . "\n";
    }
} else {
    echo '<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>' . "\n";
}
?>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Amount preset selection
    const amountPresets = document.querySelectorAll('.amount-preset');
    const customAmountInput = document.getElementById('custom_amount');
    const paymentMethodCards = document.querySelectorAll('.payment-method-card');
    const paymentMethodRadios = document.querySelectorAll('input[name="payment_method"]');

    // Amount preset selection
    amountPresets.forEach(preset => {
        preset.addEventListener('click', function() {
            amountPresets.forEach(p => p.classList.remove('selected'));
            this.classList.add('selected');
            customAmountInput.value = this.dataset.amount;
        });
    });

    // Payment method selection
    paymentMethodCards.forEach(card => {
        card.addEventListener('click', function() {
            const method = this.dataset.method;
            const radio = document.querySelector('input[value="' + method + '"]');
            if (radio) {
                radio.checked = true;
                updatePaymentMethodCards();
            }
        });
    });

    function updatePaymentMethodCards() {
        paymentMethodCards.forEach(card => {
            card.classList.remove('selected');
            const method = card.dataset.method;
            const radio = document.querySelector('input[value="' + method + '"]');
            if (radio && radio.checked) {
                card.classList.add('selected');
            }
        });
    }

    // Initialize
    updatePaymentMethodCards();
});
</script>

</body>
</html>