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

<!-- Normal Sub Header -->
<?php include 'template-parts/sub-header-user.php'; ?>

<div class="uk-container">

    <!-- Page Header -->
    <div class="page-header uk-margin-medium-bottom">
        <div class="uk-grid uk-grid-small" uk-grid>
            <div class="uk-width-expand@s">
                <div class="header-left uk-flex uk-flex-middle gap-16">
                    <div class="header-icon">
                        <span uk-icon="icon: text; ratio: 1.4" class="uk-icon"></span>
                    </div>
                    <div>
                        <h1 class="header-title">Transaction Log</h1>
                        <p class="header-subtitle uk-margin-remove">View your complete transaction history</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Filter Section for Transactions -->
    <div class="filter-section uk-margin-small-bottom">
        <div class="filter-grid uk-grid uk-grid-small uk-flex-bottom" uk-grid>
            <div class="uk-width-expand@s">
                <div class="uk-grid uk-grid-small uk-child-width-1-3@s" uk-grid>
                    <div class="filter-group">
                        <label class="form-label" for="typeFilter">Transaction Type</label>
                        <select class="uk-select" id="typeFilter">
                            <option value="">All Transactions</option>
                            <option value="deposit">Deposits</option>
                            <option value="withdraw">Withdrawals</option>
                            <option value="payment">Payments</option>
                            <option value="refund">Refunds</option>
                        </select>
                    </div>

                    <div class="filter-group">
                        <label class="form-label" for="dateFrom">Date From</label>
                        <input type="date" class="uk-input" id="dateFrom">
                    </div>

                    <div class="filter-group">
                        <label class="form-label" for="dateTo">Date To</label>
                        <input type="date" class="uk-input" id="dateTo">
                    </div>
                </div>
            </div>

            <div class="uk-width-auto@s">
                <div class="filter-group">
                    <button
                        class="btn-filter uk-button uk-button-secondary uk-width-1-1 uk-flex uk-flex-middle uk-flex-center gap-8"
                        onclick="applyFilters()">
                        <span uk-icon="icon: filter; ratio: .7" class="uk-icon"></span>
                        <span>Filter</span>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Transactions List -->
    <div class="checkout-card">
        <div id="transactionsList">
            <!-- Transaction items will be populated here -->
        </div>
    </div>

</div><!-- .uk-container -->

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

