<?php
require_once '../core/bootstrap.php';

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

$pageTitle = 'My Wallet';
include 'includes/header.php';

$user_id = $_SESSION['user_id'];
$walletModel = new Wallet();
$userWallet = $walletModel->getOrCreateWallet('user', $user_id);

// Get User Details for Payment
$userModel = new User();
$user = $userModel->getFullUserDetailsById($user_id);

// Fetch transactions
$transactions = $walletModel->getTransactions($userWallet->id, 50);

// Get currency symbol
$settingModel = new Setting();
$settings = $settingModel->getAll();
$currency_symbol = ($settings['system_currency'] ?? 'USD') === 'ZMW' ? 'K' : '$';

?>

<div class="wallet-hero">
    <div class="hero-content-wrapper">
        <div class="hero-header-row">
            <div class="hero-text">
                <h1>My Wallet</h1>
                <p>Manage your funds, view transactions, and top up your balance.</p>
            </div>
        </div>
        <div class="wallet-balance-card">
            <span class="balance-label">Current Balance</span>
            <span class="balance-value"><?php echo $currency_symbol . number_format($userWallet->balance, 2); ?></span>
            <div class="wallet-actions">
                <button class="btn btn-hero" onclick="openDepositModal()"><i class="fa-solid fa-circle-plus"></i> Add Funds</button>
                <button class="btn btn-hero-secondary" onclick="openTransferModal()"><i class="fa-solid fa-paper-plane"></i> Transfer</button>
                <button class="btn btn-hero-secondary" onclick="openWithdrawModal()"><i class="fa-solid fa-money-bill-transfer"></i> Withdraw</button>
            </div>
        </div>
    </div>
</div>

<div class="page-content" style="padding-top: 0;">
    <div class="dashboard-section">
        <h2 class="dashboard-title">Transaction History</h2>
        <div class="table-wrapper">
            <?php if (!empty($transactions)): ?>
                <table class="styled-table">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Type</th>
                            <th>Description</th>
                            <th>Amount</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($transactions as $t): ?>
                            <tr>
                                <td><?php echo date('d M Y, H:i', strtotime($t->created_at)); ?></td>
                                <td><span class="badge badge-<?php echo $t->type; ?>"><?php echo ucfirst(str_replace('_', ' ', $t->type)); ?></span></td>
                                <td><?php echo htmlspecialchars($t->description); ?></td>
                                <td class="<?php echo in_array($t->type, ['deposit', 'transfer_in']) ? 'text-success' : 'text-danger'; ?>">
                                    <?php echo (in_array($t->type, ['deposit', 'transfer_in']) ? '+' : '-') . $currency_symbol . number_format($t->amount, 2); ?>
                                </td>
                                <td><?php echo ucfirst($t->status); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <p class="no-data-msg">No transactions found.</p>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Deposit Modal -->
<div id="depositModal" class="modal">
    <div class="modal-content" style="max-width: 400px;">
        <div class="modal-header">
            <h3>Add Funds</h3>
            <button class="modal-close-btn" onclick="closeDepositModal()">&times;</button>
        </div>
        <form id="deposit-form">
            <div class="form-group">
                <label for="amount">Amount (<?php echo $currency_symbol; ?>)</label>
                <input type="number" name="amount" id="amount" step="0.01" min="1" required class="form-control" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px;">
            </div>
            <button type="button" id="pay-btn" class="btn btn-block">Proceed to Payment</button>
        </form>
    </div>
</div>

<!-- Transfer Modal -->
<div id="transferModal" class="modal">
    <div class="modal-content" style="max-width: 400px;">
        <div class="modal-header">
            <h3>Transfer Funds</h3>
            <button class="modal-close-btn" onclick="closeTransferModal()">&times;</button>
        </div>
        <form id="transfer-form" action="wallet_transfer_process.php" method="POST">
            <div class="form-group">
                <label for="recipient_email">Recipient Email</label>
                <input type="email" name="recipient_email" id="recipient_email" required class="form-control" placeholder="user@example.com" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px;">
            </div>
            <div class="form-group">
                <label for="transfer_amount">Amount (<?php echo $currency_symbol; ?>)</label>
                <input type="number" name="amount" id="transfer_amount" step="0.01" min="0.01" required class="form-control" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px;">
            </div>
            <div class="form-group">
                <label for="description">Description (Optional)</label>
                <input type="text" name="description" id="description" class="form-control" placeholder="e.g. Lunch money" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px;">
            </div>
            <button type="button" id="submit-transfer-btn" class="btn btn-block">Send Funds</button>
        </form>
    </div>
</div>

