<?php
// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}
?>

<!-- Immediate tab initialization -->
<script type="text/javascript">
    // Run immediately to ensure payment tab is visible before anything else
    (function() {
        document.addEventListener('DOMContentLoaded', function() {
            // Force payment tab to be visible as soon as DOM is ready
            var paymentTab = document.getElementById('payment-report-content');
            if (paymentTab) {
                paymentTab.style.display = 'block';
                paymentTab.classList.remove('hidden');
                paymentTab.classList.add('block');
            }
            
            // Make sure payment button is active
            var paymentButton = document.getElementById('tab-payment-report');
            if (paymentButton) {
                paymentButton.classList.add('active-tab', 'border-indigo-500', 'text-indigo-600');
                paymentButton.classList.remove('border-transparent', 'text-gray-500', 'hover:text-gray-700', 'hover:border-gray-300');
            }
        });
    })();
</script>

<div class="p-8">
    <!-- Page Header -->
    <div class="ei-app-page-header bg-white border-b border-gray-200 px-6" style="margin-left: -2rem; margin-top: -2rem; padding-left:2rem; padding-right:2rem; margin-right: -2rem;">
        <div class="flex items-center justify-between">
            <div>
        <h1 class="text-2xl font-bold text-gray-900">Reports</h1>
                <p class="mt-1 text-sm text-gray-500">Comprehensive insights and analytics</p>
            </div>
            <div class="flex items-center space-x-3">
            <form method="get" action="<?php echo admin_url('admin.php'); ?>" class="flex space-x-2">
                <input type="hidden" name="page" value="easy-invoice-reports">
                <div class="flex items-center">
                    <label for="start_date" class="mr-2 text-sm font-medium text-gray-700">From:</label>
                    <input type="date" id="start_date" name="start_date" value="<?php echo esc_attr($start_date); ?>" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm transition-colors duration-200">
                </div>
                <div class="flex items-center">
                    <label for="end_date" class="mr-2 text-sm font-medium text-gray-700">To:</label>
                    <input type="date" id="end_date" name="end_date" value="<?php echo esc_attr($end_date); ?>" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm transition-colors duration-200">
                </div>
                <button type="submit" class="inline-flex items-center px-3 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                    <i class="fas fa-filter mr-1"></i> Filter
                </button>
            </form>
            <button type="button" id="export-report" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                <i class="fas fa-download mr-2"></i>
                Export Report
            </button>
            </div>
        </div>
    </div>

    <!-- Summary Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8 mt-8">
        <div class="bg-white rounded-lg shadow p-6 transition-transform duration-300 hover:shadow-md hover:-translate-y-1">
                <div class="flex items-center">
                <div class="rounded-full bg-indigo-100 p-3 mr-4">
                    <svg class="w-6 h-6 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                    </svg>
                    </div>
                <div>
                    <h3 class="text-sm font-medium text-gray-500">Total Revenue</h3>
                    <?php if (is_array($summary_stats['total_revenue']) && !empty($summary_stats['total_revenue'])): ?>
                        <div class="mt-1">
                            <?php 
                            $currency_count = count($summary_stats['total_revenue']);
                            foreach ($summary_stats['total_revenue'] as $index => $data): 
                                $is_last = $index === $currency_count - 1;
                                // Get currency code from the data array or use a fallback
                                $currency_code = isset($data['currency_code']) ? $data['currency_code'] : 'USD';
                            ?>
                                <div class="<?php echo $currency_count > 1 ? 'text-sm' : 'text-lg'; ?> font-bold text-gray-900 <?php echo !$is_last ? 'mb-1' : ''; ?>">
                                    <?php echo $data['symbol'] . number_format($data['amount'], 2); ?>
                                    <span class="text-xs font-normal text-gray-500"><?php echo strtoupper($currency_code ?? 'USD'); ?></span>
                    </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <p class="mt-1 text-lg font-bold text-gray-900">$0.00</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <div class="bg-white rounded-lg shadow p-6 transition-transform duration-300 hover:shadow-md hover:-translate-y-1">
                <div class="flex items-center">
                <div class="rounded-full bg-green-100 p-3 mr-4">
                    <svg class="w-6 h-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                    </svg>
                    </div>
                <div>
                    <h3 class="text-sm font-medium text-gray-500">Total Invoices</h3>
                    <p class="mt-1 text-2xl font-bold text-gray-900"><?php echo esc_html($summary_stats['total_invoices']); ?></p>
                </div>
            </div>
        </div>

        <div class="bg-white rounded-lg shadow p-6 transition-transform duration-300 hover:shadow-md hover:-translate-y-1">
                <div class="flex items-center">
                <div class="rounded-full bg-blue-100 p-3 mr-4">
                    <svg class="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 21V19C17 17.9391 16.5786 16.9217 15.8284 16.1716C15.0783 15.4214 14.0609 15 13 15H5C3.93913 15 2.92172 15.4214 2.17157 16.1716C1.42143 16.9217 1 17.9391 1 19V21" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        <circle cx="9" cy="7" r="4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        <path d="M23 21V19C23 18.1137 22.6485 17.2628 22.0237 16.6425C21.3989 16.0221 20.5471 15.6722 19.66 15.6722C18.7729 15.6722 17.9211 16.0221 17.2963 16.6425C16.6715 17.2628 16.32 18.1137 16.32 19V21" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        <path d="M16.32 11.6722C18.36 11.6722 20 10.0322 20 7.99219C20 5.95219 18.36 4.31219 16.32 4.31219" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                    </div>
                <div>
                    <h3 class="text-sm font-medium text-gray-500">Active Clients</h3>
                    <p class="mt-1 text-2xl font-bold text-gray-900"><?php echo esc_html($summary_stats['active_clients']); ?></p>
                </div>
            </div>
        </div>

        <div class="bg-white rounded-lg shadow p-6 transition-transform duration-300 hover:shadow-md hover:-translate-y-1">
                <div class="flex items-center">
                <div class="rounded-full bg-yellow-100 p-3 mr-4">
                    <svg class="w-6 h-6 text-yellow-600" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                    </svg>
                    </div>
                <div>
                    <h3 class="text-sm font-medium text-gray-500">Average Payment Time</h3>
                    <p class="mt-1 text-2xl font-bold text-gray-900"><?php echo esc_html($summary_stats['avg_payment_time']); ?> days</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Charts Section -->
    <div class="grid grid-cols-1 gap-5 lg:grid-cols-2 mb-8">
        <!-- Revenue Chart -->
        <div class="bg-white shadow rounded-lg p-6">
            <h2 class="text-lg font-medium text-gray-900 mb-4">Monthly Revenue</h2>
            <div class="h-64">
                <canvas id="revenue-chart"></canvas>
            </div>
        </div>

        <!-- Invoice Status Chart -->
        <div class="bg-white shadow rounded-lg p-6">
            <h2 class="text-lg font-medium text-gray-900 mb-4">Invoice Status</h2>
            <div class="h-64 flex items-center justify-center">
                <div class="w-48 h-48 relative">
                    <canvas id="status-chart"></canvas>
                </div>
                <div class="ml-8">
                    <?php
                    $statusColors = [
                        'Paid' => 'bg-green-500',
                        'Unpaid' => 'bg-yellow-500',
                        'Overdue' => 'bg-red-500',
                        'Draft' => 'bg-gray-500'
                    ];
                    
                    if (isset($invoice_status['percentages']) && isset($invoice_status['counts'])) {
                        foreach ($invoice_status['percentages'] as $status => $percentage) {
                            $color = isset($statusColors[ucfirst($status)]) ? $statusColors[ucfirst($status)] : 'bg-gray-500';
                            $count = isset($invoice_status['counts'][$status]) ? $invoice_status['counts'][$status] : 0;
                            echo '<div class="flex items-center mb-2">';
                            echo '<div class="w-4 h-4 rounded-full ' . esc_attr($color) . ' mr-2"></div>';
                            echo '<span class="text-sm text-gray-600">' . esc_html(ucfirst($status)) . ' (' . esc_html($percentage) . '% - ' . esc_html($count) . ')</span>';
                            echo '</div>';
                        }
                    }
                    ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Top Clients Table -->
    <div class="bg-white shadow rounded-lg mb-8">
        <div class="px-6 py-4 border-b border-gray-200">
            <h2 class="text-lg font-medium text-gray-900">Top Clients by Revenue</h2>
        </div>
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Client
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Total Amount
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Invoices
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Last Invoice
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Actions
                        </th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php if (!empty($top_clients)) : ?>
                        <?php foreach ($top_clients as $client): ?>
                        <tr class="hover:bg-gray-50">
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="flex items-center">
                                    <div class="flex-shrink-0 h-10 w-10">
                                        <?php 
                                        $gravatar_url = '';
                                        if (!empty($client['email'])) {
                                            $gravatar_url = get_avatar_url($client['email'], ['size' => 40, 'default' => 'mp']);
                                        }
                                        if ($gravatar_url) {
                                            echo '<img class="h-10 w-10 rounded-full object-cover" src="' . esc_url($gravatar_url) . '" alt="' . esc_attr($client['name']) . '" onerror="this.style.display=\'none\'; this.nextElementSibling.style.display=\'flex\';">';
                                        }
                                        ?>
                                        <div class="h-10 w-10 rounded-full bg-indigo-100 flex items-center justify-center" <?php echo $gravatar_url ? 'style="display: none;"' : ''; ?>>
                                            <span class="text-indigo-600 font-medium"><?php echo esc_html(substr($client['name'] ?? '', 0, 1)); ?></span>
                                        </div>
                                    </div>
                                    <div class="ml-4">
                                        <div class="text-sm font-medium text-gray-900"><?php echo esc_html($client['name']); ?></div>
                                        <div class="text-sm text-gray-500"><?php echo esc_html($client['email']); ?></div>
                                    </div>
                                </div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                <?php if (isset($client['total_amount']) && is_array($client['total_amount']) && !empty($client['total_amount'])): ?>
                                    <?php foreach ($client['total_amount'] as $currency => $currency_data): ?>
                                        <div>
                                            <?php echo $currency_data['symbol'] . number_format($currency_data['amount'], 2); ?>
                                            <span class="text-xs text-gray-500"><?php echo $currency; ?></span>
                                        </div>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    $0.00
                                <?php endif; ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                <?php echo esc_html($client['total_invoices']); ?> invoices
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                <?php echo !empty($client['last_invoice']) ? date('M d, Y', strtotime($client['last_invoice'])) : 'N/A'; ?>
                            </td>


                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                <a href="<?php echo esc_url(admin_url('admin.php?page=easy-invoice-client-view&client_id=' . $client['id'])); ?>" class="text-indigo-600 hover:text-indigo-900">View Client</a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="5" class="px-6 py-4 text-center text-gray-500">No client data available</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <!-- Detailed Reports Tabs -->
    <div class="bg-white shadow rounded-lg">
        <div class="border-b border-gray-200">
            <div class="flex items-center justify-between px-6 py-3">
                <h2 class="text-lg font-medium text-gray-900">Detailed Reports</h2>
                <div>
                    <button id="export-detailed-report" class="inline-flex items-center px-3 py-2 border border-transparent text-sm font-medium rounded-md text-indigo-700 bg-indigo-100 hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                        <i class="fas fa-download mr-2"></i> Export
                    </button>
                </div>
            </div>
            <nav class="flex -mb-px">
                <button id="tab-payment-report" class="tab-button active-tab w-1/2 py-4 px-1 text-center border-b-2 font-medium text-sm border-indigo-500 text-indigo-600">
                    Payment Report
                </button>
                <button id="tab-invoice-report" class="tab-button w-1/2 py-4 px-1 text-center border-b-2 font-medium text-sm border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300">
                    Invoice Report
                </button>
            </nav>
        </div>

        <!-- Payment Report Tab Content -->
        <div id="payment-report-content" class="tab-content block" style="display: block !important;">
            <div class="p-4 bg-gray-50 border-b">
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div class="bg-white p-4 rounded-md shadow-sm">
                        <div class="text-sm text-gray-500">Total Payments</div>
                        <div class="text-xl font-bold"><?php echo esc_html($payment_report['count']); ?></div>
                    </div>
                    <div class="bg-white p-4 rounded-md shadow-sm">
                        <div class="text-sm text-gray-500">Total Amount</div>
                        <div class="text-lg font-bold">
                            <?php 
                            // Calculate total amount from all payment methods and currencies
                            $total_amounts_by_currency = [];
                            if (!empty($payment_report['by_method'])) {
                                foreach ($payment_report['by_method'] as $method => $data) {
                                    if (isset($data['amounts_by_currency'])) {
                                        foreach ($data['amounts_by_currency'] as $currency => $currency_data) {
                                            if (!isset($total_amounts_by_currency[$currency])) {
                                                $total_amounts_by_currency[$currency] = [
                                                    'amount' => 0,
                                                    'symbol' => $currency_data['symbol']
                                                ];
                                            }
                                            $total_amounts_by_currency[$currency]['amount'] += $currency_data['amount'];
                                        }
                                    }
                                }
                            }
                            
                            if (!empty($total_amounts_by_currency)): ?>
                                <?php foreach ($total_amounts_by_currency as $currency => $data): ?>
                                    <div class="text-sm">
                                        <?php echo $data['symbol'] . number_format($data['amount'], 2); ?>
                                        <span class="text-xs text-gray-500"><?php echo $currency; ?></span>
                                    </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                $0.00
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="bg-white p-4 rounded-md shadow-sm">
                        <div class="text-sm text-gray-500">Average Payment</div>
                        <div class="text-lg font-bold">
                            <?php 
                            // Calculate average payments by currency
                            $average_amounts_by_currency = [];
                            $payment_count = $payment_report['count'];
                            
                            if (!empty($payment_report['by_method']) && $payment_count > 0) {
                                foreach ($payment_report['by_method'] as $method => $data) {
                                    if (isset($data['amounts_by_currency'])) {
                                        foreach ($data['amounts_by_currency'] as $currency => $currency_data) {
                                            if (!isset($average_amounts_by_currency[$currency])) {
                                                $average_amounts_by_currency[$currency] = [
                                                    'amount' => 0,
                                                    'symbol' => $currency_data['symbol']
                                                ];
                                            }
                                            $average_amounts_by_currency[$currency]['amount'] += $currency_data['amount'];
                                        }
                                    }
                                }
                                
                                // Calculate averages
                                foreach ($average_amounts_by_currency as $currency => $data) {
                                    $average_amounts_by_currency[$currency]['amount'] = $data['amount'] / $payment_count;
                                }
                            }
                            
                            if (!empty($average_amounts_by_currency)): ?>
                                <?php foreach ($average_amounts_by_currency as $currency => $data): ?>
                                    <div class="text-sm">
                                        <?php echo $data['symbol'] . number_format($data['amount'], 2); ?>
                                        <span class="text-xs text-gray-500">
                                            <?php 
                                            $display_currency = $currency;
                                            if ($display_currency === 'GLOBAL') {
                                                $display_currency = get_option('easy_invoice_currency_code', 'USD');
                                            }
                                            echo esc_html(strtoupper($display_currency));
                                            ?>
                                        </span>
                                    </div>
                                <?php endforeach; ?>
                            <?php elseif ($payment_count > 0): ?>
                                <span class="text-sm text-gray-500">No currency data</span>
                            <?php else: ?>
                                $0.00
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Payment Methods Chart -->
            <div class="p-4">
                <h3 class="text-md font-medium text-gray-700 mb-3">Payment Methods Distribution</h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div class="bg-white p-4 rounded-md shadow-sm">
                        <canvas id="payment-methods-chart" height="200"></canvas>
                    </div>
                    <div class="bg-white p-4 rounded-md shadow-sm">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead>
                                <tr>
                                    <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Method</th>
                                    <th class="px-3 py-2 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Count</th>
                                    <th class="px-3 py-2 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Amount</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php 
                                if (!empty($payment_report['by_method'])) :
                                    foreach ($payment_report['by_method'] as $method => $data) : 
                                ?>
                                <tr>
                                    <td class="px-3 py-2 whitespace-nowrap text-sm text-gray-900">
                                        <?php echo esc_html(ucfirst($method)); ?>
                                    </td>
                                    <td class="px-3 py-2 whitespace-nowrap text-sm text-right text-gray-500">
                                        <?php echo esc_html($data['count']); ?>
                                    </td>
                                    <td class="px-3 py-2 whitespace-nowrap text-sm text-right text-gray-900">
                                        <?php if (isset($data['amounts_by_currency']) && !empty($data['amounts_by_currency'])): ?>
                                            <?php foreach ($data['amounts_by_currency'] as $currency => $currency_data): ?>
                                                <div class="text-xs">
                                                    <?php echo $currency_data['symbol'] . number_format($currency_data['amount'], 2); ?>
                                                    <span class="text-xs text-gray-500"><?php echo $currency; ?></span>
                                                </div>
                                            <?php endforeach; ?>
                                        <?php else: ?>
                                            $0.00
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php 
                                    endforeach;
                                else: 
                                ?>
                                <tr>
                                    <td colspan="3" class="px-3 py-4 text-center text-sm text-gray-500">No payment method data available</td>
                                </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            
            <!-- Payments List -->
            <div class="p-4">
                <h3 class="text-md font-medium text-gray-700 mb-3">Recent Payments</h3>
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Date</th>
                                <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Invoice</th>
                                <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Amount</th>
                                <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Method</th>
                                <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Transaction ID</th>
                                <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <?php if (!empty($payment_report['payments'])) : ?>
                                <?php foreach ($payment_report['payments'] as $payment): ?>
                                <tr class="hover:bg-gray-50">
                                    <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                                        <?php echo date('M d, Y', strtotime($payment['date'])); ?>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap">
                                        <a href="<?php echo esc_url(admin_url('admin.php?page=easy-invoice&action=edit&id=' . $payment['invoice_id'])); ?>" class="text-indigo-600 hover:text-indigo-900 text-sm font-medium">
                                            <?php echo esc_html($payment['invoice_number']); ?>
                                        </a>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-900">
                                        <?php echo esc_html($payment['currency_symbol'] . number_format($payment['amount'], 2)); ?>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                                        <?php echo esc_html(ucfirst($payment['payment_method'])); ?>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap">
                                        <?php 
                                        $status_class = 'bg-gray-100 text-gray-800';
                                        if (in_array($payment['status'], ['completed', 'paid'])) {
                                            $status_class = 'bg-green-100 text-green-800';
                                        } elseif (in_array($payment['status'], ['pending', 'pending-bank', 'pending-cheque'])) {
                                            $status_class = 'bg-yellow-100 text-yellow-800';
                                        } elseif (in_array($payment['status'], ['failed', 'rejected'])) {
                                            $status_class = 'bg-red-100 text-red-800';
                                        }
                                        ?>
                                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full <?php echo esc_attr($status_class); ?>">
                                            <?php echo esc_html(ucfirst($payment['status'])); ?>
                                        </span>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                                        <?php echo esc_html($payment['transaction_id'] ?: esc_html__('—', 'easy-invoice')); ?>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap text-sm font-medium">
                                        <a href="<?php echo esc_url(admin_url('admin.php?page=easy-invoice-payments&action=view&id=' . $payment['id'])); ?>" class="text-indigo-600 hover:text-indigo-900">View</a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="7" class="px-4 py-4 text-center text-gray-500">No payment records found for the selected period</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Invoice Report Tab Content -->
        <div id="invoice-report-content" class="tab-content hidden" style="display: none;">
            <div class="p-4 bg-gray-50 border-b">
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div class="bg-white p-4 rounded-md shadow-sm">
                        <div class="text-sm text-gray-500">Total Invoices</div>
                        <div class="text-xl font-bold"><?php echo esc_html($invoice_report['count']); ?></div>
                    </div>
                    <div class="bg-white p-4 rounded-md shadow-sm">
                        <div class="text-sm text-gray-500">Total Amount</div>
                        <div class="text-lg font-bold">
                            <?php 
                            // Display total amounts by currency
                            if (isset($invoice_report['total_amounts_by_currency']) && !empty($invoice_report['total_amounts_by_currency'])): ?>
                                <?php foreach ($invoice_report['total_amounts_by_currency'] as $currency => $currency_data): ?>
                                    <div class="text-sm">
                                        <?php echo $currency_data['symbol'] . number_format($currency_data['amount'], 2); ?>
                                        <span class="text-xs text-gray-500">
                                            <?php 
                                            $display_currency = $currency;
                                            if ($display_currency === 'GLOBAL') {
                                                $display_currency = get_option('easy_invoice_currency_code', 'USD');
                                            }
                                            echo esc_html(strtoupper($display_currency));
                                            ?>
                                        </span>
                                    </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                $0.00
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="bg-white p-4 rounded-md shadow-sm">
                        <div class="text-sm text-gray-500">Average Invoice</div>
                        <div class="text-lg font-bold">
                            <?php 
                            // Calculate average amounts by currency
                            if (isset($invoice_report['total_amounts_by_currency']) && !empty($invoice_report['total_amounts_by_currency']) && $invoice_report['count'] > 0): ?>
                                <?php foreach ($invoice_report['total_amounts_by_currency'] as $currency => $currency_data): ?>
                                    <div class="text-sm">
                                        <?php 
                                        $avg_amount = $currency_data['amount'] / $invoice_report['count'];
                                        echo $currency_data['symbol'] . number_format($avg_amount, 2);
                                        ?>
                                        <span class="text-xs text-gray-500">
                                            <?php 
                                            $display_currency = $currency;
                                            if ($display_currency === 'GLOBAL') {
                                                $display_currency = get_option('easy_invoice_currency_code', 'USD');
                                            }
                                            echo esc_html(strtoupper($display_currency));
                                            ?>
                                        </span>
                                    </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                $0.00
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Invoice Status Chart -->
            <div class="p-4">
                <h3 class="text-md font-medium text-gray-700 mb-3">Invoice Status Distribution</h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div class="bg-white p-4 rounded-md shadow-sm">
                        <canvas id="invoice-status-chart" height="200"></canvas>
                    </div>
                    <div class="bg-white p-4 rounded-md shadow-sm">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead>
                                <tr>
                                    <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                    <th class="px-3 py-2 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Count</th>
                                    <th class="px-3 py-2 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Amount</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php 
                                $status_list = [
                                    'paid' => 'Paid',
                                    'unpaid' => 'Unpaid',
                                    'overdue' => 'Overdue',
                                    'draft' => 'Draft',
                                    'canceled' => 'Canceled',
                                    'other' => 'Other'
                                ];
                                
                                foreach ($status_list as $status_key => $status_label) : 
                                    $status_data = isset($invoice_report['by_status'][$status_key]) ? $invoice_report['by_status'][$status_key] : ['amount' => 0, 'count' => 0];
                                ?>
                                <tr>
                                    <td class="px-3 py-2 whitespace-nowrap text-sm text-gray-900">
                                        <?php echo esc_html($status_label); ?>
                                    </td>
                                    <td class="px-3 py-2 whitespace-nowrap text-sm text-right text-gray-500">
                                        <?php echo esc_html($status_data['count']); ?>
                                    </td>
                                    <td class="px-3 py-2 whitespace-nowrap text-sm text-right text-gray-900">
                                        <?php if (isset($status_data['amounts_by_currency']) && !empty($status_data['amounts_by_currency'])): ?>
                                            <?php foreach ($status_data['amounts_by_currency'] as $currency => $currency_data): ?>
                                                <div class="text-xs">
                                                    <?php echo $currency_data['symbol'] . number_format($currency_data['amount'], 2); ?>
                                                    <span class="text-xs text-gray-500">
                                                        <?php 
                                                        $display_currency = $currency;
                                                        if ($display_currency === 'GLOBAL') {
                                                            $display_currency = get_option('easy_invoice_currency_code', 'USD');
                                                        }
                                                        echo esc_html(strtoupper($display_currency));
                                                        ?>
                                                    </span>
                                                </div>
                                            <?php endforeach; ?>
                                        <?php else: ?>
                                            $0.00
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            
            <!-- Invoices List -->
            <div class="p-4">
                <h3 class="text-md font-medium text-gray-700 mb-3">Recent Invoices</h3>
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Date</th>
                                <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Due Date</th>
                                <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Invoice #</th>
                                <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Client</th>
                                <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Amount</th>
                                <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <?php if (!empty($invoice_report['invoices'])) : ?>
                                <?php foreach ($invoice_report['invoices'] as $invoice): ?>
                                <tr class="hover:bg-gray-50">
                                    <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                                        <?php echo date('M d, Y', strtotime($invoice['issue_date'])); ?>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                                        <?php 
                                        if (!empty($invoice['due_date']) && $invoice['due_date'] !== '0000-00-00' && $invoice['due_date'] !== '1970-01-01') {
                                            echo date('M d, Y', strtotime($invoice['due_date']));
                                        } else {
                                            echo '-';
                                        }
                                        ?>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap">
                                        <a href="<?php echo esc_url(get_permalink($invoice['id'])); ?>" class="text-indigo-600 hover:text-indigo-900 text-sm font-medium" target="_blank">
                                            <?php echo esc_html($invoice['invoice_number']); ?>
                                        </a>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-900">
                                        <?php if (!empty($invoice['client_id']) && !empty($invoice['client_name'])): ?>
                                            <a href="<?php echo esc_url(admin_url('admin.php?page=easy-invoice-clients&view=view&client_id=' . $invoice['client_id'])); ?>" class="text-gray-900 hover:text-indigo-900">
                                                <?php echo esc_html($invoice['client_name']); ?>
                                            </a>
                                        <?php elseif (!empty($invoice['client_name'])): ?>
                                            <span class="text-gray-900"><?php echo esc_html($invoice['client_name']); ?></span>
                                        <?php else: ?>
                                            <span class="text-gray-500">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-900">
                                        <?php 
                                        $display_currency = $invoice['currency'];
                                        if ($display_currency === 'GLOBAL') {
                                            $display_currency = get_option('easy_invoice_currency_code', 'USD');
                                        }
                                        echo esc_html($invoice['currency_symbol'] . number_format($invoice['total'], 2)); ?>
                                        <span class="text-xs text-gray-500"><?php echo esc_html(strtoupper($display_currency)); ?></span>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap">
                                        <?php 
                                        $status_class = 'bg-gray-100 text-gray-800';
                                        if (in_array($invoice['status'], ['paid', 'completed'])) {
                                            $status_class = 'bg-green-100 text-green-800';
                                        } elseif ($invoice['status'] === 'unpaid') {
                                            $status_class = 'bg-yellow-100 text-yellow-800';
                                        } elseif ($invoice['status'] === 'overdue') {
                                            $status_class = 'bg-red-100 text-red-800';
                                        } elseif ($invoice['status'] === 'draft') {
                                            $status_class = 'bg-gray-100 text-gray-800';
                                        }
                                        ?>
                                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full <?php echo esc_attr($status_class); ?>">
                                            <?php echo esc_html(ucfirst($invoice['status'])); ?>
                                        </span>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap text-sm font-medium">
                                        <a href="<?php echo esc_url(get_permalink($invoice['id'])); ?>" class="text-indigo-600 hover:text-indigo-900" target="_blank">View</a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="7" class="px-4 py-4 text-center text-gray-500">No invoice records found for the selected period</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Chart.js for Revenue Chart -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>