<script>
    // Sample transaction data
    const transactions = [{
            id: 'TXN-2024-001',
            type: 'deposit',
            amount: 200,
            description: 'Wallet top-up',
            status: 'completed',
            date: '2024-12-12T14:30:00Z',
            paymentMethod: 'visa',
            paymentDetails: 'Visa ••••• 4532'
        },

        {
            id: 'TXN-2024-005',
            type: 'deposit',
            amount: 500,
            description: 'Wallet top-up',
            status: 'completed',
            date: '2024-12-08T13:10:00Z',
            paymentMethod: 'mada',
            paymentDetails: 'MADA ••••• 7890'
        },
        {
            id: 'TXN-2024-006',
            type: 'payment',
            amount: -220,
            description: 'Session payment - Sara Mohammed',
            status: 'completed',
            date: '2024-12-07T11:30:00Z',
            paymentMethod: 'mastercard',
            paymentDetails: 'Mastercard ••••• 1234',
            orderReference: '#CS-2024-001240'
        },
        {
            id: 'TXN-2024-007',
            type: 'payment',
            amount: -150,
            description: 'Session payment - Omar Hassan',
            status: 'failed',
            date: '2024-12-06T15:20:00Z',
            paymentMethod: 'visa',
            paymentDetails: 'Visa ••••• 9876',
            orderReference: '#CS-2024-001238'
        },
        {
            id: 'TXN-2024-008',
            type: 'deposit',
            amount: 100,
            description: 'Wallet top-up',
            status: 'completed',
            date: '2024-12-05T12:45:00Z',
            paymentMethod: 'tabby',
            paymentDetails: 'Pay in 4 installments'
        },
        {
            id: 'TXN-2024-008',
            type: 'deposit',
            amount: 100,
            description: 'Wallet top-up',
            status: 'completed',
            date: '2024-12-05T12:45:00Z',
            paymentMethod: 'tamara',
            paymentDetails: 'Pay in 4 installments'
        }
    ];

    let filteredTransactions = [...transactions];

    // Payment method configurations
    const paymentMethodConfig = {
        visa: {
            image: 'assets/images/payment/visa.jpg',
            title: 'Visa',
            subtitle: 'Credit or Debit Card'
        },
        mastercard: {
            image: 'assets/images/payment/mastercard.jpg',
            title: 'Mastercard',
            subtitle: 'Credit or Debit Card'
        },
        mada: {
            image: 'assets/images/payment/mada.jpg',
            title: 'MADA',
            subtitle: 'Saudi Payments Network'
        },
        tabby: {
            image: 'assets/images/payment/tabby.jpg',
            title: 'Tabby',
            subtitle: 'Pay in 4 installments'
        },
        tamara: {
            image: 'assets/images/payment/tamara.jpg',
            title: 'Tamara',
            subtitle: 'Buy now, pay later'
        },
        wallet: {
            image: 'assets/images/payment/wallet.svg',
            title: 'Wallet Balance',
            subtitle: 'Internal wallet'
        },
        bank: {
            image: 'assets/images/payment/bank.svg',
            title: 'Bank Transfer',
            subtitle: 'Direct bank transfer'
        }
    };

    // Transaction type configurations
    const transactionTypeConfig = {
        deposit: {
            title: 'Deposit',
            class: 'positive'
        },
        withdraw: {
            title: 'Withdrawal',
            class: 'negative'
        },
        payment: {
            title: 'Payment',
            class: 'negative'
        },
        refund: {
            title: 'Refund',
            class: 'positive'
        }
    };

    // Format date
    function formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('en-US', {
            year: 'numeric',
            month: 'short',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        });
    }

    // Format amount
    function formatAmount(amount) {
        const isPositive = amount > 0;
        const formattedAmount = Math.abs(amount).toFixed(2);
        return {
            display: `${isPositive ? '+' : ''}${formattedAmount} SAR`,
            class: isPositive ? 'positive' : 'negative'
        };
    }

    // Get status badge
    function getStatusBadge(status) {
        return `<span class="transaction-status status-${status}">${status.charAt(0).toUpperCase() + status.slice(1)}</span>`;
    }

    // Render transactions in payment method style
    function renderTransactions(transactionsToRender = filteredTransactions) {
        const container = document.getElementById('transactionsList');

        if (transactionsToRender.length === 0) {
            container.innerHTML = `
                <div class="empty-state uk-text-center uk-margin-large">
                    <div class="empty-icon uk-margin-bottom">
                        <span uk-icon="icon: database; ratio: 3" class="uk-icon"></span>
                    </div>
                    <div class="empty-title uk-h3">No transactions found</div>
                    <div class="empty-description">Try adjusting your filters</div>
                </div>
            `;
            return;
        }

        container.innerHTML = transactionsToRender.map((transaction, index) => {
            const paymentConfig = paymentMethodConfig[transaction.paymentMethod] || paymentMethodConfig.wallet;
            const typeConfig = transactionTypeConfig[transaction.type];
            const amount = formatAmount(transaction.amount);
            const statusBadge = getStatusBadge(transaction.status);
            const isLast = index === transactionsToRender.length - 1;

            return `
                <div class="payment-method${isLast ? ' uk-margin-remove-bottom' : ''}" onclick="showTransactionDetails('${transaction.id}')" style="cursor: pointer;">
                    <div class="payment-icon">
                        <img src="${paymentConfig.image}" alt="${paymentConfig.title}">
                    </div>
                    <div class="payment-info">
                        <h4>${typeConfig.title} - ${paymentConfig.title}</h4>
                        <p>${transaction.description}</p>
                        <div class="uk-text-meta uk-margin-small-top">
                            ${formatDate(transaction.date)}
                            ${transaction.paymentDetails ? ` • ${transaction.paymentDetails}` : ''}
                            ${transaction.orderReference ? ` • ${transaction.orderReference}` : ''}
                        </div>
                    </div>
                    <div class="uk-margin-left-auto uk-text-right">
                        <div class="transaction-amount ${amount.class} uk-text-bold">
                            ${amount.display}
                        </div>
                        <div class="uk-margin-small-top">
                            ${statusBadge}
                        </div>
                    </div>
                </div>
            `;
        }).join('');
    }

    // Apply filters
    function applyFilters() {
        const typeFilter = document.getElementById('typeFilter').value;
        const dateFrom = document.getElementById('dateFrom').value;
        const dateTo = document.getElementById('dateTo').value;

        filteredTransactions = transactions.filter(transaction => {
            // Type filter
            if (typeFilter && transaction.type !== typeFilter) {
                return false;
            }

            // Date filters
            const transactionDate = new Date(transaction.date);

            if (dateFrom) {
                const fromDate = new Date(dateFrom);
                if (transactionDate < fromDate) {
                    return false;
                }
            }

            if (dateTo) {
                const toDate = new Date(dateTo + 'T23:59:59');
                if (transactionDate > toDate) {
                    return false;
                }
            }

            return true;
        });

        renderTransactions(filteredTransactions);

        UIkit.notification({
            message: `Found ${filteredTransactions.length} transactions`,
            status: 'success',
            pos: 'top-center',
            timeout: 2000
        });
    }

    // Show transaction details
    function showTransactionDetails(transactionId) {
        const transaction = transactions.find(t => t.id === transactionId);
        if (!transaction) return;

        const paymentConfig = paymentMethodConfig[transaction.paymentMethod] || paymentMethodConfig.wallet;
        const typeConfig = transactionTypeConfig[transaction.type];
        const amount = formatAmount(transaction.amount);
        const statusBadge = getStatusBadge(transaction.status);

        let detailsHTML = `
            <div class="uk-text-center uk-margin-bottom">
                <div class="payment-icon uk-margin-auto uk-margin-bottom" style="width: 80px; height: 80px;">
                    <img src="${paymentConfig.image}" alt="${paymentConfig.title}" style="width: 100%; height: 100%; object-fit: contain;">
                </div>
                <h3>${typeConfig.title}</h3>
                <div class="transaction-amount ${amount.class}" style="font-size: 2rem; margin: 1rem 0;">
                    ${amount.display}
                </div>
                <div>${statusBadge}</div>
            </div>
            
            <div class="uk-grid-small" uk-grid>
                <div class="uk-width-1-3@s"><strong>Transaction ID:</strong></div>
                <div class="uk-width-2-3@s">${transaction.id}</div>
                
                <div class="uk-width-1-3@s"><strong>Date:</strong></div>
                <div class="uk-width-2-3@s">${formatDate(transaction.date)}</div>
                
                <div class="uk-width-1-3@s"><strong>Description:</strong></div>
                <div class="uk-width-2-3@s">${transaction.description}</div>
                
                <div class="uk-width-1-3@s"><strong>Payment Method:</strong></div>
                <div class="uk-width-2-3@s">${paymentConfig.title}</div>
        `;

        if (transaction.paymentDetails) {
            detailsHTML += `
                <div class="uk-width-1-3@s"><strong>Payment Details:</strong></div>
                <div class="uk-width-2-3@s">${transaction.paymentDetails}</div>
            `;
        }

        if (transaction.orderReference) {
            detailsHTML += `
                <div class="uk-width-1-3@s"><strong>Order Reference:</strong></div>
                <div class="uk-width-2-3@s">${transaction.orderReference}</div>
            `;
        }

        if (transaction.bankReference) {
            detailsHTML += `
                <div class="uk-width-1-3@s"><strong>Bank Reference:</strong></div>
                <div class="uk-width-2-3@s">${transaction.bankReference}</div>
            `;
        }

        detailsHTML += '</div>';

        UIkit.modal.dialog(detailsHTML, {
            bgClose: true,
            escClose: true,
            labels: {
                Ok: 'Close'
            }
        });
    }

    // Initialize page
    document.addEventListener('DOMContentLoaded', function() {
        // Set default date range (last 30 days)
        const today = new Date();
        const thirtyDaysAgo = new Date(today.getTime() - (30 * 24 * 60 * 60 * 1000));

        document.getElementById('dateTo').value = today.toISOString().split('T')[0];
        document.getElementById('dateFrom').value = thirtyDaysAgo.toISOString().split('T')[0];

        // Render initial transactions
        renderTransactions();
    });
</script>