<!-- Withdrawal Modal -->
<div id="withdrawModal" class="modal">
    <div class="modal-content" style="max-width: 400px;">
        <div class="modal-header">
            <h3>Request Withdrawal</h3>
            <button class="modal-close-btn" onclick="closeWithdrawModal()">&times;</button>
        </div>
        <form id="withdraw-form" action="wallet_withdrawal_process.php" method="POST">
            <div class="form-group">
                <label for="withdraw_amount">Amount (<?php echo $currency_symbol; ?>)</label>
                <input type="number" name="amount" id="withdraw_amount" step="0.01" min="0.01" required class="form-control" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px;">
            </div>
            <div class="form-group">
                <label for="withdraw_details">Payment Details</label>
                <textarea name="details" id="withdraw_details" required class="form-control" placeholder="Bank Name, Account Number, or Mobile Money Number" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px;" rows="3"></textarea>
            </div>
            <button type="button" id="submit-withdraw-btn" class="btn btn-block">Submit Request</button>
        </form>
    </div>
</div>

<!-- Confirmation Modal -->
<div id="confirmationModal" class="modal">
    <div class="modal-content" style="max-width: 400px;">
        <div class="modal-header">
            <h3 id="confirmation-title">Confirm Action</h3>
            <button class="modal-close-btn" onclick="closeConfirmationModal()">&times;</button>
        </div>
        <div class="modal-body">
            <p id="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 type="button" class="btn btn-secondary" onclick="closeConfirmationModal()">Cancel</button>
                <button type="button" class="btn btn-danger" id="confirm-action-btn">Confirm</button>
            </div>
        </div>
    </div>
</div>

<div id="toast-container"></div>

