<?php include 'header.php'; ?>

<?php include 'template-parts/sub-header-trainer.php'; ?>

<div class="uk-container">
    <div class="uk-grid uk-grid-medium" uk-grid>

        <div class="uk-width-2-6@m uk-visible@m">
            <div class="sidebar-sticky" uk-sticky="offset: 20; bottom: true">
                <?php include 'trainer-sidebar.php'; ?>
            </div>
        </div>

        <div class="uk-width-expand@m">

            <div class="profile-container">

                <div class="uk-grid" uk-grid>

                    <div class="uk-width-expand@s">
                        <div class="profile-header">
                            <h2 class="uk-heading-divider">My Wallet</h2>
                            <p class="uk-margin-remove">Manage your earnings, view balance, and withdraw funds.</p>
                        </div>
                    </div>

                    <div class="uk-width-auto@s">
                        <div class="uk-flex uk-flex-right gap-8">
                            <button class="uk-button uk-button-small uk-button-primary" onclick="openWithdrawModal()">
                                Withdraw Funds
                            </button>
                            <button class="uk-button uk-button-small uk-button-default" onclick="refreshBalance()">
                                <span uk-icon="icon: refresh; ratio: 0.6"></span>
                            </button>
                        </div>
                    </div>
                </div>

                <div class="uk-grid uk-grid-match uk-grid-medium uk-child-width-1-1 uk-child-width-1-3@m" uk-grid>

                    <div>
                        <div class="cart-item-small">
                            <h3 class="cis-title uk-margin-remove">Current Balance</h3>
                            <div class="cis-amount" id="currentBalance">2,450 SAR</div>
                            <p class="cis-text">Available for withdrawal</p>
                        </div>
                    </div>

                    <div>
                        <div class="cart-item-small">
                            <h3 class="cis-title uk-margin-remove">Pending Earnings</h3>
                            <div class="cis-amount uk-text-warning">850 SAR</div>
                            <p class="cis-text">From recent sessions</p>
                        </div>
                    </div>

                    <div>
                        <div class="cart-item-small">
                            <h3 class="cis-title uk-margin-remove">Total Withdrawn</h3>
                            <div class="cis-amount uk-text-success">15,200 SAR</div>
                            <p class="cis-text">All time withdrawals</p>
                        </div>
                    </div>

                </div>

                <div class="uk-margin-medium-top">

                    <div>
                        <h3 class="uk-h5 f600 uk-margin-remove">Recent Transactions</h3>
                        <p class="uk-margin-small-top">Your latest earnings and withdrawals</p>
                    </div>

                    <div class="uk-overflow-auto">
                        <table class="uk-table uk-table-hover uk-table uk-table-responsive uk-table-divider">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Type</th>
                                    <th>Description</th>
                                    <th>Amount</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>Aug 20, 2025</td>
                                    <td><span class="uk-label uk-label-success">Earning</span></td>
                                    <td>Session with Sarah Ahmad</td>
                                    <td class="uk-text-bold">+400 SAR</td>
                                    <td><span class="session-status completed uk-flex gap-4"><span uk-icon="icon: completed; ratio: .6" class="uk-icon" aria-hidden="true"></span>Completed</span></span></td>
                                </tr>
                                <tr>
                                    <td>Aug 18, 2025</td>
                                    <td><span class="uk-label uk-label-success">Earning</span></td>
                                    <td>Session with Ahmad Rahman</td>
                                    <td class="uk-text-bold">+400 SAR</td>
                                    <td><span class="session-status completed uk-flex gap-4"><span uk-icon="icon: completed; ratio: .6" class="uk-icon" aria-hidden="true"></span>Completed</span></span></td>
                                </tr>

                                <tr>
                                    <td>Aug 15, 2025</td>
                                    <td><span class="uk-label uk-label-primary">Withdrawal</span></td>
                                    <td>Bank Transfer - Al Rajhi Bank</td>
                                    <td class="uk-text-bold">-1,500 SAR</td>
                                    <td><span class="session-status upcoming uk-flex gap-4"><span uk-icon="icon: upcoming; ratio: .6" class="uk-icon" aria-hidden="true"></span>Processed</span></span></td>
                                </tr>

                                <tr>
                                    <td>Aug 14, 2025</td>
                                    <td><span class="uk-label uk-label-success">Earning</span></td>
                                    <td>Session with Fatima Hassan</td>
                                    <td class="uk-text-bold">+280 SAR</td>
                                    <td><span class="session-status completed uk-flex gap-4"><span uk-icon="icon: completed; ratio: .6" class="uk-icon" aria-hidden="true"></span>Completed</span></span></td>
                                </tr>
                                <tr>
                                    <td>Aug 12, 2025</td>
                                    <td><span class="uk-label uk-label-success">Earning</span></td>
                                    <td>Session with Mohammed Ali</td>
                                    <td class="uk-text-bold">+500 SAR</td>
                                    <td><span class="session-status completed uk-flex gap-4"><span uk-icon="icon: completed; ratio: .6" class="uk-icon" aria-hidden="true"></span>Completed</span></span></td>
                                </tr>

                                <tr>
                                    <td>Aug 10, 2025</td>
                                    <td><span class="uk-label uk-label-primary">Withdrawal</span></td>
                                    <td>Bank Transfer - Al Rajhi Bank</td>
                                    <td class="uk-text-bold">-800 SAR</td>
                                    <td><span class="session-status upcoming uk-flex gap-4"><span uk-icon="icon: upcoming; ratio: .6" class="uk-icon" aria-hidden="true"></span>Processed</span></span></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <div class="uk-margin-medium-top">
                        <button class="uk-button uk-button-default" onclick="loadMoreTransactions()">
                            Load More Transactions
                        </button>
                    </div>
                </div>

            </div>

        </div>

    </div></div><div id="withdrawModal" uk-modal>
    <div class="uk-modal-dialog uk-modal-body">
        <button class="uk-modal-close-default" type="button" uk-close></button>
        <h2 class="uk-modal-title">Withdraw Funds</h2>

        <form id="withdrawForm">

            <div class="uk-margin">
                <div class="uk-alert uk-alert-primary uk-text-center">
                    <h4 class="uk-margin-remove">Available Balance</h4>
                    <div class="uk-text-large uk-text-bold" id="modalCurrentBalance">2,450 SAR</div>
                </div>
            </div>

            <div class="uk-margin">
                <label class="form-label" for="withdrawAmount">Withdrawal Amount (SAR)</label>
                <div class="uk-inline uk-width-1-1">
                    <input type="number" class="uk-input" id="withdrawAmount" placeholder="Enter amount" min="100" step="1" required>
                </div>
                <div class="uk-text-small uk-text-muted uk-margin-small-top">
                    Minimum withdrawal: 100 SAR | Maximum: 2,450 SAR
                </div>
            </div>

            <div class="uk-margin">
                <div class="uk-alert uk-alert-warning">
                    <h5 class="uk-margin-remove-bottom">Processing Information</h5>
                    <ul class="uk-list uk-margin-small-top uk-margin-remove-bottom">
                        <li>• Processing time: 1-3 business days</li>
                        <li>• No processing fees applied</li>
                        <li>• You'll receive email confirmation</li>
                    </ul>
                </div>
            </div>

            <div class="uk-margin" id="withdrawalSummary" style="display: none;">
                <div class="uk-card ">
                    <h5 class="uk-card-title uk-margin-remove-bottom">Withdrawal Summary</h5>
                    <dl class="uk-description-list uk-description-list-divider uk-margin-small-top">
                        <dt>Amount to withdraw</dt>
                        <dd id="summaryAmount" class="uk-text-bold">0 SAR</dd>
                        <dt>Processing fee</dt>
                        <dd class="uk-text-success">Free</dd>
                        <dt>You will receive</dt>
                        <dd id="summaryTotal" class="uk-text-bold uk-text-primary">0 SAR</dd>
                    </dl>
                </div>
            </div>

            <div class="uk-margin uk-text-right">
                <button class="uk-button uk-button-default uk-modal-close uk-margin-small-right" type="button">Cancel</button>
                <button class="uk-button uk-button-primary" type="submit">
                    Withdraw Funds
                </button>
            </div>

        </form>
    </div>
