<?php
// Ensure we're in the correct namespace
namespace EasyInvoice\Templates\Invoices;

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

use EasyInvoice\Models\Invoice;
use EasyInvoice\Models\Client;

// Prevent function redeclaration
if (!function_exists('easy_invoice_display_notification')) {
    function easy_invoice_display_notification($type, $message) {
        $bg_class = '';
        $text_class = '';
        $icon = '';
        
        switch ($type) {
            case 'success':
                $bg_class = 'bg-green-50';
                $text_class = 'text-green-800';
                $icon = '<svg class="h-5 w-5 text-green-400" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path></svg>';
                break;
            case 'error':
                $bg_class = 'bg-red-50';
                $text_class = 'text-red-800';
                $icon = '<svg class="h-5 w-5 text-red-400" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"></path></svg>';
                break;
            case 'warning':
                $bg_class = 'bg-yellow-50';
                $text_class = 'text-yellow-800';
                $icon = '<svg class="h-5 w-5 text-yellow-400" fill="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"></path></svg>';
                break;
            default:
                $bg_class = 'bg-blue-50';
                $text_class = 'text-blue-800';
                $icon = '<svg class="h-5 w-5 text-blue-400" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd"></path></svg>';
        }
        
        echo '<div class="rounded-md ' . $bg_class . ' p-4 mb-4">';
        echo '<div class="flex">';
        echo '<div class="flex-shrink-0">' . $icon . '</div>';
        echo '<div class="ml-3">';
        echo '<p class="text-sm font-medium ' . $text_class . '">' . $message . '</p>';
        echo '</div>';
        echo '<div class="ml-auto pl-3">';
        echo '<div class="-mx-1.5 -my-1.5">';
        echo '<button type="button" class="inline-flex rounded-md p-1.5 ' . $text_class . ' hover:bg-green-100 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 notification-dismiss">';
        echo '<span class="sr-only">Dismiss</span>';
        echo '<svg class="h-5 w-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">';
        echo '<path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd" />';
        echo '</svg>';
        echo '</button>';
        echo '</div>';
        echo '</div>';
        echo '</div>';
        echo '</div>';
    }
}

// One-time fix: Update all existing draft invoices to published status for proper permalinks
if (!get_option('easy_invoice_draft_invoices_fixed', false)) {
    $invoice_repository = \EasyInvoice\Providers\InvoiceServiceProvider::getInvoiceRepository();
    $updated_count = $invoice_repository->updateAllExistingInvoices();
    
    if ($updated_count > 0) {
        // Show a one-time notification
        add_action('admin_notices', function() use ($updated_count) {
            echo '<div class="notice notice-success is-dismissible">';
            echo '<p>' . sprintf(__('%d draft invoices updated to published status for proper permalinks.', 'easy-invoice'), $updated_count) . '</p>';
            echo '</div>';
        });
    }
    
    // Mark as fixed
    update_option('easy_invoice_draft_invoices_fixed', true);
}

// Get current view (all, trash)
$current_view = isset($_GET['view']) ? sanitize_text_field($_GET['view']) : 'all';

// Get status filter
$status_filter = isset($_GET['status']) ? sanitize_text_field($_GET['status']) : '';

// Get recurring filter
$recurring_filter = isset($_GET['recurring']) ? sanitize_text_field($_GET['recurring']) : '';

// Check for bulk action notifications
$notification = false;

if (isset($_GET['bulk_trashed']) && $_GET['bulk_trashed'] > 0) {
    $count = intval($_GET['bulk_trashed']);
    easy_invoice_display_notification('success', sprintf(_n('%s invoice moved to trash.', '%s invoices moved to trash.', $count, 'easy-invoice'), $count));
    $notification = true;
}

if (isset($_GET['bulk_restored']) && $_GET['bulk_restored'] > 0) {
    $count = intval($_GET['bulk_restored']);
    easy_invoice_display_notification('success', sprintf(_n('%s invoice restored from trash.', '%s invoices restored from trash.', $count, 'easy-invoice'), $count));
    $notification = true;
}

if (isset($_GET['bulk_deleted']) && $_GET['bulk_deleted'] > 0) {
    $count = intval($_GET['bulk_deleted']);
    easy_invoice_display_notification('success', sprintf(_n('%s invoice permanently deleted.', '%s invoices permanently deleted.', $count, 'easy-invoice'), $count));
    $notification = true;
}

if (isset($_GET['bulk_drafted']) && $_GET['bulk_drafted'] > 0) {
    $count = intval($_GET['bulk_drafted']);
    easy_invoice_display_notification('success', sprintf(_n('%s invoice set to draft status.', '%s invoices set to draft status.', $count, 'easy-invoice'), $count));
    $notification = true;
}

if (isset($_GET['bulk_published']) && $_GET['bulk_published'] > 0) {
    $count = intval($_GET['bulk_published']);
    easy_invoice_display_notification('success', sprintf(_n('%s invoice published successfully.', '%s invoices published successfully.', $count, 'easy-invoice'), $count));
    $notification = true;
}

if (isset($_GET['bulk_error'])) {
    $error = sanitize_text_field($_GET['bulk_error']);
    $error_message = 'An error occurred while processing the bulk action.';
    
    if ($error === 'no_selection') {
        $error_message = 'Please select at least one invoice to perform this action.';
    } elseif ($error === 'invalid_action') {
        $error_message = 'Please select a valid bulk action.';
    }
    
    easy_invoice_display_notification('error', $error_message);
    $notification = true;
}
// Extract invoice data for statistics
$formatted_invoices = array();
foreach ($invoices as $invoice) {
    // For Invoice model objects
    if (is_object($invoice)) {
        $formatted_invoices[] = array(
            'id' => $invoice->getId(),
            'amount' => $invoice->getTotal(),
            'status' => $invoice->getStatus(),
        );
    } else {
        // For already formatted invoice arrays
        $formatted_invoices[] = array(
            'id' => $invoice['id'],
            'amount' => isset($invoice['total_amount']) ? $invoice['total_amount'] : $invoice['amount'],
            'status' => $invoice['status'],
        );
    }
}

// Get stats from all invoices, not just the current page
$invoice_controller = new \EasyInvoice\Controllers\InvoiceController();
$stats = $invoice_controller->getInvoiceStats();

// Add total invoices count from current page for display purposes
$stats['total_invoices'] = count($formatted_invoices);

// Get trash count for tab display
$trash_args = ['post_status' => 'trash'];
$trash_invoices = $repository->all($trash_args);
$trash_count = count($trash_invoices);

// Get draft count for tab display
$draft_args = ['post_status' => 'draft'];
$draft_invoices = $repository->all($draft_args);
$draft_count = count($draft_invoices);

// Define available status filters
$status_filters = array(
    'paid' => 'Paid',
    'unpaid' => 'Unpaid',
    'pending' => 'Pending',
    'draft' => 'Draft',
    'overdue' => 'Overdue',
    'cancelled' => 'Cancelled'
);

