<?php
$pageTitle = 'Club Memberships';
include 'includes/header.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$clubModel = new Club();
$walletModel = new Wallet();
$settingModel = new Setting();

$userModel = new User();
$user = $userModel->getFullUserDetailsById($_SESSION['user_id']);

// Get User Wallet Balance
$userWallet = $walletModel->getOrCreateWallet('user', $_SESSION['user_id']);
$settings = $settingModel->getAll();
$currency_symbol = ($settings['system_currency'] ?? 'USD') === 'ZMW' ? 'K' : '$';

$primary_color = $settings['primary_color'] ?? '#3498db';
$secondary_color = $settings['secondary_color'] ?? '#2c3e50';

// Fetch all active packages (grouped by club logic inside model or handle here)
// For simplicity, we'll fetch all and group them by club
$all_packages = $clubModel->getAllActivePackagesByLeague(1); // Assuming league 1 for now

?>

<div class="memberships-hero">
    <div class="hero-content-wrapper">
        <div class="hero-header-row">
            <div class="hero-text">
                <h1>Club Memberships</h1>
                <p>Support your favorite clubs and unlock exclusive benefits.</p>
            </div>
            <div class="wallet-info-hero">
                <span class="label">My Wallet</span>
                <span class="value"><?php echo $currency_symbol . number_format($userWallet->balance, 2); ?></span>
                <a href="wallet.php" class="btn-sm btn-hero-secondary">Top Up</a>
            </div>
        </div>
    </div>
</div>

<div class="page-content">
    <?php if (isset($_GET['status']) && $_GET['status'] === 'success'): ?>
        <div class="status-message success">Membership purchased successfully!</div>
    <?php elseif (isset($_GET['error'])): ?>
        <div class="status-message error">
            <?php 
            if ($_GET['error'] === 'insufficient_funds') echo 'Insufficient funds in your wallet.';
            else echo 'An error occurred. ' . htmlspecialchars($_GET['error']); 
            ?>
        </div>
    <?php endif; ?>

    <?php if (empty($all_packages)): ?>
        <p class="no-data-msg">No membership packages available at the moment.</p>
    <?php else: ?>
        <?php foreach ($all_packages as $club_id => $packages): 
            $club = $clubModel->findById($club_id);
        ?>
            <div class="dashboard-section">
                <div class="section-header" style="display:flex; align-items:center; gap:10px; margin-bottom:15px;">
                    <img src="<?php echo htmlspecialchars($club->logo); ?>" alt="" style="width:40px; height:40px; object-fit:contain;">
                    <h2 class="dashboard-title" style="margin:0;"><?php echo htmlspecialchars($club->name); ?></h2>
                </div>
                
                <div class="packages-grid">
                    <?php foreach ($packages as $pkg): ?>
                        <div class="package-card">
                            <h3><?php echo htmlspecialchars($pkg->name); ?></h3>
                            <div class="price"><?php echo $currency_symbol . number_format($pkg->price, 2); ?></div>
                            <div class="duration"><?php echo ucfirst($pkg->duration_type); ?></div>
                            <p class="description"><?php echo htmlspecialchars($pkg->description); ?></p>
                            
                            <form class="membership-form" data-package-id="<?php echo $pkg->id; ?>" data-price="<?php echo $pkg->price; ?>" data-name="<?php echo htmlspecialchars($pkg->name); ?>">
                                <input type="hidden" name="package_id" value="<?php echo $pkg->id; ?>">
                                <input type="hidden" name="payment_method" value="wallet">
                                <button type="button" class="btn btn-block purchase-btn">Purchase</button>
                            </form>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