</div>

<script>
    // Current balance value
    let currentBalance = 2450;

    // Open withdraw modal
    function openWithdrawModal() {
        // Update balance in modal
        document.getElementById('modalCurrentBalance').textContent = currentBalance.toLocaleString() + ' SAR';
        UIkit.modal('#withdrawModal').show();
    }

    // Refresh balance
    function refreshBalance() {
        UIkit.notification({
            message: 'Refreshing balance...',
            status: 'primary',
            pos: 'top-center',
            timeout: 2000
        });

        // Simulate API call
        setTimeout(() => {
            UIkit.notification({
                message: 'Balance updated successfully!',
                status: 'success',
                pos: 'top-center',
                timeout: 3000
            });
        }, 1500);
    }

    // Update withdrawal summary when amount changes
    document.getElementById('withdrawAmount').addEventListener('input', function() {
        const amount = parseFloat(this.value) || 0;
        const summaryDiv = document.getElementById('withdrawalSummary');

        if (amount > 0) {
            document.getElementById('summaryAmount').textContent = amount.toLocaleString() + ' SAR';
            document.getElementById('summaryTotal').textContent = amount.toLocaleString() + ' SAR';
            summaryDiv.style.display = 'block';
        } else {
            summaryDiv.style.display = 'none';
        }
    });

    // Validate withdrawal amount
    document.getElementById('withdrawAmount').addEventListener('blur', function() {
        const amount = parseFloat(this.value) || 0;

        if (amount < 100 && amount > 0) {
            UIkit.notification({
                message: 'Minimum withdrawal amount is 100 SAR',
                status: 'warning',
                pos: 'top-center',
                timeout: 3000
            });
            this.focus();
        } else if (amount > currentBalance) {
            UIkit.notification({
                message: 'Amount exceeds available balance',
                status: 'warning',
                pos: 'top-center',
                timeout: 3000
            });
            this.value = currentBalance;
            this.focus();
        }
    });

    // Handle withdrawal form submission
    document.getElementById('withdrawForm').addEventListener('submit', function(e) {
        e.preventDefault();

        const amount = parseFloat(document.getElementById('withdrawAmount').value);

        // Validation
        if (!amount || amount < 100) {
            UIkit.notification({
                message: 'Please enter a valid withdrawal amount (minimum 100 SAR)',
                status: 'warning',
                pos: 'top-center',
                timeout: 3000
            });
            return;
        }

        if (amount > currentBalance) {
            UIkit.notification({
                message: 'Amount exceeds available balance',
                status: 'warning',
                pos: 'top-center',
                timeout: 3000
            });
            return;
        }

        // Show processing notification
        UIkit.notification({
            message: 'Processing withdrawal request...',
            status: 'primary',
            pos: 'top-center',
            timeout: 3000
        });

        // Simulate API call
        setTimeout(() => {
            // Update balance
            currentBalance -= amount;
            document.getElementById('currentBalance').textContent = currentBalance.toLocaleString() + ' SAR';
            document.getElementById('modalCurrentBalance').textContent = currentBalance.toLocaleString() + ' SAR';

            // Add transaction to table
            addTransactionToTable('withdrawal', amount, 'processing');

            // Close modal and reset form
            UIkit.modal('#withdrawModal').hide();
            document.getElementById('withdrawForm').reset();
            document.getElementById('withdrawalSummary').style.display = 'none';

            // Success notification
            UIkit.notification({
                message: `Withdrawal request for ${amount.toLocaleString()} SAR submitted successfully! You'll receive confirmation via email.`,
                status: 'success',
                pos: 'top-center',
                timeout: 5000
            });

        }, 2000);
    });

    // Add transaction to table
    function addTransactionToTable(type, amount, status) {
        const tbody = document.querySelector('.uk-table tbody');
        const today = new Date().toLocaleDateString('en-GB', {
            day: 'numeric',
            month: 'short',
            year: 'numeric'
        });

        const row = document.createElement('tr');

        if (type === 'withdrawal') {
            row.innerHTML = `
            <td>${today}</td>
            <td><span class="uk-label uk-label-primary">Withdrawal</span></td>
            <td>Bank Transfer - (Account removed)</td>
            <td class="uk-text-primary uk-text-bold">-${amount.toLocaleString()} SAR</td>
            <td><span class="session-status upcoming uk-flex gap-4"><span uk-icon="icon: upcoming; ratio: .6" class="uk-icon" aria-hidden="true"></span>Upcoming</span></span></td>
        `;
        } else {
            row.innerHTML = `
            <td>${today}</td>
            <td><span class="uk-label uk-label-success">Earning</span></td>
            <td>Session payment</td>
            <td class="uk-text-success uk-text-bold">+${amount.toLocaleString()} SAR</td>
            <td><span class="session-status completed uk-flex gap-4"><span uk-icon="icon: completed; ratio: .6" class="uk-icon" aria-hidden="true"></span>Completed</span></span></td>
        `;
        }

        // Insert at the beginning
        tbody.insertBefore(row, tbody.firstChild);
    }

    // Load more transactions
    function loadMoreTransactions() {
        UIkit.notification({
            message: 'Loading more transactions...',
            status: 'primary',
            pos: 'bottom-center',
            timeout: 2000
        });

        // Simulate loading more data
        setTimeout(() => {
            UIkit.notification({
                message: 'No more transactions to load',
                status: 'warning',
                pos: 'bottom-center',
                timeout: 2000
            });
        }, 1500);
    }

    // Initialize tooltips and other UI components
    document.addEventListener('DOMContentLoaded', function() {
        // Any initialization code can go here
        console.log('Wallet dashboard loaded');
    });

    // Auto-refresh balance every 30 seconds (optional)
    setInterval(function() {
        // This would typically make an API call to check for new earnings
        // For demo purposes, we'll just log it
        console.log('Auto-checking for balance updates...');
    }, 30000);

    // Format currency inputs
    document.getElementById('withdrawAmount').addEventListener('input', function() {
        // Remove any non-digit characters except decimal point
        this.value = this.value.replace(/[^0-9.]/g, '');

        // Ensure only one decimal point
        const parts = this.value.split('.');
        if (parts.length > 2) {
            this.value = parts[0] + '.' + parts.slice(1).join('');
        }

        // Limit to 2 decimal places
        if (parts[1] && parts[1].length > 2) {
            this.value = parts[0] + '.' + parts[1].substring(0, 2);
        }
    });

    // Prevent negative values
    document.getElementById('withdrawAmount').addEventListener('keydown', function(e) {
        // Prevent minus sign
        if (e.key === '-' || e.key === '+') {
            e.preventDefault();
        }
    });
</script>

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