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

use EasyInvoice\Constants\PagesSlugs;

$monthly_revenue = isset($monthly_revenue) && is_array($monthly_revenue) ? $monthly_revenue : array();
$easy_invoice_has_chart_data = false;
foreach ($monthly_revenue as $currencies) {
    if (! is_array($currencies)) {
        continue;
    }
    foreach ($currencies as $row) {
        if (isset($row['amount']) && is_numeric($row['amount']) && (float) $row['amount'] > 0) {
            $easy_invoice_has_chart_data = true;
            break 2;
        }
    }
}

if ($easy_invoice_has_chart_data) {
    wp_enqueue_script(
        'easy-invoice-chart-vendor',
        EASY_INVOICE_PLUGIN_URL . 'assets/js/vendors/chart.min.js',
        array(),
        EASY_INVOICE_VERSION,
        true
    );
    wp_enqueue_script(
        'easy-invoice-dashboard-chart',
        EASY_INVOICE_PLUGIN_URL . 'assets/js/dashboard-chart.js',
        array('easy-invoice-chart-vendor'),
        EASY_INVOICE_VERSION,
        true
    );
    wp_localize_script(
        'easy-invoice-dashboard-chart',
        'easyInvoiceDashboard',
        array(
            'monthlyRevenue' => $monthly_revenue,
            'hasData'        => true,
        )
    );
}

$invoices_list_url = admin_url('admin.php?page=' . PagesSlugs::ALL_INVOICES);
?>