<!-- Top Up Modal -->
<div id="topUpModal" class="modal">
    <div class="modal-content" style="max-width: 400px;">
        <div class="modal-header">
            <h3>Top Up Wallet</h3>
            <button class="modal-close-btn" onclick="closeTopUpModal()">&times;</button>
        </div>
        <div class="form-group">
            <label for="topup_amount">Amount (<?php echo $currency_symbol; ?>)</label>
            <input type="number" id="topup_amount" class="form-control" min="1" step="0.01" placeholder="Enter amount">
        </div>
        <button type="button" id="confirm-topup-btn" class="btn btn-block">Proceed to Payment</button>
    </div>
</div>

<!-- Payment Confirmation Modal -->
<div id="paymentConfirmationModal" class="modal">
    <div class="modal-content" style="max-width: 400px;">
        <div class="modal-header">
            <h3>Confirm Payment</h3>
            <button class="modal-close-btn" onclick="closePaymentModal()">&times;</button>
        </div>
        <div class="modal-body">
            <p id="payment-confirmation-text" style="font-size: 1.1rem; margin-bottom: 20px;"></p>
            <div class="modal-actions" style="display: flex; gap: 10px; justify-content: flex-end;">
                <button class="btn btn-secondary" onclick="closePaymentModal()">Cancel</button>
                <button class="btn" id="confirm-payment-btn">Proceed to Pay</button>
            </div>
        </div>
    </div>
</div>

<style>
:root {
    --hero-gradient: linear-gradient(135deg, <?php echo $primary_color; ?> 0%, <?php echo $secondary_color; ?> 100%);
}

.memberships-hero {
    background: var(--hero-gradient);
    color: white;
    padding: 6rem 20px 3rem 20px;
    border-radius: 0 0 30px 30px;
    margin-bottom: 2rem;
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    margin-top: 0;
}

.hero-content-wrapper {
    max-width: 1200px;
    margin: 0 auto;
}

.hero-header-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 20px;
}

.hero-text h1 {
    margin: 0 0 10px 0;
    font-size: 2.5rem;
    font-weight: 800;
}

.hero-text p {
    margin: 0;
    font-size: 1.1rem;
    opacity: 0.9;
}

.wallet-info-hero {
    background: rgba(255,255,255,0.15);
    padding: 15px 25px;
    border-radius: 12px;
    backdrop-filter: blur(5px);
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    min-width: 150px;
}

.wallet-info-hero .label {
    font-size: 0.8rem;
    text-transform: uppercase;
    opacity: 0.8;
    margin-bottom: 5px;
}

.wallet-info-hero .value {
    font-size: 1.8rem;
    font-weight: 800;
    margin-bottom: 10px;
}

.btn-hero-secondary {
    background: rgba(255,255,255,0.2);
    color: white;
    border: 1px solid rgba(255,255,255,0.3);
    text-decoration: none;
    padding: 5px 15px;
    border-radius: 20px;
    font-size: 0.85rem;
    transition: background 0.2s;
}

.btn-hero-secondary:hover {
    background: rgba(255,255,255,0.3);
}