?>
<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"><?php _e('Invoices', 'easy-invoice'); ?></h1>
                <p class="mt-1 text-sm text-gray-500"><?php _e('Manage and track your invoices', 'easy-invoice'); ?></p>
            </div>
            <div class="flex items-center space-x-3">
                <?php if (isset($_GET['rewrite_flushed'])): ?>
                    <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-2 rounded-md text-sm">
                        <?php _e('Rewrite rules flushed successfully!', 'easy-invoice'); ?>
                    </div>
                <?php endif; ?>
                
                <?php if (isset($_GET['post_types_registered'])): ?>
                    <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-2 rounded-md text-sm">
                        <?php _e('Post types registered successfully!', 'easy-invoice'); ?>
                    </div>
                <?php endif; ?>
                
                <a href="<?php echo wp_nonce_url(admin_url('admin-post.php?action=flush_easy_invoice_rewrite_rules'), 'flush_easy_invoice_rewrite_rules'); ?>" 
                   class="bg-yellow-100 text-yellow-700 hover:bg-yellow-200 px-4 py-2 rounded-md text-sm font-medium transition-colors duration-200">
                    <?php _e('Flush Rewrite Rules', 'easy-invoice'); ?>
                </a>
                
                <?php if (!easy_invoice_has_pro()): ?>
                <button type="button" id="export-all-invoices-btn" class="premium-export-btn inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors duration-200 relative">
                    <svg class="w-4 h-4 mr-2 text-gray-500" 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 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 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>
                    <?php _e('Export All', 'easy-invoice'); ?>
                    <svg class="ml-2 w-5 h-5 text-purple-600 crown-icon" fill="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path d="M12 8L15 13.2L18 10.5L17.3 14H6.7L6 10.5L9 13.2L12 8M12 4L8.5 10L3 5L5 16H19L21 5L15.5 10L12 4Z"/>
                    </svg>
                </button>
                <script>
                jQuery(document).ready(function($) {
                    $('#export-all-invoices-btn').on('click', function(e) {
                        e.preventDefault();
                        // Show premium popup using the proper confirmation modal
                        if (typeof EasyInvoiceConfirmation !== 'undefined') {
                            EasyInvoiceConfirmation.showFeatureUpgrade('Export All Invoices', 'Export all your invoices to CSV, Excel, or PDF format for backup, analysis, or sharing with your team.');
                        } else {
                            // Fallback to alert if confirmation modal is not available
                            alert('<?php echo esc_js(__('Exporting all invoices is a premium feature. Upgrade to Easy Invoice Pro to unlock this feature.', 'easy-invoice')); ?>');
                        }
                    });
                });
                </script>
                <?php else: ?>
                <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="display:inline;">
                    <input type="hidden" name="action" value="easy_invoice_export_all_invoices" />
                    <input type="hidden" name="_wpnonce" value="<?php echo wp_create_nonce('easy_invoice_export_all_invoices'); ?>" />
                    <button type="submit" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-indigo-700 bg-indigo-100 hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                        <svg class="w-4 h-4 mr-2 text-indigo-500" 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 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 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>
                        <?php _e('Export All', 'easy-invoice'); ?>
                    </button>
                </form>
                <?php endif; ?>
                <a href="#" id="create-new-invoice-btn" 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">
                    <svg class="w-4 h-4 mr-2" 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 6v6m0 0v6m0-6h6m-6 0H6"></path>
                    </svg>
                    <?php _e('Create New Invoice', 'easy-invoice'); ?>
                </a>
            </div>
        </div>
    </div>

    <!-- Stats Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 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">Total Invoices</h3>
                    <p class="mt-1 text-2xl font-bold text-gray-900"><?php echo $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-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">Total Revenue</h3>
                    <?php if (is_array($stats['total_revenue']) && !empty($stats['total_revenue'])): ?>
                        <div class="mt-1">
                            <?php foreach ($stats['total_revenue'] as $currency => $data): ?>
                                <?php 
                                // Create a temporary invoice object with the currency for proper formatting
                                $temp_invoice = new \EasyInvoice\Models\Invoice();
                                $temp_invoice->setCurrencyCode($currency);
                                $formatter = new \EasyInvoice\Helpers\InvoiceFormatter($temp_invoice);
                                ?>
                                <p class="text-lg font-bold text-gray-900">
                                    <?php echo $formatter->format($data['amount']); ?>
                                    <span class="text-sm font-normal text-gray-500"><?php echo $currency; ?></span>
                                </p>
                            <?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-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="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 Value</h3>
                    <?php if (is_array($stats['total_value']) && !empty($stats['total_value'])): ?>
                        <div class="mt-1">
                            <?php foreach ($stats['total_value'] as $currency => $data): ?>
                                <?php 
                                $formatter = new \EasyInvoice\Helpers\InvoiceFormatter($data['invoice_object']);
                                $formatted_amount = $formatter->format($data['amount']);
                                ?>
                                <div class="text-lg font-bold text-gray-900">
                                    <?php echo $formatted_amount; ?>
                                    <span class="text-xs font-normal text-gray-500 ml-1">(<?php echo $data['invoices']; ?> <?php echo $data['invoices'] > 1 ? 'invoices' : 'invoice'; ?>)</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 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">Paid Invoices</h3>
                    <p class="mt-1 text-2xl font-bold text-green-600"><?php echo $stats['paid_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-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">Pending Invoices</h3>
                    <p class="mt-1 text-2xl font-bold text-yellow-600"><?php echo $stats['pending_invoices']; ?></p>
                </div>
            </div>
        </div>
    </div>

    <!-- Top Pagination -->
    <?php if ($total_invoices > 0): ?>
    <div class="mb-4">
        <div class="px-4 py-3 flex items-center justify-between">
            <div class="flex items-center space-x-2">
                <span class="text-sm text-gray-700">
                    Showing 
                    <span class="font-medium"><?php echo number_format((($current_page - 1) * $per_page) + 1); ?></span>
                    to 
                    <span class="font-medium"><?php echo number_format(min($current_page * $per_page, $total_invoices)); ?></span>
                    of 
                    <span class="font-medium"><?php echo number_format($total_invoices); ?></span>
                    results
                </span>
            </div>
            <?php if ($total_pages > 1): ?>
            <div class="flex items-center space-x-2">
                <span class="text-sm text-gray-500">Page <?php echo number_format($current_page); ?> of <?php echo number_format($total_pages); ?></span>
                <?php
                // Use WordPress's built-in pagination for top
                $top_pagination_args = array(
                    'base' => add_query_arg('paged', '%#%'),
                    'format' => '',
                    'current' => $current_page,
                    'total' => $total_pages,
                    'prev_text' => '‹ Previous',
                    'next_text' => 'Next ›',
                    'type' => 'array',
                    'end_size' => 1,
                    'mid_size' => 2,
                    'add_args' => array(
                        'view' => $current_view,
                        'status' => $status_filter,
                        'recurring' => $recurring_filter
                    )
                );
                
                $top_pagination_links = paginate_links($top_pagination_args);
                
                if ($top_pagination_links) {
                    echo '<div class="flex space-x-1">';
                    foreach ($top_pagination_links as $link) {
                        // Add null check to prevent passing null to easy_invoice_str_replace
                        if ($link === null) {
                            continue;
                        }
                        
                        // Convert WordPress pagination to our styling
                        $link = easy_invoice_str_replace('page-numbers', 'px-3 py-2 text-sm font-medium border border-gray-300 rounded-md', $link);
                        $link = easy_invoice_str_replace('current', 'bg-indigo-50 border-indigo-500 text-indigo-600', $link);
                        $link = easy_invoice_str_replace('prev', 'bg-white text-gray-500 hover:bg-gray-50', $link);
                        $link = easy_invoice_str_replace('next', 'bg-white text-gray-500 hover:bg-gray-50', $link);
                        $link = easy_invoice_str_replace('dots', 'bg-white text-gray-700', $link);
                        
                        // Add default styling for regular page numbers
                        if ($link && strpos($link, 'bg-indigo-50') === false && strpos($link, 'bg-white') === false) {
                            $link = easy_invoice_str_replace('border-gray-300', 'border-gray-300 bg-white text-gray-500 hover:bg-gray-50', $link);
                        }
                        
                        echo $link;
                    }
                    echo '</div>';
                }
                ?>
            </div>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- View Tabs and Filters -->
    <div class="bg-white rounded-lg shadow mb-6 overflow-hidden">
        <!-- Tabs with more modern styling -->
        <div class="border-b border-gray-200 bg-gradient-to-r from-indigo-50 to-white">
            <nav class="flex">
                <?php 
                // View Tabs (All, Draft, Trash)
                $views = array(
                    'all' => 'All (' . $stats['total_invoices'] . ')',
                    'draft' => 'Draft (' . $draft_count . ')',
                    'trash' => 'Trash (' . $trash_count . ')'
                );
                
                foreach ($views as $view => $label) {
                    $is_current = $current_view === $view;
                    $status_param = !empty($status_filter) && $view === 'all' ? '&status=' . $status_filter : '';
                    $class = $is_current 
                        ? 'border-b-2 border-indigo-500 text-indigo-600 bg-white' 
                        : 'border-b-2 border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300';
                    ?>
                    <a href="?page=easy-invoice-all&view=<?php echo esc_attr($view . $status_param); ?>" 
                       class="flex items-center whitespace-nowrap py-4 px-6 font-medium text-sm transition-colors duration-200 <?php echo $class; ?>">
                        <?php if ($view === 'all'): ?>
                            <svg class="w-4 h-4 mr-2" 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>
                        <?php elseif ($view === 'draft'): ?>
                            <svg class="w-4 h-4 mr-2" 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="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                            </svg>
                        <?php elseif ($view === 'trash'): ?>
                            <svg class="w-4 h-4 mr-2" 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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                            </svg>
                        <?php endif; ?>
                        <?php echo $label; ?>
                    </a>
                    <?php
                }
                ?>
            </nav>
        </div>
        
        <!-- Filters and Bulk Actions with Search -->
        <div class="p-4 flex flex-wrap items-center justify-between bg-white border-b border-gray-100">
            <!-- Bulk Actions (Left Side) -->
            <div class="flex items-center space-x-2 my-2">
                <form id="bulk-action-form" method="post" class="flex items-center gap-2">
                    <?php wp_nonce_field('easy_invoice_bulk_action', 'easy_invoice_bulk_nonce'); ?>
                    <input type="hidden" name="action" value="easy_invoice_bulk_action">
                    
                    <select name="bulk_action" class="block w-full px-3 py-2 border border-gray-300 rounded-md leading-5 bg-white text-gray-700 placeholder-gray-500 focus:outline-none focus:placeholder-gray-400 focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                        <option value="">Bulk Actions</option>
                        <?php if ($current_view === 'trash'): ?>
                            <option value="restore">Restore</option>
                            <option value="delete">Delete Permanently</option>
                        <?php elseif ($current_view === 'draft'): ?>
                            <option value="publish">Publish</option>
                            <option value="trash">Move to Trash</option>
                        <?php else: ?>
                            <option value="trash">Move to Trash</option>
                            <option value="draft">Set to Draft</option>
                        <?php endif; ?>
                    </select>
                    
                    <button type="submit" 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">
                        Apply
                    </button>
                </form>
            </div>
            
            <?php if ($current_view !== 'trash'): ?>
            <!-- Search Form (Right Side) -->
            <div class="flex items-center gap-2">
                <form method="get" class="flex items-center gap-2">
                    <input type="hidden" name="page" value="easy-invoice-all">
                    <input type="hidden" name="view" value="<?php echo esc_attr($current_view); ?>">
                    <?php if (!empty($status_filter)): ?>
                        <input type="hidden" name="status" value="<?php echo esc_attr($status_filter); ?>">
                    <?php endif; ?>
                    <?php if (!empty($recurring_filter)): ?>
                        <input type="hidden" name="recurring" value="<?php echo esc_attr($recurring_filter); ?>">
                    <?php endif; ?>
                    
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                            <svg class="h-5 w-5 text-gray-400" 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="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                            </svg>
                        </div>
                        <input type="text" 
                               name="search" 
                               value="<?php echo esc_attr($search_query); ?>" 
                               placeholder="<?php _e('Search invoices, numbers, or clients...', 'easy-invoice'); ?>"
                               class="block w-64 pl-10 pr-3 py-2 border border-gray-300 rounded-md leading-5 bg-white placeholder-gray-500 focus:outline-none focus:placeholder-gray-400 focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                    </div>
                    
                    <button type="submit" 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">
                        <?php _e('Search', 'easy-invoice'); ?>
                    </button>
                    
                    <?php if (!empty($search_query)): ?>
                        <a href="<?php echo esc_url(remove_query_arg('search', $_SERVER['REQUEST_URI'])); ?>" class="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                            <?php _e('Clear', 'easy-invoice'); ?>
                        </a>
                    <?php endif; ?>
                </form>
            </div>
            <?php endif; ?>
        </div>
        
        <!-- Status Filters -->
        <?php if ($current_view !== 'trash'): ?>
        <div class="p-4 bg-white border-b border-gray-100">
            <div class="flex flex-wrap items-center gap-2 my-2">
                <span class="text-sm text-gray-500 mr-2">Filter by status:</span>
                <div class="flex flex-wrap gap-1">
                    <?php 
                    // Build base URL with current view, recurring filter, and search query
                    $base_url = '?page=easy-invoice-all&view=' . $current_view;
                    if (!empty($recurring_filter)) {
                        $base_url .= '&recurring=' . urlencode($recurring_filter);
                    }
                    if (!empty($search_query)) {
                        $base_url .= '&search=' . urlencode($search_query);
                    }
                    ?>
                    <a href="<?php echo esc_url($base_url); ?>" class="<?php echo empty($status_filter) ? 'bg-indigo-100 text-indigo-800 ring-1 ring-indigo-300' : 'bg-gray-50 text-gray-700 hover:bg-gray-100'; ?> px-3 py-1 rounded-full text-xs font-medium transition-colors duration-200">
                        All
                    </a>
                    
                    <?php 
                    $status_colors = [
                        'paid' => 'bg-green-100 text-green-800 ring-1 ring-green-300',
                        'unpaid' => 'bg-yellow-100 text-yellow-800 ring-1 ring-yellow-300',
                        'pending' => 'bg-blue-100 text-blue-800 ring-1 ring-blue-300',
                        'draft' => 'bg-gray-100 text-gray-800 ring-1 ring-gray-300',
                        'overdue' => 'bg-red-100 text-red-800 ring-1 ring-red-300',
                        'cancelled' => 'bg-gray-100 text-gray-800 ring-1 ring-gray-300'
                    ];
                    
                    foreach ($status_filters as $status_key => $status_label): 
                        $is_current = $status_filter === $status_key;
                        $base_class = 'px-3 py-1 rounded-full text-xs font-medium transition-colors duration-200';
                        
                        if ($is_current) {
                            $color_class = $status_colors[$status_key] ?? 'bg-indigo-100 text-indigo-800 ring-1 ring-indigo-300';
                        } else {
                            $color_class = 'bg-gray-50 text-gray-700 hover:bg-gray-100';
                        }
                        
                        // Build URL with status filter
                        $status_url = $base_url . '&status=' . urlencode($status_key);
                    ?>
                        <a href="<?php echo esc_url($status_url); ?>" 
                           class="<?php echo $base_class . ' ' . $color_class; ?>">
                            <?php echo $status_label; ?>
                        </a>
                    <?php endforeach; ?>
                </div>
                <?php do_action('easy_invoice_inline_type_filter'); ?>
            </div>
            
            <!-- Hook for Pro plugin to add additional filters -->
            <?php do_action('easy_invoice_before_invoice_listing'); ?>
            <?php endif; ?>
        </div>
    </div>

    <!-- Invoices Table -->
    <div class="bg-white rounded-lg shadow overflow-hidden">
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead>
                    <tr class="bg-gray-50">
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-10 border-b border-gray-200">
                            <input type="checkbox" id="select-all" class="rounded border-gray-300 text-indigo-600 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider border-b border-gray-200">
                            <?php _e('Invoice', 'easy-invoice'); ?>
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider border-b border-gray-200">
                            <?php _e('Client', 'easy-invoice'); ?>
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider border-b border-gray-200">
                            <?php _e('Status', 'easy-invoice'); ?>
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider border-b border-gray-200">
                            <?php _e('Amount', 'easy-invoice'); ?>
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider border-b border-gray-200">
                            <?php _e('Due Date', 'easy-invoice'); ?>
                        </th>
                        <?php do_action('easy_invoice_after_invoice_listing_header'); ?>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-100">
                    <?php foreach ($invoices as $invoice) : 
                        // Handle both object and array formats
                        if (is_object($invoice)) {
                            $invoice_id = $invoice->getId();
                            $invoice_number = $invoice->getNumber();
                            $invoice_title = $invoice->getTitle();
                            
                            // Get client name directly from client repository
                            $client_name = 'No Client';
                            if ($invoice->getClientId() > 0) {
                                $client_repository = \EasyInvoice\Providers\ClientServiceProvider::getClientRepository();
                                $client = $client_repository->find($invoice->getClientId());
                                if ($client) {
                                    $client_name = $client->getBusinessClientName() ?: ($client->getFirstName() . ' ' . $client->getLastName());
                                    if (empty(trim($client_name))) {
                                        $client_name = $client->getDisplayName() ?: 'Client ' . $client->getId();
                                    }
                                }
                            } elseif ($invoice->getCustomerName()) {
                                $client_name = $invoice->getCustomerName();
                            }
                            
                            $client_email = $invoice->getCustomerEmail();
                            $status = $invoice->getStatus();
                            
                            // Use formatter to display amount properly
                            $formatter = new \EasyInvoice\Helpers\InvoiceFormatter($invoice);
                            $amount = $formatter->format($invoice->getTotal());
                            $due_date = $invoice->getDueDate();
                        } else {
                            $invoice_id = $invoice['id'];
                            $invoice_number = $invoice['invoice_number'];
                            $invoice_title = isset($invoice['title']) ? $invoice['title'] : $invoice_number;
                            $client_name = $invoice['client_name'];
                            $client_email = isset($invoice['client_email']) ? $invoice['client_email'] : '';
                            $status = $invoice['status'];
                            $amount = $invoice['total_amount'];
                            $due_date = $invoice['due_date'];
                        }
                        
                        // Format the display title
                        $display_title = $invoice_title ?: 'Untitled Invoice';
                        
                        // Determine classes for status badge
                        $status_class = 'bg-gray-100 text-gray-800 ring-1 ring-gray-200';
                        if ($status === 'paid') {
                            $status_class = 'bg-green-100 text-green-800 ring-1 ring-green-200';
                        } elseif ($status === 'pending') {
                            $status_class = 'bg-yellow-100 text-yellow-800 ring-1 ring-yellow-200';
                        } elseif ($status === 'overdue') {
                            $status_class = 'bg-red-100 text-red-800 ring-1 ring-red-200';
                        }
                    ?>
                    <?php do_action('easy_invoice_before_invoice_listing_row', $invoice); ?>
                    <tr class="hover:bg-gray-50 transition-colors duration-150" data-invoice-id="<?php echo $invoice_id; ?>">
                        <td class="px-6 py-4 whitespace-nowrap">
                            <input type="checkbox" name="invoice_ids[]" value="<?php echo $invoice_id; ?>" form="bulk-action-form" class="invoice-checkbox rounded border-gray-300 text-indigo-600 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <?php if ($current_view === 'trash'): ?>
                                <div class="text-sm font-medium text-gray-900">
                                    <?php echo esc_html($display_title); ?>
                                </div>
                                <div class="text-xs text-gray-500 mt-1">
                                    <?php echo apply_filters('easy_invoice_invoice_number_display', esc_html($invoice_number), $invoice); ?>
                                    <?php
                                    // Check if this invoice was converted from a quote
                                    $quote_info = \EasyInvoice\Helpers\QuoteInvoiceHelper::getQuoteInfoFromInvoice($invoice_id);
                                    if ($quote_info): ?>
                                        <span class="ml-2 inline-flex items-center space-x-1">
                                            <i class="<?php echo esc_attr($quote_info['icon_class']); ?> text-blue-500 text-xs" title="<?php echo esc_attr($quote_info['tooltip_text']); ?>"></i>
                                            <a href="<?php echo esc_url($quote_info['url']); ?>" 
                                               target="_blank" 
                                               class="text-blue-600 hover:text-blue-800 hover:underline text-xs"
                                               title="<?php echo esc_attr($quote_info['tooltip_text']); ?>">
                                                <?php echo esc_html($quote_info['number'] ?: $quote_info['title']); ?>
                                            </a>
                                        </span>
                                    <?php endif; ?>
                                </div>
                                <div class="row-actions mt-1">
                                    <span class="restore"><a href="#" class="restore-invoice" data-invoice-id="<?php echo $invoice_id; ?>" data-invoice-number="<?php echo esc_attr($invoice_number); ?>"><svg class="w-3.5 h-3.5 mr-1 inline-block" 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="M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6"></path></svg><?php _e('Restore', 'easy-invoice'); ?></a></span>
                                    <span class="delete"><a href="#" class="delete-permanently text-red-600" data-invoice-id="<?php echo $invoice_id; ?>" data-invoice-number="<?php echo esc_attr($invoice_number); ?>"><svg class="w-3.5 h-3.5 mr-1 inline-block" 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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg><?php _e('Delete Permanently', 'easy-invoice'); ?></a></span>
                                </div>
                            <?php elseif ($current_view === 'draft'): ?>
                                <div class="text-sm font-medium text-gray-900">
                                    <a href="<?php echo get_permalink($invoice_id); ?>" class="text-indigo-600 hover:text-indigo-900">
                                        <?php echo apply_filters('easy_invoice_invoice_title', esc_html($display_title), $invoice); ?>
                                    </a>
                                </div>
                                <div class="text-xs text-gray-500 mt-1">
                                    <?php echo apply_filters('easy_invoice_invoice_number_display', esc_html($invoice_number), $invoice); ?>
                                    <?php
                                    // Check if this invoice was converted from a quote
                                    $quote_info = \EasyInvoice\Helpers\QuoteInvoiceHelper::getQuoteInfoFromInvoice($invoice_id);
                                    if ($quote_info): ?>
                                        <span class="ml-2 inline-flex items-center space-x-1">
                                            <i class="<?php echo esc_attr($quote_info['icon_class']); ?> text-blue-500 text-xs" title="<?php echo esc_attr($quote_info['tooltip_text']); ?>"></i>
                                            <a href="<?php echo esc_url($quote_info['url']); ?>" 
                                               target="_blank" 
                                               class="text-blue-600 hover:text-blue-800 hover:underline text-xs"
                                               title="<?php echo esc_attr($quote_info['tooltip_text']); ?>">
                                                <?php echo esc_html($quote_info['number'] ?: $quote_info['title']); ?>
                                            </a>
                                        </span>
                                    <?php endif; ?>
                                </div>
                                <div class="row-actions mt-1">
                                    <span class="edit"><a href="<?php echo admin_url('admin.php?page=easy-invoice-builder&invoice_id=' . $invoice_id); ?>"><svg class="w-3.5 h-3.5 mr-1 inline-block" 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="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path></svg><?php _e('Edit', 'easy-invoice'); ?></a></span>
                                    <span class="publish"><a href="#" class="publish-invoice" data-invoice-id="<?php echo $invoice_id; ?>" data-invoice-number="<?php echo esc_attr($invoice_number); ?>"><svg class="w-3.5 h-3.5 mr-1 inline-block" 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="M5 13l4 4L19 7"></path></svg><?php _e('Publish', 'easy-invoice'); ?></a></span>
                                    <span class="trash"><a href="#" class="trash-invoice text-red-600" data-invoice-id="<?php echo $invoice_id; ?>" data-invoice-number="<?php echo esc_attr($invoice_number); ?>"><svg class="w-3.5 h-3.5 mr-1 inline-block" 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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg><?php _e('Trash', 'easy-invoice'); ?></a></span>
                                    <span class="email"><a href="#" class="email-invoice" data-invoice-id="<?php echo $invoice_id; ?>" data-invoice-number="<?php echo esc_attr($invoice_number); ?>"><svg class="w-3.5 h-3.5 mr-1 inline-block" 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="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path></svg><?php _e('Send Email', 'easy-invoice'); ?></a></span>
                                    <span class="pdf"><a href="<?php echo get_permalink($invoice_id); ?>?auto_download_pdf=1" target="_blank" class="download-pdf" data-invoice-id="<?php echo $invoice_id; ?>" data-invoice-number="<?php echo esc_attr($invoice_number); ?>"><svg class="w-3.5 h-3.5 mr-1 inline-block" 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 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 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><?php _e('Download PDF', 'easy-invoice'); ?></a></span>
                                    <?php if (!easy_invoice_has_pro()): ?>
                                    <span class="export premium-feature"><a href="#" class="export-invoice-pro-placeholder text-yellow-600 font-semibold" data-invoice-id="<?php echo $invoice_id; ?>" data-invoice-number="<?php echo esc_attr($invoice_number); ?>"><svg class="w-3.5 h-3.5 mr-1 inline-block text-yellow-500" 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 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 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>Export</a></span>
                                    <?php endif; ?>
                                    <?php if (!easy_invoice_has_pro()): ?>
                                    <span class="duplicate premium-feature"><a href="#" class="duplicate-invoice-pro-placeholder text-yellow-600 font-semibold" data-invoice-id="<?php echo $invoice_id; ?>" data-invoice-number="<?php echo esc_attr($invoice_number); ?>"><svg class="w-3.5 h-3.5 mr-1 inline-block text-yellow-500" 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="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 7l2 4 4 .5-3 2.5.5 4-3.5-2-3.5 2 .5-4-3-2.5 4-.5 2-4z"/></svg>Duplicate</a></span>
                                    <?php endif; ?>
                                    
                                    <?php 
                                    // Apply filter for Pro plugin to add secure link actions
                                    $secure_actions = apply_filters('easy_invoice_invoice_row_actions', [], $invoice);
                                    foreach ($secure_actions as $action_key => $action_html) {
                                        echo '<span class="' . esc_attr($action_key) . '">' . $action_html . '</span>';
                                    }
                                    ?>
                                </div>
                            <?php else: ?>
                                <div class="text-sm font-medium text-gray-900">
                                    <a href="<?php echo admin_url('admin.php?page=easy-invoice-builder&invoice_id=' . $invoice_id); ?>" class="text-indigo-600 hover:text-indigo-900">
                                        <?php echo apply_filters('easy_invoice_invoice_title', esc_html($display_title), $invoice); ?>
                                    </a>
                                </div>
                                <div class="text-xs text-gray-500 mt-1">
                                    <?php echo apply_filters('easy_invoice_invoice_number_display', esc_html($invoice_number), $invoice); ?>
                                    <?php
                                    // Check if this invoice was converted from a quote
                                    $quote_info = \EasyInvoice\Helpers\QuoteInvoiceHelper::getQuoteInfoFromInvoice($invoice_id);
                                    if ($quote_info): ?>
                                        <span class="ml-2 inline-flex items-center space-x-1">
                                            <i class="<?php echo esc_attr($quote_info['icon_class']); ?> text-blue-500 text-xs" title="<?php echo esc_attr($quote_info['tooltip_text']); ?>"></i>
                                            <a href="<?php echo esc_url($quote_info['url']); ?>" 
                                               target="_blank" 
                                               class="text-blue-600 hover:text-blue-800 hover:underline text-xs"
                                               title="<?php echo esc_attr($quote_info['tooltip_text']); ?>">
                                                <?php echo esc_html($quote_info['number'] ?: $quote_info['title']); ?>
                                            </a>
                                        </span>
                                    <?php endif; ?>
                                </div>
                                <div class="row-actions mt-1">
                                    <span class="view"><a href="<?php echo apply_filters('easy_invoice_invoice_view_url', get_permalink($invoice_id), $invoice_id); ?>" target="_blank"><svg class="w-3.5 h-3.5 mr-1 inline-block" 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="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path></svg><?php _e('View', 'easy-invoice'); ?></a></span>
                                    <span class="edit"><a href="<?php echo admin_url('admin.php?page=easy-invoice-builder&invoice_id=' . $invoice_id); ?>"><svg class="w-3.5 h-3.5 mr-1 inline-block" 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="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path></svg><?php _e('Edit', 'easy-invoice'); ?></a></span>
                                    <span class="draft"><a href="#" class="draft-invoice" data-invoice-id="<?php echo $invoice_id; ?>" data-invoice-number="<?php echo esc_attr($invoice_number); ?>"><svg class="w-3.5 h-3.5 mr-1 inline-block" 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><?php _e('Draft', 'easy-invoice'); ?></a></span>
                                    <span class="trash"><a href="#" class="trash-invoice text-red-600" data-invoice-id="<?php echo $invoice_id; ?>" data-invoice-number="<?php echo esc_attr($invoice_number); ?>"><svg class="w-3.5 h-3.5 mr-1 inline-block" 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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg><?php _e('Trash', 'easy-invoice'); ?></a></span>
                                    <span class="email"><a href="#" class="email-invoice" data-invoice-id="<?php echo $invoice_id; ?>" data-invoice-number="<?php echo esc_attr($invoice_number); ?>"><svg class="w-3.5 h-3.5 mr-1 inline-block" 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="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path></svg><?php _e('Send Email', 'easy-invoice'); ?></a></span>
                                    <span class="pdf"><a href="<?php echo get_permalink($invoice_id); ?>?auto_download_pdf=1" target="_blank" class="download-pdf" data-invoice-id="<?php echo $invoice_id; ?>" data-invoice-number="<?php echo esc_attr($invoice_number); ?>"><svg class="w-3.5 h-3.5 mr-1 inline-block" 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 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 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><?php _e('Download PDF', 'easy-invoice'); ?></a></span>
                                    <?php if (!easy_invoice_has_pro()): ?>
                                    <span class="export premium-feature"><a href="#" class="export-invoice-pro-placeholder text-yellow-600 font-semibold" data-invoice-id="<?php echo $invoice_id; ?>" data-invoice-number="<?php echo esc_attr($invoice_number); ?>"><svg class="w-3.5 h-3.5 mr-1 inline-block text-yellow-500" 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 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 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>Export</a></span>
                                    <?php endif; ?>
                                    <?php if (!easy_invoice_has_pro()): ?>
                                    <span class="duplicate premium-feature"><a href="#" class="duplicate-invoice-pro-placeholder text-yellow-600 font-semibold" data-invoice-id="<?php echo $invoice_id; ?>" data-invoice-number="<?php echo esc_attr($invoice_number); ?>"><svg class="w-3.5 h-3.5 mr-1 inline-block text-yellow-500" 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="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 7l2 4 4 .5-3 2.5.5 4-3.5-2-3.5 2 .5-4-3-2.5 4-.5 2-4z"/></svg>Duplicate</a></span>
                                    <?php endif; ?>
                                    
                                    <?php 
                                    // Apply filter for Pro plugin to add secure link actions
                                    $secure_actions = apply_filters('easy_invoice_invoice_row_actions', [], $invoice);
                                    foreach ($secure_actions as $action_key => $action_html) {
                                        echo '<span class="' . esc_attr($action_key) . '">' . $action_html . '</span>';
                                    }
                                    ?>
                                </div>
                            <?php endif; ?>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-900"><?php echo esc_html($client_name ?: 'No Client'); ?></div>
                            <div class="text-sm text-gray-500"><?php echo esc_html($client_email ?: ''); ?></div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="px-3 py-1 inline-flex text-xs leading-5 font-medium rounded-full <?php echo $status_class; ?>">
                                <?php echo ucfirst(esc_html($status)); ?>
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-700 font-medium">
                            <?php echo esc_html($amount); ?>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            <?php echo esc_html($due_date); ?>
                        </td>
                        <?php do_action('easy_invoice_after_invoice_listing_row', $invoice); ?>
                    </tr>
                    <?php endforeach; ?>
                    
                    <?php if (empty($invoices)): ?>
                        <tr>
                            <td colspan="7" class="px-6 py-4 text-center text-sm text-gray-500">
                                <?php if ($current_view === 'trash'): ?>
                                    No invoices found in trash.
                                <?php elseif ($current_view === 'draft'): ?>
                                    No invoices found in draft. <a href="#" class="text-indigo-600 hover:text-indigo-900 create-first-invoice">Create your first invoice</a>.
                                <?php else: ?>
                                    No invoices found. <a href="#" class="text-indigo-600 hover:text-indigo-900 create-first-invoice">Create your first invoice</a>.
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <!-- Pagination -->
    <?php if ($total_invoices > 0): ?>
    <div class="mt-4">
        <div class="px-4 py-3 flex items-center justify-between">
            <div class="flex items-center space-x-2">
                <span class="text-sm text-gray-700">
                    Showing 
                    <span class="font-medium"><?php echo number_format((($current_page - 1) * $per_page) + 1); ?></span>
                    to 
                    <span class="font-medium"><?php echo number_format(min($current_page * $per_page, $total_invoices)); ?></span>
                    of 
                    <span class="font-medium"><?php echo number_format($total_invoices); ?></span>
                    results
                </span>
            </div>
            <?php if ($total_pages > 1): ?>
            <div class="flex items-center space-x-2">
                <span class="text-sm text-gray-500">Page <?php echo number_format($current_page); ?> of <?php echo number_format($total_pages); ?></span>
                <?php
                // Use WordPress's built-in pagination for bottom
                $bottom_pagination_args = array(
                    'base' => add_query_arg('paged', '%#%'),
                    'format' => '',
                    'current' => $current_page,
                    'total' => $total_pages,
                    'prev_text' => '‹ Previous',
                    'next_text' => 'Next ›',
                    'type' => 'array',
                    'end_size' => 1,
                    'mid_size' => 2,
                    'add_args' => array(
                        'view' => $current_view,
                        'status' => $status_filter,
                        'recurring' => $recurring_filter
                    )
                );
                
                $bottom_pagination_links = paginate_links($bottom_pagination_args);
                
                if ($bottom_pagination_links) {
                    echo '<div class="flex space-x-1">';
                    foreach ($bottom_pagination_links as $link) {
                        // Add null check to prevent passing null to easy_invoice_str_replace
                        if ($link === null) {
                            continue;
                        }
                        
                        // Convert WordPress pagination to our styling
                        $link = easy_invoice_str_replace('page-numbers', 'px-3 py-2 text-sm font-medium border border-gray-300 rounded-md', $link);
                        $link = easy_invoice_str_replace('current', 'bg-indigo-50 border-indigo-500 text-indigo-600', $link);
                        $link = easy_invoice_str_replace('prev', 'bg-white text-gray-500 hover:bg-gray-50', $link);
                        $link = easy_invoice_str_replace('next', 'bg-white text-gray-500 hover:bg-gray-50', $link);
                        $link = easy_invoice_str_replace('dots', 'bg-white text-gray-700', $link);
                        
                        // Add default styling for regular page numbers
                        if ($link && strpos($link, 'bg-indigo-50') === false && strpos($link, 'bg-white') === false) {
                            $link = easy_invoice_str_replace('border-gray-300', 'border-gray-300 bg-white text-gray-500 hover:bg-gray-50', $link);
                        }
                        
                        echo $link;
                    }
                    echo '</div>';
                }
                ?>
            </div>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>
</div>

<!-- Delete Invoice Confirmation Modal -->
<div id="trash-invoice-modal" class="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center hidden z-50">
    <div class="bg-white rounded-lg shadow-xl max-w-md w-full p-6 relative">
        <button class="close-modal absolute top-4 right-4 text-gray-400 hover:text-gray-500">
            <i class="fas fa-times"></i>
        </button>
        <h2 class="text-xl font-medium text-gray-900 mb-4">Move to Trash</h2>
        <p class="text-sm text-gray-500 mb-4">Are you sure you want to move invoice <span id="trash-invoice-number" class="font-medium"></span> to trash?</p>
        
        <div class="mt-5 flex justify-end space-x-3">
            <button type="button" class="cancel-modal bg-white py-2 px-4 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                Cancel
            </button>
            <button type="button" id="confirm-trash" class="bg-red-600 py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500">
                Move to Trash
            </button>
        </div>
    </div>
</div>

<!-- Restore Invoice Confirmation Modal -->
<div id="restore-invoice-modal" class="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center hidden z-50">
    <div class="bg-white rounded-lg shadow-xl max-w-md w-full p-6 relative">
        <button class="close-modal absolute top-4 right-4 text-gray-400 hover:text-gray-500">
            <i class="fas fa-times"></i>
        </button>
        <h2 class="text-xl font-medium text-gray-900 mb-4">Restore Invoice</h2>
        <p class="text-sm text-gray-500 mb-4">Are you sure you want to restore invoice <span id="restore-invoice-number" class="font-medium"></span>?</p>
        
        <div class="mt-5 flex justify-end space-x-3">
            <button type="button" class="cancel-modal bg-white py-2 px-4 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                Cancel
            </button>
            <button type="button" id="confirm-restore" class="bg-indigo-600 py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                Restore Invoice
            </button>
        </div>
    </div>
</div>

<!-- Permanently Delete Invoice Confirmation Modal -->
<div id="delete-permanently-modal" class="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center hidden z-50">
    <div class="bg-white rounded-lg shadow-xl max-w-md w-full p-6 relative">
        <button class="close-modal absolute top-4 right-4 text-gray-400 hover:text-gray-500">
            <i class="fas fa-times"></i>
        </button>
        <h2 class="text-xl font-medium text-gray-900 mb-4">Delete Invoice Permanently</h2>
        <p class="text-sm text-gray-500 mb-4">Are you sure you want to permanently delete invoice <span id="delete-permanently-number" class="font-medium"></span>? This action cannot be undone.</p>
        
        <div class="mt-5 flex justify-end space-x-3">
            <button type="button" class="cancel-modal bg-white py-2 px-4 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                Cancel
            </button>
            <button type="button" id="confirm-delete-permanently" class="bg-red-600 py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500">
                Delete Permanently
            </button>
        </div>
    </div>
</div>

<!-- Publish Invoice Confirmation Modal -->
<div id="publish-invoice-modal" class="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center hidden z-50">
    <div class="bg-white rounded-lg shadow-xl max-w-md w-full p-6 relative">
        <button class="close-modal absolute top-4 right-4 text-gray-400 hover:text-gray-500">
            <i class="fas fa-times"></i>
        </button>
        <h2 class="text-xl font-medium text-gray-900 mb-4">Publish Invoice</h2>
        <p class="text-sm text-gray-500 mb-4">Are you sure you want to publish invoice <span id="publish-invoice-number" class="font-medium"></span>?</p>
        
        <div class="mt-5 flex justify-end space-x-3">
            <button type="button" class="cancel-modal bg-white py-2 px-4 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                Cancel
            </button>
            <button type="button" id="confirm-publish" class="bg-green-600 py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500">
                Publish Invoice
            </button>
        </div>
    </div>
</div>

<!-- Draft Invoice Confirmation Modal -->
<div id="draft-invoice-modal" class="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center hidden z-50">
    <div class="bg-white rounded-lg shadow-xl max-w-md w-full p-6 relative">
        <button class="close-modal absolute top-4 right-4 text-gray-400 hover:text-gray-500">
            <i class="fas fa-times"></i>
        </button>
        <h2 class="text-xl font-medium text-gray-900 mb-4">Set Invoice to Draft</h2>
        <p class="text-sm text-gray-500 mb-4">Are you sure you want to set invoice <span id="draft-invoice-number" class="font-medium"></span> to draft status?</p>
        
        <div class="mt-5 flex justify-end space-x-3">
            <button type="button" class="cancel-modal bg-white py-2 px-4 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                Cancel
            </button>
            <button type="button" id="confirm-draft" class="bg-indigo-600 py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                Set to Draft
            </button>
        </div>
    </div>
</div>

<style>
/* Modern row actions styling */
.row-actions {
    visibility: hidden;
    font-size: 12px;
    padding-top: 4px;
    display: flex;
    gap: 8px;
}

tr:hover .row-actions {
    visibility: visible;
}

.row-actions span a {
    color: #6366f1; /* indigo-500 */
    text-decoration: none;
    transition: all 0.2s;
    display: inline-flex;
    align-items: center;
}

.row-actions span a:hover {
    color: #4f46e5; /* indigo-600 */
    text-decoration: none;
}

.row-actions span a.text-red-600 {
    color: #dc2626; /* red-600 */
}

.row-actions span a.text-red-600:hover {
    color: #b91c1c; /* red-700 */
}

/* Add subtle separators between action links */
.row-actions span:not(:last-child)::after {
    content: "";
    display: inline-block;
    width: 3px;
    height: 3px;
    border-radius: 50%;
    background-color: #d1d5db; /* gray-300 */
    margin-left: 8px;
    vertical-align: middle;
}

/* Premium duplicate button styling */
.premium-feature .premium-duplicate-btn {
    border: 1.5px solid #FFD700;
    background: linear-gradient(90deg, #fffbe6 0%, #fff8dc 100%);
    box-shadow: 0 0 6px 0 #ffe06633;
    position: relative;
    transition: box-shadow 0.2s, border-color 0.2s;
}
.premium-feature .premium-duplicate-btn:hover {
    box-shadow: 0 0 16px 2px #ffd70099, 0 0 0 2px #fffbe6;
    border-color: #FFA500;
    animation: shimmer 1.2s linear infinite;
}
@keyframes shimmer {
    0% { box-shadow: 0 0 6px 0 #ffe06633; }
    50% { box-shadow: 0 0 24px 4px #ffd700cc; }
    100% { box-shadow: 0 0 6px 0 #ffe06633; }
}
.premium-feature .premium-tooltip {
    opacity: 0;
    pointer-events: none;
    position: absolute;
    left: 50%;
    top: 120%;
    transform: translateX(-50%);
    background: #222;
    color: #fffbe6;
    padding: 3px 10px;
    border-radius: 4px;
    font-size: 11px;
    white-space: nowrap;
    z-index: 10;
    transition: opacity 0.2s;
    box-shadow: 0 2px 8px #0002;
}
.premium-feature .group:hover .premium-tooltip {
    opacity: 1;
}
.premium-feature .premium-duplicate-icon {
    filter: drop-shadow(0 0 2px #ffd700);
}

/* Premium Export Button Styling - Minimal */
.premium-export-btn {
    border-color: #d1d5db;
    transition: all 0.2s ease;
}

.premium-export-btn:hover {
    border-color: #9ca3af;
    background-color: #f9fafb;
}

.premium-export-btn .crown-icon {
    filter: drop-shadow(0 1px 3px rgba(0, 0, 0, 0.2));
    color: #9333ea;
    transition: all 0.3s ease;
}

.premium-export-btn:hover .crown-icon {
    filter: drop-shadow(0 2px 6px rgba(147, 51, 234, 0.3));
    transform: scale(1.1);
    color: #7c3aed;
}
</style>

<?php
// Localize script data for AJAX operations
$script_data = array(
    'ajaxUrl' => admin_url('admin-ajax.php'),
    'nonce' => wp_create_nonce('easy_invoice_nonce')
);
?>
<script type="text/javascript">
    // Make sure easyInvoice object is available for the AJAX operations
    var easyInvoice = <?php echo json_encode($script_data); ?>;
    
    jQuery(document).ready(function($) {
        var selectedInvoiceId = null;
        
        // Select All Checkboxes
        $("#select-all").on("click", function() {
            $(".invoice-checkbox").prop("checked", $(this).prop("checked"));
        });
        
        // Check if any checkbox is unchecked and update select all
        $(".invoice-checkbox").on("click", function() {
            if (!$(this).prop("checked")) {
                $("#select-all").prop("checked", false);
            } else {
                // Check if all checkboxes are checked
                var allChecked = true;
                $(".invoice-checkbox").each(function() {
                    if (!$(this).prop("checked")) {
                        allChecked = false;
                        return false; // Break the loop
                    }
                });
                $("#select-all").prop("checked", allChecked);
            }
        });
        
        // Open trash modal when Trash link is clicked
        $(".trash-invoice").on("click", function(e) {
            e.preventDefault();
            selectedInvoiceId = $(this).data("invoice-id");
            var invoiceNumber = $(this).data("invoice-number");
            
            $("#trash-invoice-number").text(invoiceNumber);
            $("#trash-invoice-modal").removeClass("hidden");
        });
        
        // Open restore modal when Restore link is clicked
        $(".restore-invoice").on("click", function(e) {
            e.preventDefault();
            selectedInvoiceId = $(this).data("invoice-id");
            var invoiceNumber = $(this).data("invoice-number");
            
            $("#restore-invoice-number").text(invoiceNumber);
            $("#restore-invoice-modal").removeClass("hidden");
        });
        
        // Open delete permanently modal
        $(".delete-permanently").on("click", function(e) {
            e.preventDefault();
            selectedInvoiceId = $(this).data("invoice-id");
            var invoiceNumber = $(this).data("invoice-number");
            
            $("#delete-permanently-number").text(invoiceNumber);
            $("#delete-permanently-modal").removeClass("hidden");
        });
        
        // Open publish invoice modal
        $(".publish-invoice").on("click", function(e) {
            e.preventDefault();
            selectedInvoiceId = $(this).data("invoice-id");
            var invoiceNumber = $(this).data("invoice-number");
            
            $("#publish-invoice-number").text(invoiceNumber);
            $("#publish-invoice-modal").removeClass("hidden");
        });
        
        // Open draft invoice modal
        $(".draft-invoice").on("click", function(e) {
            e.preventDefault();
            selectedInvoiceId = $(this).data("invoice-id");
            var invoiceNumber = $(this).data("invoice-number");
            
            $("#draft-invoice-number").text(invoiceNumber);
            $("#draft-invoice-modal").removeClass("hidden");
        });
        
        // Handle Email Invoice click
        $(".email-invoice").on("click", function(e) {
            e.preventDefault();
            var invoiceId = $(this).data("invoice-id");
            var invoiceNumber = $(this).data("invoice-number");
            
            // Use the new confirmation system instead of browser confirm
            if (typeof EasyInvoiceConfirmation !== 'undefined') {
                EasyInvoiceConfirmation.confirmAction('send email', 'invoice ' + invoiceNumber, function() {
                    // Show loading state
                    var $link = $(this);
                    var originalText = $link.text();
                    $link.text("Sending...").css("opacity", "0.7");
                    
                    // Send AJAX request
                    $.ajax({
                        url: easyInvoice.ajaxUrl,
                        type: "POST",
                        data: {
                            action: "easy_invoice_send_email",
                            invoice_id: invoiceId,
                            nonce: easyInvoice.nonce
                        },
                        success: function(response) {
                            if (response.success) {
                                EasyInvoiceToast.success("Email sent successfully!");
                            } else {
                                EasyInvoiceToast.error(response.data.message || "Error sending email");
                            }
                            // Reset link text
                            $link.text(originalText).css("opacity", "1");
                        },
                        error: function() {
                            EasyInvoiceToast.error("Error connecting to server");
                            // Reset link text
                            $link.text(originalText).css("opacity", "1");
                        }
                    });
                });
            } else {
                // Fallback to browser confirm if toast system not available
                if (confirm("Are you sure you want to send invoice " + invoiceNumber + " via email?")) {
                    // Show loading state
                    var $link = $(this);
                    var originalText = $link.text();
                    $link.text("Sending...").css("opacity", "0.7");
                    
                    // Send AJAX request
                    $.ajax({
                        url: easyInvoice.ajaxUrl,
                        type: "POST",
                        data: {
                            action: "easy_invoice_send_email",
                            invoice_id: invoiceId,
                            nonce: easyInvoice.nonce
                        },
                        success: function(response) {
                            if (response.success) {
                                EasyInvoiceToast.success("Email sent successfully!");
                            } else {
                                EasyInvoiceToast.error(response.data.message || "Error sending email");
                            }
                            // Reset link text
                            $link.text(originalText).css("opacity", "1");
                        },
                        error: function() {
                            EasyInvoiceToast.error("Error connecting to server");
                            // Reset link text
                            $link.text(originalText).css("opacity", "1");
                        }
                    });
                }
            }
        });
        
        // Handle Download PDF click
        $(".download-pdf").on("click", function(e) {
            e.preventDefault();
            var invoiceId = $(this).data("invoice-id");
            var invoiceNumber = $(this).data("invoice-number");
            
            // Show loading state
            var $link = $(this);
            var originalText = $link.text();
            $link.text("Generating PDF...").css("opacity", "0.7");
            
            // Get invoice data via AJAX and generate PDF
            $.ajax({
                url: easyInvoice.ajaxUrl,
                type: "POST",
                data: {
                    action: "easy_invoice_download_invoice_pdf",
                    invoice_id: invoiceId,
                    nonce: easyInvoice.nonce
                },
                success: function(response) {
                if (response.success && response.data.download_url) {
                    // Open the download URL in a new tab
                    window.open(response.data.download_url, '_blank');
                    EasyInvoiceToast.success("PDF download started");
                } else {
                    EasyInvoiceToast.error(response.data.message || "Error preparing PDF data");
                }
                // Reset link text
                $link.text(originalText).css("opacity", "1");
            },
                error: function() {
                    EasyInvoiceToast.error("Error connecting to server");
                    // Reset link text
                    $link.text(originalText).css("opacity", "1");
                }
            });
        });
        
        // Close modals when Close button or Cancel is clicked
        $(".close-modal, .cancel-modal").on("click", function() {
            $(".fixed").addClass("hidden");
            selectedInvoiceId = null;
        });
        
        // Handle trash confirmation
        $("#confirm-trash").on("click", function() {
            if (selectedInvoiceId) {
                // Send AJAX request to trash the invoice
                $.ajax({
                    url: easyInvoice.ajaxUrl,
                    type: "POST",
                    data: {
                        action: "easy_invoice_trash_invoice",
                        invoice_id: selectedInvoiceId,
                        nonce: easyInvoice.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            // Reload the page to show updated list
                            window.location.reload();
                        } else {
                            EasyInvoiceToast.error(response.data.message || "Error trashing invoice");
                        }
                    },
                    error: function() {
                        EasyInvoiceToast.error("Error connecting to server");
                    }
                });
            }
        });
        
        // Handle restore confirmation
        $("#confirm-restore").on("click", function() {
            if (selectedInvoiceId) {
                // Send AJAX request to restore the invoice
                $.ajax({
                    url: easyInvoice.ajaxUrl,
                    type: "POST",
                    data: {
                        action: "easy_invoice_restore_invoice",
                        invoice_id: selectedInvoiceId,
                        nonce: easyInvoice.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            // Reload the page to show updated list
                            window.location.reload();
                        } else {
                            EasyInvoiceToast.error(response.data.message || "Error restoring invoice");
                        }
                    },
                    error: function() {
                        EasyInvoiceToast.error("Error connecting to server");
                    }
                });
            }
        });
        
        // Handle publish confirmation
        $("#confirm-publish").on("click", function() {
            if (selectedInvoiceId) {
                // Send AJAX request to publish the invoice
                $.ajax({
                    url: easyInvoice.ajaxUrl,
                    type: "POST",
                    data: {
                        action: "easy_invoice_publish_invoice",
                        invoice_id: selectedInvoiceId,
                        nonce: easyInvoice.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            // Reload the page to show updated list
                            window.location.reload();
                        } else {
                            EasyInvoiceToast.error(response.data.message || "Error publishing invoice");
                        }
                    },
                    error: function() {
                        EasyInvoiceToast.error("Error connecting to server");
                    }
                });
            }
        });
        
        // Handle draft confirmation
        $("#confirm-draft").on("click", function() {
            if (selectedInvoiceId) {
                // Send AJAX request to set the invoice to draft
                $.ajax({
                    url: easyInvoice.ajaxUrl,
                    type: "POST",
                    data: {
                        action: "easy_invoice_draft_invoice",
                        invoice_id: selectedInvoiceId,
                        nonce: easyInvoice.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            // Reload the page to show updated list
                            window.location.reload();
                        } else {
                            EasyInvoiceToast.error(response.data.message || "Error setting invoice to draft");
                        }
                    },
                    error: function() {
                        EasyInvoiceToast.error("Error connecting to server");
                    }
                });
            }
        });
        
        // Handle delete permanently confirmation
        $("#confirm-delete-permanently").on("click", function() {
            if (selectedInvoiceId) {
                // Send AJAX request to delete the invoice permanently
                $.ajax({
                    url: easyInvoice.ajaxUrl,
                    type: "POST",
                    data: {
                        action: "easy_invoice_delete_invoice_permanently",
                        invoice_id: selectedInvoiceId,
                        nonce: easyInvoice.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            // Reload the page to show updated list
                            window.location.reload();
                        } else {
                            EasyInvoiceToast.error(response.data.message || "Error deleting invoice");
                        }
                    },
                    error: function() {
                        EasyInvoiceToast.error("Error connecting to server");
                    }
                });
            }
        });
        
        // Form submission validation for bulk actions
        $("#bulk-action-form").on("submit", function(e) {
            // Check if an action is selected
            var bulkAction = $("select[name='bulk_action']").val();
            if (!bulkAction) {
                e.preventDefault();
                EasyInvoiceToast.warning("Please select an action");
                return false;
            }
            
            // Check if at least one invoice is selected
            var checkedInvoices = $(".invoice-checkbox:checked").length;
            if (checkedInvoices < 1) {
                e.preventDefault();
                EasyInvoiceToast.warning("Please select at least one invoice");
                return false;
            }
            
            // Confirm bulk actions using the new confirmation system
            if (bulkAction === 'trash') {
                e.preventDefault();
                if (typeof EasyInvoiceConfirmation !== 'undefined') {
                    EasyInvoiceConfirmation.confirmAction('move to trash', 'the selected invoices', function() {
                        $("#bulk-action-form")[0].submit();
                    });
                } else {
                    // Fallback to browser confirm
                    if (!confirm('Are you sure you want to move the selected invoices to trash?')) {
                        return false;
                    }
                }
                return false;
            } else if (bulkAction === 'delete') {
                e.preventDefault();
                if (typeof EasyInvoiceConfirmation !== 'undefined') {
                    EasyInvoiceConfirmation.confirmAction('permanently delete', 'the selected invoices', function() {
                        $("#bulk-action-form")[0].submit();
                    });
                } else {
                    // Fallback to browser confirm
                    if (!confirm('Are you sure you want to permanently delete the selected invoices? This cannot be undone.')) {
                        return false;
                    }
                }
                return false;
            }
            
            return true;
        });
        
        // Dismiss notifications
        $(".notification-dismiss").on("click", function() {
            $(this).closest(".rounded-md").fadeOut(300, function() {
                $(this).remove();
            });
        });

        // Duplicate invoice functionality
        $(document).on('click', '.duplicate-invoice-pro-placeholder', function(e) {
            e.preventDefault();
            EasyInvoiceConfirmation.showFeatureUpgrade('Invoice Duplication');
        });

        // Export invoice functionality
        $(document).on('click', '.export-invoice-pro-placeholder', function(e) {
            e.preventDefault();
            EasyInvoiceConfirmation.showFeatureUpgrade('Invoice Export', 'Export your invoices to CSV, Excel, or PDF format for backup, analysis, or sharing with your team.');
        });

        // Handle "Create Sample Invoice" button click
        $('#easy-invoice-create-sample').on('click', function() {
            var $button = $(this);
            var original_text = $button.html();
            $button.html('Creating...').prop('disabled', true);

            $.ajax({
                url: ajaxurl, // WordPress AJAX URL
                type: 'POST',
                data: {
                    action: 'easy_invoice_create_sample_invoice',
                    nonce: '<?php echo wp_create_nonce("easy_invoice_admin_nonce"); ?>' // Make sure this nonce matches the one checked in PHP
                },
                success: function(response) {
                    if (response.success) {
                        EasyInvoiceToast.success(response.data.message + ' You can edit it at: ' + response.data.edit_link);
                        // Optionally, refresh the page or redirect
                        window.location.reload(); 
                    } else {
                        EasyInvoiceToast.error('Error: ' + response.data.message);
                    }
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    EasyInvoiceToast.error('AJAX Error: ' + textStatus + ' - ' + errorThrown);
                },
                complete: function() {
                    $button.html(original_text).prop('disabled', false);
                }
            });
        });
    });
</script>

<!-- New Invoice Modal -->
<div id="new-invoice-modal" class="fixed inset-0 bg-gray-600 bg-opacity-75 overflow-y-auto h-full w-full z-50 hidden">
    <div class="relative mx-auto p-6 border w-96 shadow-xl rounded-lg bg-white my-20">
        <div class="flex justify-between items-center mb-6">
                            <h3 class="text-xl font-semibold text-gray-900"><?php esc_html_e('Create New Invoice', 'easy-invoice'); ?></h3>
            <button type="button" id="close-new-invoice-modal" class="text-gray-400 hover:text-gray-600 transition-colors duration-200">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                </svg>
            </button>
        </div>
        
        <form id="new-invoice-form" class="space-y-6">
            <div>
                <label for="new_invoice_title" class="block text-sm font-medium text-gray-700 mb-2">Invoice Title *</label>
                <input type="text" 
                       name="new_invoice_title" 
                       id="new_invoice_title" 
                       required 
                       placeholder="Enter invoice title..."
                       class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-3 px-4 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm transition-colors duration-200">
                <p class="mt-2 text-sm text-gray-500">This will be the title of your invoice</p>
            </div>
            
            <div class="flex justify-end space-x-3 pt-4">
                <button type="button" id="cancel-new-invoice" 
                        class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors duration-200">
                    Cancel
                </button>
                <button type="submit" 
                        class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors duration-200">
                    Create Invoice
                </button>
            </div>
        </form>
        
        <div id="new-invoice-message" class="mt-4 hidden"></div>
    </div>
</div>

<script>
jQuery(document).ready(function($) {
    // Initialize easyInvoice object for AJAX calls
    window.easyInvoice = {
        ajaxUrl: '<?php echo admin_url('admin-ajax.php'); ?>',
        nonce: '<?php echo wp_create_nonce('easy_invoice_nonce'); ?>',
        isPro: <?php echo easy_invoice_has_pro() ? 'true' : 'false'; ?>
    };
    
    // New Invoice Modal Functionality
    $('#create-new-invoice-btn').on('click', function(e) {
        e.preventDefault(); // Prevent the default link behavior
        $('#new-invoice-modal').removeClass('hidden');
        $('#new_invoice_title').focus();
    });
    
    // Handle "Create your first invoice" links
    $(document).on('click', '.create-first-invoice', function(e) {
        e.preventDefault(); // Prevent the default link behavior
        $('#new-invoice-modal').removeClass('hidden');
        $('#new_invoice_title').focus();
    });
    
    $('#close-new-invoice-modal, #cancel-new-invoice').on('click', function() {
        $('#new-invoice-modal').addClass('hidden');
        $('#new-invoice-form')[0].reset();
        $('#new-invoice-message').addClass('hidden').html('');
    });
    
    // Close modal when clicking outside
    $('#new-invoice-modal').on('click', function(e) {
        if (e.target === this) {
            $(this).addClass('hidden');
            $('#new-invoice-form')[0].reset();
            $('#new-invoice-message').addClass('hidden').html('');
        }
    });
    
    // Handle form submission
    $('#new-invoice-form').on('submit', function(e) {
        e.preventDefault();
        
        var $form = $(this);
        var $submitBtn = $form.find('button[type="submit"]');
        var $message = $('#new-invoice-message');
        var title = $('#new_invoice_title').val().trim();
        
        if (!title) {
            $message.removeClass('hidden').html('<div class="text-red-600 text-sm">Please enter an invoice title.</div>');
            return;
        }
        
        // Show loading state
        $submitBtn.prop('disabled', true).html('Creating...');
        $message.addClass('hidden');
        
        $.ajax({
            url: easyInvoice.ajaxUrl,
            type: 'POST',
            data: {
                action: 'easy_invoice_create_new_invoice',
                title: title,
                nonce: easyInvoice.nonce
            },
            success: function(response) {
                if (response.success) {
                    // Show success message
                    $message.removeClass('hidden').html('<div class="text-green-600 text-sm">Invoice created successfully! Redirecting...</div>');
                    
                    // Redirect to the builder page with the new invoice ID
                    setTimeout(function() {
                        window.location.href = response.data.redirect_url;
                    }, 1000);
                } else {
                    $message.removeClass('hidden').html('<div class="text-red-600 text-sm">' + (response.data.message || 'Error creating invoice.') + '</div>');
                    $submitBtn.prop('disabled', false).html('Create Invoice');
                }
            },
            error: function() {
                $message.removeClass('hidden').html('<div class="text-red-600 text-sm">Error connecting to server. Please try again.</div>');
                $submitBtn.prop('disabled', false).html('Create Invoice');
            }
        });
    });
});
</script>
<?php