<script src="https://checkout.flutterwave.com/v3.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const depositModal = document.getElementById('depositModal');
    const transferModal = document.getElementById('transferModal');
    const withdrawModal = document.getElementById('withdrawModal');
    const payBtn = document.getElementById('pay-btn');
    const confirmationModal = document.getElementById('confirmationModal');
    const confirmationTitle = document.getElementById('confirmation-title');
    const confirmationText = document.getElementById('confirmation-text');
    const confirmActionBtn = document.getElementById('confirm-action-btn');
    let formToSubmit = null;

    if (payBtn) {
        payBtn.addEventListener('click', function(e) {
            e.preventDefault();
            const amount = document.getElementById('amount').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;
            }

            const txRef = 'wallet_' + Date.now();

            FlutterwaveCheckout({
                public_key: publicKey,
                tx_ref: txRef,
                amount: 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: {
                    user_id: <?php echo $user_id; ?>,
                    payment_context: 'wallet_deposit'
                },
                customizations: {
                    title: "Wallet Deposit",
                    description: "Add funds to your 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: 'wallet_deposit'
                        })
                    })
                    .then(response => response.json())
                    .then(result => {
                        window.location.href = result.redirect_url || 'wallet.php';
                    });
                },
                onclose: function() {}
            });
        });
    }

    window.openDepositModal = function() { depositModal.classList.add('show'); }
    window.closeDepositModal = function() { depositModal.classList.remove('show'); }
    window.openTransferModal = function() { transferModal.classList.add('show'); }
    window.closeTransferModal = function() { transferModal.classList.remove('show'); }
    window.openWithdrawModal = function() { withdrawModal.classList.add('show'); }
    window.closeWithdrawModal = function() { withdrawModal.classList.remove('show'); }

    function openConfirmationModal(title, text, formId) {
        if (confirmationTitle) confirmationTitle.textContent = title;
        if (confirmationText) confirmationText.textContent = text;
        formToSubmit = document.getElementById(formId);
        if (confirmationModal) confirmationModal.classList.add('show');
    }

    window.closeConfirmationModal = function() {
        if (confirmationModal) confirmationModal.classList.remove('show');
        formToSubmit = null;
    }

    const submitTransferBtn = document.getElementById('submit-transfer-btn');
    if (submitTransferBtn) {
        submitTransferBtn.addEventListener('click', function() {
            const amount = document.getElementById('transfer_amount').value;
            const recipient = document.getElementById('recipient_email').value;
            if (!amount || !recipient || amount <= 0) {
                showToast('Please fill in a valid recipient and amount.', 'error');
                return;
            }
            openConfirmationModal(
                'Confirm Transfer', 
                `Are you sure you want to transfer <?php echo $currency_symbol; ?>${amount} to ${recipient}?`,
                'transfer-form'
            );
        });
    }

    const submitWithdrawBtn = document.getElementById('submit-withdraw-btn');
    if (submitWithdrawBtn) {
        submitWithdrawBtn.addEventListener('click', function() {
            const amount = document.getElementById('withdraw_amount').value;
            const details = document.getElementById('withdraw_details').value;
            if (!amount || amount <= 0 || !details) {
                showToast('Please enter a valid amount and withdrawal details.', 'error');
                return;
            }
            openConfirmationModal(
                'Confirm Withdrawal',
                `Are you sure you want to request a withdrawal of <?php echo $currency_symbol; ?>${amount}?`,
                'withdraw-form'
            );
        });
    }

    if (confirmActionBtn) {
        confirmActionBtn.addEventListener('click', function() {
            if (formToSubmit) {
                formToSubmit.submit();
            }
            closeConfirmationModal();
        });
    }

    window.onclick = function(event) {
        if (event.target == depositModal) closeDepositModal();
        if (event.target == transferModal) closeTransferModal();
        if (event.target == withdrawModal) closeWithdrawModal();
        if (event.target == confirmationModal) closeConfirmationModal();
    }

    const toastContainer = document.getElementById('toast-container');
    function showToast(message, type = 'success') {
        if (!toastContainer) return;
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`;
        
        let icon = '';
        if (type === 'success') icon = '<i class="fa-solid fa-check-circle" style="margin-right: 10px;"></i>';
        if (type === 'error') icon = '<i class="fa-solid fa-circle-exclamation" style="margin-right: 10px;"></i>';
        if (type === 'info') icon = '<i class="fa-solid fa-info-circle" style="margin-right: 10px;"></i>';
        
        toast.innerHTML = icon + message;
        toastContainer.appendChild(toast);
        
        setTimeout(() => {
            toast.classList.add('hide');
            toast.addEventListener('transitionend', () => toast.remove());
        }, 3000);
    }

    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.has('error')) {
        showToast(urlParams.get('error'), 'error');
        window.history.replaceState({}, document.title, window.location.pathname);
    }
    if (urlParams.has('status') && urlParams.get('status') === 'success' && urlParams.has('msg')) {
        showToast(urlParams.get('msg'), 'success');
        window.history.replaceState({}, document.title, window.location.pathname);
    }
});
</script>

<style>
    .wallet-hero { background: linear-gradient(135deg, var(--primary-color, #3498db) 0%, var(--secondary-color, #2c3e50) 100%); 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-balance-card { background: rgba(255,255,255,0.1); border: 1px solid rgba(255,255,255,0.2); margin-top: 2rem; padding: 2rem; border-radius: 15px; text-align: center; }
    .balance-label { display: block; font-size: 1rem; opacity: 0.8; margin-bottom: 10px; }
    .balance-value { display: block; font-size: 3.5rem; font-weight: 800; line-height: 1; margin-bottom: 25px; }
    .wallet-actions { display: flex; justify-content: center; gap: 15px; flex-wrap: wrap; }
    .btn-hero { background: white; color: var(--primary-color); border: none; }
    .btn-hero:hover { background: #f0f0f0; }
    .btn-hero-secondary { background: rgba(255,255,255,0.2); color: white; border: 1px solid rgba(255,255,255,0.3); }
    .btn-hero-secondary:hover { background: rgba(255,255,255,0.3); }

    .text-success { color: #27ae60; font-weight: 700; }
    .text-danger { color: #e74c3c; font-weight: 700; }
    
    .badge { padding: 4px 10px; border-radius: 20px; font-size: 0.75rem; text-transform: uppercase; font-weight: 700; letter-spacing: 0.5px; }
    .badge-deposit { background: #e8f5e9; color: #27ae60; }
    .badge-withdrawal { background: #fdecea; color: #c0392b; }
    .badge-payment { background: #f3f4f6; color: #7f8c8d; }
    .badge-transfer_in { background: #e8f5e9; color: #27ae60; }
    .badge-transfer_out { background: #fdecea; color: #c0392b; }

    /* Toast Notifications */
    #toast-container { position: fixed; bottom: 20px; right: 20px; z-index: 9999; }
    .toast { background: white; padding: 15px 20px; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.15); margin-bottom: 10px; display: flex; align-items: center; animation: slideInUp 0.3s ease-out forwards; border-left: 4px solid #333; min-width: 250px; }
    .toast.hide { animation: slideOutDown 0.3s ease-in forwards; }
    .toast-success { border-left-color: #27ae60; }
    .toast-error { border-left-color: #e74c3c; }
    .toast-info { border-left-color: #3498db; }

    @keyframes slideInUp {
        from { transform: translateY(100%); opacity: 0; }
        to { transform: translateY(0); opacity: 1; }
    }
    @keyframes slideOutDown {
        from { transform: translateY(0); opacity: 1; }
        to { transform: translateY(100%); opacity: 0; }
    }

    /* Transparent Header Override */
    header {
        background: transparent !important;
        box-shadow: none !important;
        position: absolute !important;
        width: 100%;
        top: 0;
        z-index: 1000;
    }
</style>

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