.packages-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 20px;
}
.package-card {
    border: 1px solid #eee;
    border-radius: 8px;
    padding: 20px;
    text-align: center;
    background: #fff;
    transition: transform 0.2s;
    display: flex;
    flex-direction: column;
}
.package-card:hover { transform: translateY(-5px); box-shadow: 0 5px 15px rgba(0,0,0,0.05); }
.package-card h3 { margin: 0 0 10px 0; color: var(--primary-color); }
.package-card .price { font-size: 1.8rem; font-weight: 800; color: #333; }
.package-card .duration { color: #777; font-size: 0.9rem; margin-bottom: 15px; text-transform: uppercase; }
.package-card .description { color: #555; font-size: 0.9rem; margin-bottom: 20px; min-height: 40px; flex-grow: 1; }

/* Ensure modal is hidden by default */
.modal { display: none; }
.modal.show { display: flex; }
</style>

<script src="https://checkout.flutterwave.com/v3.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const purchaseBtns = document.querySelectorAll('.purchase-btn');
    const topUpModal = document.getElementById('topUpModal');
    const paymentModal = document.getElementById('paymentConfirmationModal');
    const confirmPaymentBtn = document.getElementById('confirm-payment-btn');
    const paymentText = document.getElementById('payment-confirmation-text');
    
    const userWalletBalance = <?php echo floatval($userWallet->balance ?? 0); ?>;
    const currencySymbol = '<?php echo $currency_symbol; ?>';
    let paymentData = null;

    window.closeTopUpModal = function() { topUpModal.classList.remove('show'); }
    window.closePaymentModal = function() { paymentModal.classList.remove('show'); }
    window.addEventListener('click', (e) => { 
        if (e.target === paymentModal) closePaymentModal();
        if (e.target === topUpModal) closeTopUpModal();
    });
    
    purchaseBtns.forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            const form = this.closest('form');
            const price = parseFloat(form.dataset.price);
            
            if (userWalletBalance >= price) {
                // Submit to PHP for wallet processing
                form.action = 'purchase_membership_process.php';
                form.method = 'POST';
                form.submit();
            } else {
                // Insufficient funds
                const needed = price - userWalletBalance;
                document.getElementById('topup_amount').value = needed.toFixed(2);
                alert(`Insufficient funds. You need ${currencySymbol}${needed.toFixed(2)} more.`);
                topUpModal.classList.add('show');
            }
        });
    });

    // --- Top Up Logic ---
    const confirmTopUpBtn = document.getElementById('confirm-topup-btn');
    if (confirmTopUpBtn) {
        confirmTopUpBtn.addEventListener('click', function() {
            const amountInput = document.getElementById('topup_amount');
            const amount = parseFloat(amountInput.value);

            if (!amount || amount <= 0) {
                alert("Please enter a valid amount.");
                return;
            }

            const publicKey = "<?php echo $settings['flutterwave_public_key'] ?? ''; ?>";
            if (!publicKey) {
                alert("Payment gateway not configured.");
                return;
            }

            closeTopUpModal();

            paymentData = {
                amount: amount,
                publicKey: publicKey
            };

            paymentText.textContent = `Top up wallet with ${currencySymbol}${amount.toFixed(2)}?`;
            paymentModal.classList.add('show');
        });
    }

    if (confirmPaymentBtn) {
        confirmPaymentBtn.addEventListener('click', function() {
            if (!paymentData) return;
            closePaymentModal();

            const txRef = 'user_topup_' + Date.now();
            
            try {
                FlutterwaveCheckout({
                    public_key: paymentData.publicKey,
                    tx_ref: txRef,
                    amount: paymentData.amount,
                    currency: "<?php echo $settings['system_currency'] ?? 'USD'; ?>",
                    payment_options: "card,mobilemoney,ussd",
                    customer: {
                        email: <?php echo json_encode($user->email ?? ''); ?>,
                        name: <?php echo json_encode(($user->first_name ?? '') . ' ' . ($user->last_name ?? '')); ?>,
                    },
                    meta: {
                        payment_context: 'user_wallet_deposit'
                    },
                    customizations: {
                        title: "Wallet Top Up",
                        description: "Add funds to wallet",
                        logo: <?php echo json_encode($settings['app_logo'] ?? ''); ?>,
                    },
                    callback: function(data) {
                        // Verify transaction on backend
                        fetch('flutterwave_verify.php', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({
                                transaction_id: data.transaction_id,
                                tx_ref: data.tx_ref,
                                payment_context: 'user_wallet_deposit'
                            })
                        })
                        .then(response => response.json())
                        .then(result => {
                            if (result.status === 'success') {
                                window.location.reload();
                            } else {
                                alert(result.message || 'Verification failed.');
                            }
                        });
                    },
                    onclose: function() {}
                });
            } catch (error) {
                console.error("Flutterwave Error:", error);
                alert("Failed to initialize payment.");
            }
        });
    }
});
</script>

<?php include 'includes/footer.php'; ?>