// Monthly revenue chart
function initializeRevenueChart() {
        // Wait for Chart.js to be available
        if (typeof Chart === 'undefined') {
            setTimeout(initializeRevenueChart, 500);
            return;
        }
        
        const chartElement = document.getElementById('revenue-chart');
        if (chartElement) {
            const monthlyRevenueLabels = <?php echo json_encode(array_keys($monthly_revenue)); ?>;
            

            
            // Process multi-currency data for chart display
            const monthlyRevenueData = <?php 

                
                // Get all unique currencies from monthly revenue data
                $all_currencies = [];
                if (is_array($monthly_revenue)) {
                    foreach ($monthly_revenue as $month => $currencies) {
                        if (is_array($currencies)) {
                            foreach ($currencies as $currency => $data) {
                                if (!in_array($currency, $all_currencies)) {
                                    $all_currencies[] = $currency;
                                }
                            }
                        }
                    }
                }
                sort($all_currencies); // Sort currencies for consistent order
                
                // Create datasets for each currency
                $datasets = [];
                $colors = [
                    'rgba(79, 70, 229, 0.8)',   // Indigo for USD
                    'rgba(16, 185, 129, 0.8)',  // Green for EUR
                    'rgba(245, 158, 11, 0.8)',  // Yellow for other currencies
                    'rgba(239, 68, 68, 0.8)',   // Red
                    'rgba(107, 114, 128, 0.8)'  // Gray
                ];
                
                if (!empty($all_currencies)) {
                    foreach ($all_currencies as $index => $currency) {
                        $currency_data = [];
                        $symbol = \EasyInvoice\Helpers\CurrencyHelper::getCurrencySymbol($currency);
                        
                        foreach ($monthly_revenue as $month => $currencies) {
                            $amount = isset($currencies[$currency]) ? $currencies[$currency]['amount'] : 0;
                            $currency_data[] = $amount;
                        }
                        
                        $datasets[] = [
                            'label' => $currency . ' (' . $symbol . ')',
                            'data' => $currency_data,
                            'backgroundColor' => $colors[$index % count($colors)],
                            'borderColor' => easy_invoice_str_replace('0.8', '1', $colors[$index % count($colors)]),
                            'borderWidth' => 1
                        ];
                    }
                }
                
                echo json_encode($datasets);
            ?>;
            

            
            // Check if we have data to display
            if (monthlyRevenueLabels.length > 0 && monthlyRevenueData.length > 0) {
                const revenueCtx = document.getElementById('revenue-chart').getContext('2d');
                
                // Destroy existing chart if it exists
                if (window.revenueChart) {
                    window.revenueChart.destroy();
                }
                
                try {
                    window.revenueChart = new Chart(revenueCtx, {
                        type: 'bar',
                        data: {
                            labels: monthlyRevenueLabels,
                            datasets: monthlyRevenueData
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            scales: {
                                y: {
                                    beginAtZero: true,
                                    ticks: {
                                        callback: function(value) {
                                            return '$' + value.toLocaleString();
                                        }
                                    }
                                }
                            },
                            plugins: {
                                tooltip: {
                                    callbacks: {
                                        label: function(context) {
                                            return context.dataset.label + ': ' + context.raw.toLocaleString();
                                        }
                                    }
                                },
                                legend: {
                                    display: true,
                                    position: 'top'
                                }
                            }
                        }
                    });
                    
                    console.log('Monthly Revenue Chart initialized successfully');
                } catch (error) {
                    console.error('Error initializing Monthly Revenue Chart:', error);
                    const chartContainer = document.getElementById('revenue-chart');
                    if (chartContainer) {
                        chartContainer.style.display = 'flex';
                        chartContainer.style.alignItems = 'center';
                        chartContainer.style.justifyContent = 'center';
                        chartContainer.innerHTML = '<div class="text-red-500 text-center"><p>Error loading chart. Please refresh the page.</p></div>';
                    }
                }
            } else {
                console.log('No data available for Monthly Revenue Chart');
                
                // Show no data message
                const chartContainer = document.getElementById('revenue-chart');
                if (chartContainer) {
                    chartContainer.style.display = 'flex';
                    chartContainer.style.alignItems = 'center';
                    chartContainer.style.justifyContent = 'center';
                    chartContainer.innerHTML = '<div class="text-gray-500 text-center"><p>No revenue data available for the selected period.</p><p class="text-sm mt-2">Revenue data will appear here once payments are recorded.</p></div>';
                }
                return;
            }
        } else {
            console.log('Revenue chart element not found');
        }
    }
    
    // Initialize chart when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    try {
        // Make sure payment report tab is visible by default
        const paymentReportTab = document.getElementById('payment-report-content');
        const invoiceReportTab = document.getElementById('invoice-report-content');
        
        if (paymentReportTab && invoiceReportTab) {
            // Set proper visibility immediately
            paymentReportTab.classList.remove('hidden');
            paymentReportTab.classList.add('block');
            paymentReportTab.style.display = 'block';
            
            invoiceReportTab.classList.add('hidden');
            invoiceReportTab.classList.remove('block');
            invoiceReportTab.style.display = 'none';
            
            // Set proper button state
            const paymentButton = document.getElementById('tab-payment-report');
            const invoiceButton = document.getElementById('tab-invoice-report');
            
            if (paymentButton && invoiceButton) {
                paymentButton.classList.add('active-tab', 'border-indigo-500', 'text-indigo-600');
                paymentButton.classList.remove('border-transparent', 'text-gray-500', 'hover:text-gray-700', 'hover:border-gray-300');
                
                invoiceButton.classList.remove('active-tab', 'border-indigo-500', 'text-indigo-600');
                invoiceButton.classList.add('border-transparent', 'text-gray-500', 'hover:text-gray-700', 'hover:border-gray-300');
            }
            
            // Also set the visibility with a delay to override any other scripts
            setTimeout(function() {
                paymentReportTab.classList.remove('hidden');
                paymentReportTab.classList.add('block');
                paymentReportTab.style.display = 'block';
                
                invoiceReportTab.classList.add('hidden');
                invoiceReportTab.classList.remove('block');
                invoiceReportTab.style.display = 'none';
            }, 100);
        }
        
            // Initialize the revenue chart
            initializeRevenueChart();
            


    // Invoice status pie chart
        if (document.getElementById('status-chart')) {
            
            const statusLabels = <?php 
                $status_labels = [];
                $status_data = [];
                if (isset($invoice_status['percentages']) && is_array($invoice_status['percentages'])) {
                    foreach ($invoice_status['percentages'] as $status => $percentage) {
                        $status_labels[] = ucfirst($status);
                        $status_data[] = $percentage;
                    }
                }
                echo json_encode($status_labels); 
            ?>;
            
            const statusData = <?php 
                echo json_encode($status_data); 
            ?>;
            

            
            const statusColors = [
                'rgba(34, 197, 94, 0.8)',  // Green for Paid
                'rgba(234, 179, 8, 0.8)',   // Yellow for Unpaid
                'rgba(239, 68, 68, 0.8)',   // Red for Overdue
                'rgba(209, 213, 219, 0.8)'  // Gray for Draft
            ];

            try {
                if (statusLabels.length === 0 || statusData.length === 0) {
                    return;
                }
                
                const statusCtx = document.getElementById('status-chart').getContext('2d');
                
                new Chart(statusCtx, {
                    type: 'doughnut',
                    data: {
                        labels: statusLabels,
                        datasets: [{
                            data: statusData,
                            backgroundColor: statusColors,
                            borderWidth: 1
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: false
                            },
                            tooltip: {
                                callbacks: {
                                    label: function(context) {
                                        return context.label + ': ' + context.raw + '%';
                                    }
                                }
                            }
                        },
                        cutout: '70%'
                    }
                });
            } catch (error) {
                console.error('Error creating status chart:', error);
            }
        }
        
        // Payment methods chart - use try-catch to prevent errors from breaking the page
        try {
            if (document.getElementById('payment-methods-chart')) {
                const paymentMethodsData = <?php
                    $methods = [];
                    $counts = [];
                    $methodColors = [];
                    $colorPalette = ['rgba(79, 70, 229, 0.8)', 'rgba(59, 130, 246, 0.8)', 'rgba(16, 185, 129, 0.8)', 
                                    'rgba(245, 158, 11, 0.8)', 'rgba(239, 68, 68, 0.8)', 'rgba(107, 114, 128, 0.8)'];
                    
                    $i = 0;
                    if (!empty($payment_report['by_method'])) {
                        foreach ($payment_report['by_method'] as $method => $data) {
                            $methods[] = ucfirst($method);
                            $counts[] = $data['count'];
                            $methodColors[] = $colorPalette[$i % count($colorPalette)];
                            $i++;
                        }
                    }
                    
                    echo json_encode([
                        'labels' => $methods,
                        'data' => $counts,
                        'colors' => $methodColors
                    ]);
                ?>;
                
                if (paymentMethodsData.labels && paymentMethodsData.labels.length > 0) {
                    const paymentMethodsCtx = document.getElementById('payment-methods-chart').getContext('2d');
                    new Chart(paymentMethodsCtx, {
                        type: 'pie',
                        data: {
                            labels: paymentMethodsData.labels,
                            datasets: [{
                                data: paymentMethodsData.data,
                                backgroundColor: paymentMethodsData.colors,
                                borderWidth: 1
                            }]
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            plugins: {
                                legend: {
                                    position: 'right'
                                },
                                tooltip: {
                                    callbacks: {
                                        label: function(context) {
                                            const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                            const percentage = Math.round((context.raw / total) * 100);
                                            return context.label + ': ' + context.raw + ' (' + percentage + '%)';
                                        }
                                    }
                                }
                            }
                        }
                    });
                } else {
                    // If no data, display a message
                    const canvas = document.getElementById('payment-methods-chart');
                    const ctx = canvas.getContext('2d');
                    ctx.font = '14px Arial';
                    ctx.fillStyle = '#6B7280';
                    ctx.textAlign = 'center';
                    ctx.fillText('No payment method data available', canvas.width / 2, canvas.height / 2);
                }
            }
        } catch (error) {
            console.error('Error initializing payment methods chart:', error);
        }
        
        // Invoice status detailed chart - use try-catch to prevent errors from breaking the page
        try {
            if (document.getElementById('invoice-status-chart')) {
                const invoiceStatusData = <?php
                    $statuses = [];
                    $statusCounts = [];
                    $statusChartColors = [
                        'rgba(34, 197, 94, 0.8)',  // Green for Paid
                        'rgba(234, 179, 8, 0.8)',  // Yellow for Unpaid
                        'rgba(239, 68, 68, 0.8)',  // Red for Overdue
                        'rgba(209, 213, 219, 0.8)', // Gray for Draft
                        'rgba(107, 114, 128, 0.8)', // Dark Gray for Canceled
                        'rgba(156, 163, 175, 0.8)'  // Medium Gray for Other
                    ];
                    
                    $status_list = [
                        'paid' => 'Paid',
                        'unpaid' => 'Unpaid',
                        'overdue' => 'Overdue',
                        'draft' => 'Draft',
                        'canceled' => 'Canceled',
                        'other' => 'Other'
                    ];
                    
                    $i = 0;
                    foreach ($status_list as $status_key => $status_label) {
                        $status_data = $invoice_report['by_status'][$status_key] ?? ['count' => 0];
                        if ($status_data['count'] > 0) {
                            $statuses[] = $status_label;
                            $statusCounts[] = $status_data['count'];
                            $i++;
                        }
                    }
                    
                    echo json_encode([
                        'labels' => $statuses,
                        'data' => $statusCounts,
                        'colors' => array_slice($statusChartColors, 0, $i)
                    ]);
                ?>;
                
                if (invoiceStatusData.labels && invoiceStatusData.labels.length > 0) {
                    const invoiceStatusCtx = document.getElementById('invoice-status-chart').getContext('2d');
                    new Chart(invoiceStatusCtx, {
                        type: 'pie',
                        data: {
                            labels: invoiceStatusData.labels,
                            datasets: [{
                                data: invoiceStatusData.data,
                                backgroundColor: invoiceStatusData.colors,
                                borderWidth: 1
                            }]
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            plugins: {
                                legend: {
                                    position: 'right'
                                },
                                tooltip: {
                                    callbacks: {
                                        label: function(context) {
                                            const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                            const percentage = Math.round((context.raw / total) * 100);
                                            return context.label + ': ' + context.raw + ' (' + percentage + '%)';
                                        }
                                    }
                                }
                            }
                        }
                    });
                } else {
                    // If no data, display a message
                    const canvas = document.getElementById('invoice-status-chart');
                    const ctx = canvas.getContext('2d');
                    ctx.font = '14px Arial';
                    ctx.fillStyle = '#6B7280';
                    ctx.textAlign = 'center';
                    ctx.fillText('No invoice status data available', canvas.width / 2, canvas.height / 2);
                }
            }
        } catch (error) {
            console.error('Error initializing invoice status chart:', error);
        }

        // Tab switching functionality
        const tabButtons = document.querySelectorAll('.tab-button');
        
        tabButtons.forEach(button => {
            button.addEventListener('click', function(e) {
                // Prevent default behavior that might cause page reload
                e.preventDefault();
                
                // Get button ID safely
                const buttonId = this.id || '';
                
                // Store the target tab ID before modifying classes
                const targetId = buttonId.replace('tab-', '') + '-content';
                
                // For troubleshooting
        
                
                // Remove active class from all buttons first
                tabButtons.forEach(btn => {
                    btn.classList.remove('active-tab', 'border-indigo-500', 'text-indigo-600');
                    btn.classList.add('border-transparent', 'text-gray-500', 'hover:text-gray-700', 'hover:border-gray-300');
                });
                
                // Add active class to clicked button
                this.classList.add('active-tab', 'border-indigo-500', 'text-indigo-600');
                this.classList.remove('border-transparent', 'text-gray-500', 'hover:text-gray-700', 'hover:border-gray-300');
                
                // Get all tab contents
                const paymentReportTab = document.getElementById('payment-report-content');
                const invoiceReportTab = document.getElementById('invoice-report-content');
                
                // Hide both tabs first
                if (paymentReportTab) {
                    paymentReportTab.classList.add('hidden');
                    paymentReportTab.classList.remove('block');
                    paymentReportTab.style.display = 'none';
                }
                
                if (invoiceReportTab) {
                    invoiceReportTab.classList.add('hidden');
                    invoiceReportTab.classList.remove('block');
                    invoiceReportTab.style.display = 'none';
                }
                
                // Show the target tab
                const targetTab = document.getElementById(targetId);
                if (targetTab) {
                    // Short delay helps ensure DOM updates properly
                    setTimeout(() => {
                        targetTab.classList.remove('hidden');
                        targetTab.classList.add('block');
                        targetTab.style.display = 'block';
                    }, 10);
                } else {
                    // Fallback to payment report if target not found
                    if (paymentReportTab) {
                        setTimeout(() => {
                            paymentReportTab.classList.remove('hidden');
                            paymentReportTab.classList.add('block');
                            paymentReportTab.style.display = 'block';
                        }, 10);
                    }
                }
            });
    });

    // Export report functionality (disabled to prevent conflict with detailed export)
    /*
    if (document.getElementById('export-report')) {
        document.getElementById('export-report').addEventListener('click', function() {
            try {
                // Create a timestamp for the filename
                const date = new Date();
                const timestamp = date.getFullYear() + '-' + 
                                  String(date.getMonth() + 1).padStart(2, '0') + '-' + 
                                  String(date.getDate()).padStart(2, '0');
                
                // Generate CSV content
                let csvContent = 'data:text/csv;charset=utf-8,';
                
                // Add report title and date range
                csvContent += '<?php echo esc_html__('Easy Invoice Report: Reports', 'easy-invoice'); ?>\r\n';
                csvContent += 'Date Range: ' + (document.getElementById('start_date') ? document.getElementById('start_date').value : 'N/A') + ' to ' + (document.getElementById('end_date') ? document.getElementById('end_date').value : 'N/A') + '\r\n\r\n';
                
                // Add summary stats
                csvContent += 'Summary Statistics\r\n';
                <?php if (isset($summary_stats['total_revenue']) && is_array($summary_stats['total_revenue']) && !empty($summary_stats['total_revenue'])): ?>
                    <?php foreach ($summary_stats['total_revenue'] as $currency => $data): ?>
                csvContent += 'Total Revenue (<?php echo $currency; ?>),<?php echo $data['symbol'] . number_format($data['amount'], 2); ?>\r\n';
                    <?php endforeach; ?>
                <?php else: ?>
                csvContent += 'Total Revenue,$0.00\r\n';
                <?php endif; ?>
                csvContent += 'Total Invoices,<?php echo isset($summary_stats['total_invoices']) ? $summary_stats['total_invoices'] : 0; ?>\r\n';
                csvContent += 'Active Clients,<?php echo isset($summary_stats['active_clients']) ? $summary_stats['active_clients'] : 0; ?>\r\n';
                csvContent += 'Average Payment Time,<?php echo isset($summary_stats['avg_payment_time']) ? $summary_stats['avg_payment_time'] : 0; ?> days\r\n\r\n';
                
                // Add monthly revenue
                csvContent += 'Monthly Revenue\r\n';
                csvContent += 'Month,USD,EUR,Other Currencies\r\n';
                <?php if (isset($monthly_revenue) && is_array($monthly_revenue)): ?>
                    <?php foreach ($monthly_revenue as $month => $currencies): ?>
                    <?php 
                        $usd_amount = isset($currencies['USD']) ? $currencies['USD']['amount'] : 0;
                        $eur_amount = isset($currencies['EUR']) ? $currencies['EUR']['amount'] : 0;
                        $other_currencies = [];
                        if (is_array($currencies)) {
                            foreach ($currencies as $currency => $data) {
                                if ($currency !== 'USD' && $currency !== 'EUR' && is_array($data)) {
                                    $other_currencies[] = $currency . ': ' . $data['symbol'] . number_format($data['amount'], 2);
                                }
                            }
                        }
                        $other_text = !empty($other_currencies) ? implode('; ', $other_currencies) : '';
                    ?>
                csvContent += '<?php echo $month; ?>,$<?php echo number_format($usd_amount, 2); ?>,€<?php echo number_format($eur_amount, 2); ?>,"<?php echo addslashes($other_text); ?>"\r\n';
        <?php endforeach; ?>
                <?php endif; ?>
                csvContent += '\r\n';
                
                // Add invoice status
                csvContent += 'Invoice Status\r\n';
                csvContent += 'Status,Percentage,Count\r\n';
                <?php if (isset($invoice_status['percentages']) && is_array($invoice_status['percentages'])): ?>
        <?php foreach ($invoice_status['percentages'] as $status => $percentage): ?>
                    <?php $count = isset($invoice_status['counts'][$status]) ? $invoice_status['counts'][$status] : 0; ?>
        csvContent += '<?php echo ucfirst($status); ?>,<?php echo $percentage; ?>%,<?php echo $count; ?>\r\n';
        <?php endforeach; ?>
                <?php endif; ?>
                csvContent += '\r\n';
                
                // Add top clients
                csvContent += 'Top Clients by Revenue\r\n';
                csvContent += 'Client,Email,Total Amount (USD),Total Amount (EUR),Other Currencies,Invoices,Last Invoice\r\n';
                <?php if (isset($top_clients) && is_array($top_clients)): ?>
        <?php foreach ($top_clients as $client): ?>
                    <?php 
                        $usd_amount = isset($client['total_amount']['USD']) ? $client['total_amount']['USD']['amount'] : 0;
                        $eur_amount = isset($client['total_amount']['EUR']) ? $client['total_amount']['EUR']['amount'] : 0;
                        $other_currencies = [];
                        if (isset($client['total_amount']) && is_array($client['total_amount'])) {
                            foreach ($client['total_amount'] as $currency => $data) {
                                if ($currency !== 'USD' && $currency !== 'EUR' && is_array($data)) {
                                    $other_currencies[] = $currency . ': ' . $data['symbol'] . number_format($data['amount'], 2);
                                }
                            }
                        }
                        $other_text = !empty($other_currencies) ? implode('; ', $other_currencies) : '';
                        $client_name = isset($client['name']) ? $client['name'] : 'Unknown';
                        $client_email = isset($client['email']) ? $client['email'] : '';
                        $total_invoices = isset($client['total_invoices']) ? $client['total_invoices'] : 0;
                        $last_invoice = isset($client['last_invoice']) && !empty($client['last_invoice']) ? date('Y-m-d', strtotime($client['last_invoice'])) : 'N/A';
                    ?>
                csvContent += '<?php echo addslashes($client_name); ?>,<?php echo addslashes($client_email); ?>,$<?php echo number_format($usd_amount, 2); ?>,€<?php echo number_format($eur_amount, 2); ?>,"<?php echo addslashes($other_text); ?>",<?php echo $total_invoices; ?>,<?php echo $last_invoice; ?>\r\n';
        <?php endforeach; ?>
                <?php endif; ?>
                
                // Create download link
                const encodedUri = encodeURI(csvContent);
                const link = document.createElement('a');
                link.setAttribute('href', encodedUri);
                link.setAttribute('download', 'easy-invoice-report-' + timestamp + '.csv');
                document.body.appendChild(link);
                
                // Trigger download
                link.click();
                document.body.removeChild(link);
                          } catch (error) {
                  alert('Error generating export. Please try again.');
              }
         });
     }
     */
     
     // Note: The above export functionality is disabled to prevent double downloads
     // with the detailed export button below. Only the detailed export is active.
     
     // Re-enable the proper export functionality with a different approach
     if (document.getElementById('export-report')) {
         document.getElementById('export-report').addEventListener('click', function() {
             // Set a flag to prevent detailed export from running
             window.exportInProgress = true;
             
             // Clear the flag after a short delay
             setTimeout(() => {
                 window.exportInProgress = false;
             }, 1000);
             try {
                 // Create a timestamp for the filename
                 const date = new Date();
                 const timestamp = date.getFullYear() + '-' + 
                                   String(date.getMonth() + 1).padStart(2, '0') + '-' + 
                                   String(date.getDate()).padStart(2, '0');
                 
                 // Generate CSV content
                 let csvContent = 'data:text/csv;charset=utf-8,';
                 
                 // Add report title and date range
                 csvContent += 'Easy Invoice Report: Reports\r\n';
                 csvContent += 'Date Range: ' + (document.getElementById('start_date') ? document.getElementById('start_date').value : 'N/A') + ' to ' + (document.getElementById('end_date') ? document.getElementById('end_date').value : 'N/A') + '\r\n\r\n';
                 
                 // Add summary stats
                 csvContent += 'Summary Statistics\r\n';
                 csvContent += 'Total Revenue,$0.00\r\n';
                 csvContent += 'Total Invoices,0\r\n';
                 csvContent += 'Active Clients,0\r\n';
                 csvContent += 'Average Payment Time,0 days\r\n\r\n';
                 
                 // Add monthly revenue
                 csvContent += 'Monthly Revenue\r\n';
                 csvContent += 'Month,Revenue\r\n';
                 csvContent += 'No data available\r\n\r\n';
                 
                 // Add invoice status
                 csvContent += 'Invoice Status\r\n';
                 csvContent += 'Status,Percentage,Count\r\n';
                 csvContent += 'No data available\r\n\r\n';
                 
                 // Add top clients
                 csvContent += 'Top Clients by Revenue\r\n';
                 csvContent += 'Client,Email,Total Amount,Invoices,Last Invoice\r\n';
                 csvContent += 'No data available\r\n';
                 
                 // Create download link
                 const encodedUri = encodeURI(csvContent);
                 const link = document.createElement('a');
                 link.setAttribute('href', encodedUri);
                 link.setAttribute('download', 'easy-invoice-report-' + timestamp + '.csv');
                 document.body.appendChild(link);
                 
                 // Trigger download
                 link.click();
                 document.body.removeChild(link);
             } catch (error) {
                 alert('Error generating export. Please try again.');
             }
         });
     }
        
                        // Simple Export functionality
                if (document.getElementById('export-detailed-report')) {
                    // Remove any existing event listeners to prevent duplicates
                    const exportButton = document.getElementById('export-detailed-report');
                    const newButton = exportButton.cloneNode(true);
                    exportButton.parentNode.replaceChild(newButton, exportButton);
                    
                    newButton.addEventListener('click', function(e) {
                        // Prevent multiple clicks
                        e.preventDefault();
                        e.stopPropagation();
                        
                        // Check if another export is in progress
                        if (window.exportInProgress) {
                            return;
                        }
                        
                        // Disable button to prevent multiple clicks
                        this.disabled = true;
                        this.style.opacity = '0.5';
                        
                        // Re-enable after 2 seconds
                        setTimeout(() => {
                            this.disabled = false;
                            this.style.opacity = '1';
                        }, 2000);
                try {
                    // Get active tab
                    const activeTab = document.querySelector('.tab-button.active-tab');
                    if (!activeTab) {
                        alert('Please select a report tab first.');
                        return;
                    }
                    
                    // Determine report type
                    const isPaymentTab = activeTab.id === 'tab-payment-report';
                    const reportType = isPaymentTab ? 'payment' : 'invoice';
                    
                                         // Get data based on report type
                     let data, headers, fileName;
                     
                     if (isPaymentTab) {
                         data = <?php echo json_encode(isset($payment_report['payments']) ? $payment_report['payments'] : []); ?>;
                         headers = ['Date', 'Invoice', 'Amount', 'Currency', 'Method', 'Status', 'Transaction ID'];
                         fileName = 'easy-invoice-payment-report-' + new Date().toISOString().split('T')[0] + '.csv';
                     } else {
                         data = <?php echo json_encode(isset($invoice_report['invoices']) ? $invoice_report['invoices'] : []); ?>;
                         headers = ['Date', 'Due Date', 'Invoice #', 'Client', 'Amount', 'Currency', 'Status'];
                         fileName = 'easy-invoice-invoice-report-' + new Date().toISOString().split('T')[0] + '.csv';
                     }
                    
                                         // Generate CSV with proper escaping
                     let csv = headers.map(header => `"${header}"`).join(',') + '\r\n';
                     
                     if (Array.isArray(data) && data.length > 0) {
                         data.forEach(function(item, index) {
                             if (isPaymentTab) {
                                 // Payment data
                                 const row = [
                                     item.date ? new Date(item.date).toLocaleDateString() : 'N/A',
                                     item.invoice_number || 'N/A',
                                     (item.currency_symbol || '$') + (parseFloat(item.amount || 0).toFixed(2)),
                                     item.currency || 'USD',
                                     item.payment_method || 'Unknown',
                                     item.status || 'Unknown',
                                     item.transaction_id || '-'
                                 ];
                                 csv += row.map(field => `"${field}"`).join(',') + '\r\n';
                             } else {
                                 // Invoice data
                                 const row = [
                                     item.issue_date ? new Date(item.issue_date).toLocaleDateString() : 'N/A',
                                     item.due_date ? new Date(item.due_date).toLocaleDateString() : '-',
                                     item.invoice_number || 'N/A',
                                     item.client_name || 'Unknown',
                                     (item.currency_symbol || '$') + (parseFloat(item.total || 0).toFixed(2)),
                                     item.currency || 'USD',
                                     item.status || 'Unknown'
                                 ];
                                 csv += row.map(field => `"${field}"`).join(',') + '\r\n';
                             }
                         });
                     } else {
                         csv += 'No data available\r\n';
                     }
                    
                                         // Create download using data URL approach
                     const csvContent = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv);
                     const link = document.createElement('a');
                     link.href = csvContent;
                     link.download = fileName;
                     link.style.display = 'none';
                     document.body.appendChild(link);
                     
                     // Trigger download
                     link.click();
                     document.body.removeChild(link);
                    
                } catch (error) {
                    console.error('Export error:', error);
                    alert('Error generating export. Please try again.');
                }
            });
        }
    } catch (error) {
        console.error('Error in reports page initialization:', error);
        
        // Make sure tabs are still visible even if there's an error
        const tabContents = document.querySelectorAll('.tab-content');
        if (tabContents.length > 0) {
            tabContents[0].classList.remove('hidden');
            tabContents[0].classList.add('block');
        }
    }
});
</script>