<div class="p-8">
    <!-- Page Header -->
    <div class="ei-app-page-header bg-white border-b border-gray-200 px-6 easy-invoice-admin-page-header">
        <div class="flex items-center justify-between">
            <div>
                <h1 class="text-2xl font-bold text-gray-900"><?php esc_html_e( 'Dashboard', 'easy-invoice' ); ?></h1>
                <p class="mt-1 text-sm text-gray-500"><?php esc_html_e( 'Overview of your invoice management system', 'easy-invoice' ); ?></p>
            </div>
        </div>
    </div>
    
    <!-- Stats 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="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"><?php esc_html_e( 'Total Invoices', 'easy-invoice' ); ?></h3>
                    <p class="mt-1 text-2xl font-bold text-gray-900"><?php echo esc_html($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-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="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"><?php esc_html_e( 'Total Revenue', 'easy-invoice' ); ?></h3>
                    <?php if (is_array($total_revenue) && !empty($total_revenue)): ?>
                        <div class="mt-1">
                            <?php 
                            $currency_count = count($total_revenue);
                            foreach ($total_revenue as $currency => $data): 
                                $is_last = --$currency_count === 0;
                                $amount = isset($data['amount']) && is_numeric($data['amount']) ? $data['amount'] : 0;
                                $symbol = isset($data['symbol']) ? $data['symbol'] : '';
                            ?>
                                <div class="<?php echo $currency_count > 0 ? 'text-sm' : 'text-lg'; ?> font-bold text-gray-900 <?php echo !$is_last ? 'mb-1' : ''; ?>">
                                    <?php echo $symbol . number_format($amount, 2); ?>
                                    <span class="text-xs font-normal text-gray-500"><?php echo esc_html(strtoupper((string)($currency ?? 'USD'))); ?></span>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <p class="mt-1 text-lg font-bold text-gray-500"><?php esc_html_e( 'No revenue recorded', 'easy-invoice' ); ?></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-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"><?php esc_html_e( 'Unpaid Invoices', 'easy-invoice' ); ?></h3>
                    <p class="mt-1 text-2xl font-bold text-yellow-600"><?php echo esc_html($unpaid_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-red-100 p-3 mr-4">
                    <svg class="w-6 h-6 text-red-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 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z"></path>
                    </svg>
                </div>
                <div>
            <h3 class="text-sm font-medium text-gray-500"><?php esc_html_e( 'Overdue Invoices', 'easy-invoice' ); ?></h3>
                    <p class="mt-1 text-2xl font-bold text-red-600"><?php echo esc_html($overdue_invoices); ?></p>
                </div>
            </div>
        </div>
    </div>

    <!-- Client Stats Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-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-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"><?php esc_html_e( 'Total Clients', 'easy-invoice' ); ?></h3>
                    <p class="mt-1 text-2xl font-bold text-gray-900"><?php echo esc_html($total_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-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="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                    </svg>
                </div>
                <div>
            <h3 class="text-sm font-medium text-gray-500"><?php esc_html_e( 'Active Clients', 'easy-invoice' ); ?></h3>
                    <p class="mt-1 text-2xl font-bold text-indigo-600"><?php echo esc_html($active_clients); ?></p>
                </div>
            </div>
        </div>
    </div>

    <!-- Monthly Revenue Chart -->
    <div class="bg-white rounded-lg shadow p-6 mb-8 border border-gray-100">
        <h2 class="text-lg font-medium text-gray-900 mb-1"><?php esc_html_e( 'Monthly Revenue', 'easy-invoice' ); ?></h2>
        <?php if ($easy_invoice_has_chart_data) : ?>
            <p class="text-sm text-gray-500 mb-4"><?php esc_html_e( 'Paid amounts recorded over the last twelve months, by currency.', 'easy-invoice' ); ?></p>
            <div class="easy-invoice-chart-wrap">
                <canvas id="revenue-chart" class="easy-invoice-chart-canvas" role="img" aria-label="<?php echo esc_attr__( 'Monthly revenue by month and currency', 'easy-invoice' ); ?>"></canvas>
            </div>
        <?php else : ?>
            <p class="text-sm text-gray-500 mb-6"><?php esc_html_e( 'Trends appear here once completed payments exist in the selected period.', 'easy-invoice' ); ?></p>
            <div class="rounded-xl border border-dashed border-gray-200 bg-gradient-to-b from-gray-50 to-white px-8 py-12 text-center">
                <div class="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-indigo-50 text-indigo-600">
                    <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path>
                    </svg>
                </div>
                <h3 class="mt-4 text-base font-semibold text-gray-900"><?php esc_html_e( 'No revenue trend to show yet', 'easy-invoice' ); ?></h3>
                <p class="mt-2 max-w-md mx-auto text-sm text-gray-500 leading-relaxed">
                    <?php esc_html_e( 'Record a payment on an invoice to see your monthly performance in this chart.', 'easy-invoice' ); ?>
                </p>
                <a href="<?php echo esc_url($invoices_list_url); ?>" class="mt-6 inline-flex items-center rounded-md bg-indigo-600 px-4 py-2.5 text-sm font-medium text-white shadow-sm transition hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">
                    <?php esc_html_e( 'View all invoices', 'easy-invoice' ); ?>
                </a>
            </div>
        <?php endif; ?>
    </div>

    <!-- Recent Invoices -->
    <div class="bg-white rounded-lg shadow">
        <div class="px-6 py-4 border-b border-gray-200">
            <h2 class="text-lg font-medium text-gray-900"><?php esc_html_e( 'Recent Invoices', 'easy-invoice' ); ?></h2>
        </div>
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"><?php esc_html_e( 'Invoice #', 'easy-invoice' ); ?></th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"><?php esc_html_e( 'Client', 'easy-invoice' ); ?></th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"><?php esc_html_e( 'Amount', 'easy-invoice' ); ?></th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"><?php esc_html_e( 'Status', 'easy-invoice' ); ?></th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"><?php esc_html_e( 'Due Date', 'easy-invoice' ); ?></th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"><?php esc_html_e( 'Actions', 'easy-invoice' ); ?></th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php if (!empty($recent_invoices)) : ?>
                        <?php foreach ($recent_invoices as $invoice): 
                            $statusClass = [
                                'paid' => 'bg-green-100 text-green-800',
                                'unpaid' => 'bg-yellow-100 text-yellow-800',
                                'overdue' => 'bg-red-100 text-red-800',
                                'draft' => 'bg-gray-100 text-gray-800'
                            ][$invoice->getStatus()] ?? 'bg-gray-100 text-gray-800';
                            
                            $invoiceId = $invoice->getId();
                            $invoiceNumber = $invoice->getNumber() ?: ('INV-' . $invoiceId);
                            $invoiceTotal = $invoice->getTotal();
                            $clientName = $invoice->getCustomerName() ?: __( 'Client', 'easy-invoice' );
                            $dueDate = $invoice->getDueDate() ?: date('Y-m-d');
                            $raw_status = $invoice->getStatus();
                            $status_map = array(
                                'paid'    => __( 'Paid', 'easy-invoice' ),
                                'unpaid'  => __( 'Unpaid', 'easy-invoice' ),
                                'overdue' => __( 'Overdue', 'easy-invoice' ),
                                'draft'   => __( 'Draft', 'easy-invoice' ),
                            );
                            $status = isset( $status_map[ $raw_status ] ) ? $status_map[ $raw_status ] : esc_html( ucfirst( (string) $raw_status ) );
                        ?>
                        <tr>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"><?php echo esc_html($invoiceNumber); ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?php echo esc_html($clientName); ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?php 
                                // Use InvoiceFormatter for proper currency formatting
                                $formatter = new \EasyInvoice\Helpers\InvoiceFormatter();
                                echo esc_html($formatter->format($invoiceTotal)); 
                            ?></td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full <?php echo esc_attr($statusClass); ?>">
                                    <?php echo esc_html( $status ); ?>
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?php echo esc_html($dueDate); ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                <a href="<?php echo admin_url('admin.php?page=easy-invoice-invoices&view=edit&invoice_id=' . $invoiceId); ?>" class="text-indigo-600 hover:text-indigo-900 mr-3"><?php esc_html_e( 'Edit', 'easy-invoice' ); ?></a>
                                <a href="<?php echo admin_url('admin.php?page=easy-invoice-invoices&view=view&invoice_id=' . $invoiceId); ?>" class="text-indigo-600 hover:text-indigo-900"><?php esc_html_e( 'View', 'easy-invoice' ); ?></a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="6" class="px-6 py-4 text-center text-sm text-gray-500"><?php esc_html_e( 'No invoices found', 'easy-invoice' ); ?></td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>