<?php
/**
 * Quote Listing Template
 *
 * @package     EasyInvoice
 * @since       1.0.0
 */

// Initialize variables
$quotes = $quotes ?? [];
$stats = $stats ?? [
    'total' => 0,
    'available' => 0,
    'draft' => 0,
    'sent' => 0,
    'accepted' => 0,
    'declined' => 0,
    'cancelled' => 0,
    'expired' => 0
];

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

// Define status filters
$status_filters = array(
    'available' => 'Available',
    'draft' => 'Draft',
    'sent' => 'Sent',
    'accepted' => 'Accepted',
    'declined' => 'Declined',
    'cancelled' => 'Trash',
    'expired' => 'Expired'
);

// Extract quote data for statistics
$formatted_quotes = array();
foreach ($quotes as $quote) {
    // For Quote model objects
    if (is_object($quote)) {
        $formatted_quotes[] = array(
            'id' => $quote->getId(),
            'amount' => $quote->getTotal(),
            'status' => $quote->getStatus(),
        );
    } else {
        // For already formatted quote arrays
        $formatted_quotes[] = array(
            'id' => $quote['id'],
            'amount' => isset($quote['total_amount']) ? $quote['total_amount'] : $quote['amount'],
            'status' => $quote['status'],
        );
    }
}

// Group quotes by currency for proper total calculation
$currency_totals = [];
$total_quotes = count($formatted_quotes);

foreach ($quotes as $quote) {
    if (is_object($quote)) {
        $currency_code = $quote->getCurrencyCode() ?: 'USD';
        $amount = $quote->getTotal() ?: 0;

        if (!isset($currency_totals[$currency_code])) {
            $currency_totals[$currency_code] = [
                'total' => 0,
                'quotes' => 0,
                'quote_object' => $quote // Keep reference for formatting
            ];
        }

        $currency_totals[$currency_code]['total'] += floatval($amount);
        $currency_totals[$currency_code]['quotes']++;
    }
}

$enhanced_stats = [
    'total_quotes' => $total_quotes,
    'currency_totals' => $currency_totals,
    'accepted_quotes' => count(array_filter($formatted_quotes, function($quote) {
        return $quote['status'] === 'accepted';
    })),
    'pending_quotes' => count(array_filter($formatted_quotes, function($quote) {
        return $quote['status'] === 'sent' || $quote['status'] === 'draft';
    })),
    'rejected_quotes' => count(array_filter($formatted_quotes, function($quote) {
        return $quote['status'] === 'rejected';
    }))
];

?>
<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('Quotes', 'easy-invoice'); ?></h1>
                <p class="mt-1 text-sm text-gray-500"><?php _e('Manage and track your quotes', '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-quotes-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-quotes-btn').on('click', function(e) {
                        e.preventDefault();
                        // Show premium popup using the proper confirmation modal
                        if (typeof EasyInvoiceConfirmation !== 'undefined') {
                            EasyInvoiceConfirmation.showFeatureUpgrade('Export All Quotes', 'Export all your quotes 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 quotes 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_quotes" />
                    <input type="hidden" name="_wpnonce" value="<?php echo wp_create_nonce('easy_invoice_export_all_quotes'); ?>" />
                    <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; ?>
                <button type="button" id="create-quote-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 Quote', 'easy-invoice'); ?>
                </button>
            </div>
        </div>
    </div>

    <!-- New Quote Modal -->
    <div id="new-quote-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">Create New Quote</h3>
                <button type="button" id="close-new-quote-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-quote-form" class="space-y-6">
                <div>
                    <label for="new_quote_title" class="block text-sm font-medium text-gray-700 mb-2">Quote Title *</label>
                    <input type="text"
                           name="new_quote_title"
                           id="new_quote_title"
                           required
                           placeholder="Enter quote 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 quote</p>
                </div>

                <div class="flex justify-end space-x-3 pt-4">
                    <button type="button" id="cancel-new-quote"
                            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 Quote
                    </button>
                </div>
            </form>

            <div id="new-quote-message" class="mt-4 hidden"></div>
        </div>
    </div>

    <!-- Logs Modal -->
    <div id="logs-modal" class="fixed z-50 inset-0 overflow-y-auto hidden">
        <div class="flex items-center justify-center min-h-screen px-4">
            <div class="fixed inset-0 transition-opacity" aria-hidden="true">
                <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
            </div>
            <div class="bg-white rounded-lg overflow-hidden shadow-xl transform transition-all sm:max-w-2xl w-full z-50">
                <div class="px-6 py-4 border-b border-gray-200">
                    <div class="flex justify-between items-center">
                        <h3 class="text-lg font-medium text-gray-900">Quote Activity Logs</h3>
                        <button type="button" id="close-logs-modal" class="text-gray-400 hover:text-gray-500 focus:outline-none">
                            <span class="sr-only">Close</span>
                            <svg class="w-6 h-6" 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="M6 18L18 6M6 6l12 12"></path>
                            </svg>
                        </button>
                    </div>
                </div>
                <div class="px-6 py-4 modal-body">
                    <!-- Logs content will be loaded here -->
                </div>
            </div>
        </div>
    </div>

    <!-- Stats Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8 mt-8">
        <div class="bg-white rounded-lg shadow p-6 transition-transform duration-300 hover:shadow-md hover:-translate-y-1">
            <div class="flex items-center">
                <div class="rounded-full bg-indigo-100 p-3 mr-4">
                    <svg class="w-6 h-6 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                    </svg>
                </div>
                <div>
                    <h3 class="text-sm font-medium text-gray-500">Total Quotes</h3>
                    <p class="mt-1 text-2xl font-bold text-gray-900"><?php echo $enhanced_stats['total_quotes']; ?></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 Value</h3>
                    <?php if (empty($enhanced_stats['currency_totals'])): ?>
                        <p class="mt-1 text-2xl font-bold text-gray-900">$0.00</p>
                    <?php else: ?>
                        <div class="mt-1 space-y-1">
                            <?php foreach ($enhanced_stats['currency_totals'] as $currency_code => $currency_data): ?>
                                <?php
                                $formatter = new \EasyInvoice\Helpers\QuoteFormatter($currency_data['quote_object']);
                                $formatted_amount = $formatter->format($currency_data['total']);
                                ?>
                                <div class="flex items-center justify-between">
                                    <span class="text-lg font-bold text-gray-900"><?php echo $formatted_amount; ?></span>
                                    <span class="text-xs text-gray-500 bg-gray-100 px-2 py-1 rounded"><?php echo $currency_data['quotes']; ?> quote<?php echo $currency_data['quotes'] > 1 ? 's' : ''; ?></span>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?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">Accepted Quotes</h3>
                    <p class="mt-1 text-2xl font-bold text-green-600"><?php echo $enhanced_stats['accepted_quotes']; ?></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 Quotes</h3>
                    <p class="mt-1 text-2xl font-bold text-yellow-600"><?php echo $enhanced_stats['pending_quotes']; ?></p>
                </div>
            </div>
        </div>
    </div>

    <!-- Top Pagination -->
    <?php if (isset($pagination) && $pagination['total_pages'] > 1): ?>
    <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 (($pagination['current_page'] - 1) * $pagination['per_page']) + 1; ?></span>
                    to
                    <span class="font-medium"><?php echo min($pagination['current_page'] * $pagination['per_page'], $pagination['total_quotes']); ?></span>
                    of
                    <span class="font-medium"><?php echo $pagination['total_quotes']; ?></span>
                    results
                </span>
            </div>
            <div class="flex items-center space-x-2">
                <span class="text-sm text-gray-500">Page <?php echo $pagination['current_page']; ?> of <?php echo $pagination['total_pages']; ?></span>
                <div class="flex space-x-1">
                    <?php
                    $prev_page = $pagination['current_page'] > 1 ? $pagination['current_page'] - 1 : 1;
                    $next_page = $pagination['current_page'] < $pagination['total_pages'] ? $pagination['current_page'] + 1 : $pagination['total_pages'];
                    $current_url = add_query_arg($_GET, admin_url('admin.php'));
                    $current_url = remove_query_arg('paged', $current_url);
                    $start_page = max(1, $pagination['current_page'] - 2);
                    $end_page = min($pagination['total_pages'], $pagination['current_page'] + 2);
                    if ($pagination['current_page'] > 1): ?>
                        <a class="bg-white text-gray-500 hover:bg-gray-50 px-3 py-2 text-sm font-medium border border-gray-300 rounded-md" href="<?php echo esc_url(add_query_arg('paged', $prev_page, $current_url)); ?>">‹ Previous</a>
                    <?php endif;
                    for ($i = $start_page; $i <= $end_page; $i++):
                        if ($i == $pagination['current_page']): ?>
                            <span class="px-3 py-2 text-sm font-medium border border-gray-300 rounded-md bg-indigo-50 border-indigo-500 text-indigo-600"><?php echo $i; ?></span>
                        <?php else: ?>
                            <a class="px-3 py-2 text-sm font-medium border border-gray-300 bg-white text-gray-500 hover:bg-gray-50 rounded-md" href="<?php echo esc_url(add_query_arg('paged', $i, $current_url)); ?>"><?php echo $i; ?></a>
                        <?php endif;
                    endfor;
                    if ($pagination['current_page'] < $pagination['total_pages']): ?>
                        <a class="bg-white text-gray-500 hover:bg-gray-50 px-3 py-2 text-sm font-medium border border-gray-300 rounded-md" href="<?php echo esc_url(add_query_arg('paged', $next_page, $current_url)); ?>">Next ›</a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- Main Content Area -->
    <div class="bg-white shadow rounded-lg">
        <!-- Navigation Tabs -->
        <div class="border-b border-gray-200 bg-gradient-to-r from-indigo-50 to-white">
            <nav class="flex">
                <?php
                // Use the counts passed from the controller
                $status_counts = [
                    'all' => $all_count ?? 0,
                    'available' => $available_count ?? 0,
                    'draft' => $draft_count ?? 0,
                    'sent' => $sent_count ?? 0,
                    'accepted' => $accepted_count ?? 0,
                    'declined' => $declined_count ?? 0,
                    'cancelled' => $trash_count ?? 0,
                    'expired' => $expired_count ?? 0
                ];

                // Define tabs with their labels and status values
                $tabs = [
                    'all' => __('All Quotes', 'easy-invoice'),
                    'available' => __('Available', 'easy-invoice'),
                    'draft' => __('Draft', 'easy-invoice'),
                    'sent' => __('Sent', 'easy-invoice'),
                    'accepted' => __('Accepted', 'easy-invoice'),
                    'declined' => __('Declined', 'easy-invoice'),
                    'cancelled' => __('Trash', 'easy-invoice'),
                    'expired' => __('Expired', 'easy-invoice')
                ];

                foreach ($tabs as $tab_key => $tab_label):
                    $is_active = ($view === $tab_key);
                    $count = $status_counts[$tab_key] ?? 0;
                    $class = $is_active
                        ? '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="<?php echo esc_url(add_query_arg('view', $tab_key, remove_query_arg('status'))); ?>"
                   class="flex items-center whitespace-nowrap py-4 px-6 font-medium text-sm transition-colors duration-200 <?php echo $class; ?>">
                    <?php if ($tab_key === '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 ($tab_key === '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 ($tab_key === 'sent'): ?>
                        <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 19l9 2-9-18-9 18 9-2zm0 0v-8"></path>
                        </svg>
                    <?php elseif ($tab_key === 'accepted'): ?>
                        <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="M5 13l4 4L19 7"></path>
                        </svg>
                    <?php elseif ($tab_key === 'declined'): ?>
                        <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="M6 18L18 6M6 6l12 12"></path>
                        </svg>
                    <?php elseif ($tab_key === 'cancelled'): ?>
                        <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="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                        </svg>
                    <?php elseif ($tab_key === 'expired'): ?>
                        <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 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                        </svg>
                    <?php elseif ($tab_key === 'available'): ?>
                        <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 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                        </svg>
                    <?php endif; ?>
                    <?php echo $tab_label; ?> (<?php echo $count; ?>)
                </a>
                <?php endforeach; ?>
            </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">
                    <input type="hidden" name="nonce" value="<?php echo wp_create_nonce('easy_invoice_admin_nonce'); ?>">

                    <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 ($view === 'cancelled'): ?>
                            <option value="restore">Restore Selected</option>
                            <option value="delete">Delete Permanently</option>
                        <?php else: ?>
                            <option value="delete">Delete Selected</option>
                            <option value="trash">Move to Trash</option>
                            <option value="draft">Move to Draft</option>
                        <?php endif; ?>
                        <option value="export">Export Selected</option>
                    </select>

                    <button type="submit" class="inline-flex items-center justify-center h-9 px-4 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>

                    <?php if ($view === 'cancelled' && !empty($quotes)): ?>
                        <button type="button" id="empty-trash-btn" class="inline-flex items-center justify-center h-9 px-6 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 whitespace-nowrap">
                            <svg class="w-4 h-4 mr-2 flex-shrink-0" 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>
                            Empty Trash
                        </button>
                    <?php endif; ?>
                </form>
            </div>

            <!-- 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-quotes-all">
                    <input type="hidden" name="view" value="<?php echo esc_attr($view); ?>">
                    <?php if (!empty($status_filter)): ?>
                        <input type="hidden" name="status" value="<?php echo esc_attr($status_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 quotes, 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>
        </div>

        <!-- Quotes Table -->
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            <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">
                            Quote
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Client
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Amount
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Status
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Issue Date
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Expiry Date
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Logs
                        </th>
                        <th scope="col" class="relative px-6 py-3">
                            <span class="sr-only">Actions</span>
                        </th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php if (empty($quotes)): ?>
                        <tr>
                            <td colspan="9" class="px-6 py-12 text-center text-gray-500">
                                <div class="flex flex-col items-center">
                                    <svg class="w-12 h-12 text-gray-300 mb-4" 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>
                                    <h3 class="text-lg font-medium text-gray-900 mb-2">No quotes found</h3>
                                    <p class="text-gray-500 mb-4">Get started by creating your first quote.</p>
                                    <button type="button" id="create-first-quote-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>
                                        Create Your First Quote
                                    </button>
                                </div>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php
                        // Force register post types and flush rewrite rules to ensure proper permalinks
                        $easy_invoice = \EasyInvoice\EasyInvoice::getInstance();
                        $easy_invoice->registerPostTypes();
                        $easy_invoice->forceFlushRewriteRules();

                        // Force a complete rewrite rules flush
                        flush_rewrite_rules(true);

                        // One-time fix: Update all existing quotes to have proper slugs
                        if (!get_option('easy_invoice_quotes_slugs_fixed_v3', false)) {
                            global $wpdb;
                            $quote_posts = $wpdb->get_results($wpdb->prepare(
                                "SELECT ID, post_title, post_name FROM {$wpdb->posts}
                                 WHERE post_type = %s",
                                \EasyInvoice\Constants\PostTypes::EASY_INVOICE_QUOTE_POST_TYPE
                            ));

                            foreach ($quote_posts as $post) {
                                // Generate a proper slug if empty or doesn't match our format
                                $post_name = $post->post_name ?? '';
                                if (empty($post_name) || strpos($post_name, 'easy-invoice-quote') === false) {
                                    $slug = sanitize_title($post->post_title ?: 'easy-invoice-quote-' . $post->ID);
                                    wp_update_post([
                                        'ID' => $post->ID,
                                        'post_name' => $slug
                                    ]);
                                }
                            }

                            update_option('easy_invoice_quotes_slugs_fixed_v3', true);
                        }

                        // One-time fix: Publish all draft quotes to ensure proper permalinks
                        if (!get_option('easy_invoice_quotes_published_v1', false)) {
                            global $wpdb;
                            $draft_quotes = $wpdb->get_results($wpdb->prepare(
                                "SELECT ID FROM {$wpdb->posts}
                                 WHERE post_type = %s AND post_status = 'draft'",
                                \EasyInvoice\Constants\PostTypes::EASY_INVOICE_QUOTE_POST_TYPE
                            ));

                            foreach ($draft_quotes as $quote) {
                                wp_update_post([
                                    'ID' => $quote->ID,
                                    'post_status' => 'publish'
                                ]);
                            }

                            update_option('easy_invoice_quotes_published_v1', true);
                        }

                        // Ensure all quotes have proper slugs
                        foreach ($quotes as $quote):
                            $quote->ensureProperSlug();
                        ?>
                        <tr class="hover:bg-gray-50 transition-colors duration-150">
                            <td class="px-6 py-4 whitespace-nowrap">
                                <input type="checkbox" class="quote-checkbox rounded border-gray-300 text-indigo-600 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" value="<?php echo $quote->getId(); ?>">
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="flex items-center">
                                    <div class="flex-shrink-0 h-10 w-10">
                                        <div class="h-10 w-10 rounded-full bg-indigo-100 flex items-center justify-center">
                                            <svg class="w-5 h-5 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>
                                    <div class="ml-4">
                                        <div class="text-sm font-medium text-gray-900">
                                            <a href="<?php echo admin_url('admin.php?page=easy-invoice-quote-builder&id=' . $quote->getId()); ?>" class="text-indigo-600 hover:text-indigo-900 transition-colors duration-150">
                                                <?php echo esc_html($quote->getTitle() ?: 'Untitled Quote'); ?>
                                            </a>
                                        </div>
                                        <div class="text-sm text-gray-500">
                                            <?php echo esc_html($quote->getNumber() ?: 'QT-' . $quote->getId()); ?>
                                        </div>
                                        <div class="row-actions mt-1">
                                            <span class="view"><a href="<?php echo apply_filters('easy_invoice_quote_view_url', get_permalink($quote->getId()), $quote->getId()); ?>" 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>View</a></span>
                                            <span class="edit"><a href="<?php echo admin_url('admin.php?page=easy-invoice-quote-builder&id=' . $quote->getId()); ?>"><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>Edit</a></span>
                                            <?php if ($quote->getStatus() === 'cancelled'): ?>
                                                <span class="restore"><a href="#" class="restore-quote text-green-600" data-quote-id="<?php echo $quote->getId(); ?>" data-quote-number="<?php echo esc_attr($quote->getNumber() ?: 'QT-' . $quote->getId()); ?>"><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="M4 4v5h.582M20 20v-5h-.581M5 9a7 7 0 0114 0c0 3.866-3.134 7-7 7a7 7 0 01-7-7zm7 7v4m0 0h-2m2 0h2"/></svg>Restore</a></span>
                                                <span class="delete"><a href="#" class="delete-quote-btn text-red-600" data-quote-id="<?php echo $quote->getId(); ?>" data-quote-number="<?php echo esc_attr($quote->getNumber() ?: 'QT-' . $quote->getId()); ?>"><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>Delete Permanently</a></span>
                                            <?php else: ?>
                                                <span class="trash"><a href="#" class="trash-quote text-red-600" data-quote-id="<?php echo $quote->getId(); ?>" data-quote-number="<?php echo esc_attr($quote->getNumber() ?: 'QT-' . $quote->getId()); ?>"><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>Trash</a></span>
                                                <span class="email"><a href="#" class="email-quote" data-quote-id="<?php echo $quote->getId(); ?>" data-quote-number="<?php echo esc_attr($quote->getNumber() ?: 'QT-' . $quote->getId()); ?>"><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>Send</a></span>
                                                <span class="pdf"><a href="<?php echo get_permalink($quote->getId()); ?>?auto_download_pdf=1" target="_blank" class="download-pdf-quote" data-quote-id="<?php echo $quote->getId(); ?>" data-quote-number="<?php echo esc_attr($quote->getNumber() ?: 'QT-' . $quote->getId()); ?>"><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>Download</a></span>
                                                <?php if (!easy_invoice_has_pro()): ?>
                                                <span class="export premium-feature"><a href="#" class="export-quote-pro-placeholder text-yellow-600 font-semibold" data-quote-id="<?php echo $quote->getId(); ?>" data-quote-number="<?php echo esc_attr($quote->getNumber() ?: 'QT-' . $quote->getId()); ?>"><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-quote-pro-placeholder text-yellow-600 font-semibold" data-quote-id="<?php echo $quote->getId(); ?>" data-quote-number="<?php echo esc_attr($quote->getNumber() ?: 'QT-' . $quote->getId()); ?>"><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_quote_row_actions', [], $quote);
                                                foreach ($secure_actions as $action_key => $action_html) {
                                                    echo '<span class="' . esc_attr($action_key) . '">' . $action_html . '</span>';
                                                }
                                                ?>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-sm text-gray-900">
                                    <?php
                                    // Get client name directly from client repository
                                    $client_name = 'No Client';
                                    if ($quote->getClientId() > 0) {
                                        $client_repository = \EasyInvoice\Providers\ClientServiceProvider::getClientRepository();
                                        $client = $client_repository->find($quote->getClientId());
                                        if ($client) {
                                            $client_name = $client->getBusinessClientName() ?: ($client->getFirstName() . ' ' . $client->getLastName());
                                            if (empty(trim($client_name))) {
                                                $client_name = $client->getDisplayName() ?: 'Client ' . $client->getId();
                                            }
                                        }
                                    } elseif ($quote->getCustomerName()) {
                                        $client_name = $quote->getCustomerName();
                                    }
                                    echo esc_html($client_name);
                                    ?>
                                </div>
                                <div class="text-sm text-gray-500"><?php echo esc_html($quote->getCustomerEmail() ?: ''); ?></div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 font-medium">
                                <?php
                                // Use QuoteFormatter for proper currency formatting
                                $formatter = new \EasyInvoice\Helpers\QuoteFormatter($quote);
                                echo esc_html($formatter->format($quote->getTotal() ?: 0));
                                ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <?php
                                $status = $quote->getStatus() ?: 'draft';
                                $status_classes = [
                                    'draft' => 'bg-gray-100 text-gray-800 ring-1 ring-gray-300',
                                    'sent' => 'bg-blue-100 text-blue-800 ring-1 ring-blue-300',
                                    'accepted' => 'bg-green-100 text-green-800 ring-1 ring-green-300',
                                    'declined' => 'bg-red-100 text-red-800 ring-1 ring-red-300',
                                    'expired' => 'bg-yellow-100 text-yellow-800 ring-1 ring-yellow-300'
                                ];
                                $status_class = $status_classes[$status] ?? 'bg-gray-100 text-gray-800 ring-1 ring-gray-300';
                                ?>
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium <?php echo $status_class; ?>">
                                    <?php echo ucfirst($status); ?>
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                <?php echo $quote->getIssueDate() ? date('M j, Y', strtotime($quote->getIssueDate())) : '—'; ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                <?php echo $quote->getExpiryDate() ? date('M j, Y', strtotime($quote->getExpiryDate())) : '—'; ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                <?php
                                // Get all logs for this quote
                                try {
                                    $quote_log_service = new \EasyInvoice\Services\QuoteLogService();
                                    $all_logs = $quote_log_service->getLogs($quote->getId());
                                    $logs_count = count($all_logs);

                                    if ($logs_count > 0): ?>
                                        <button type="button"
                                                class="view-logs-btn text-xs text-indigo-600 hover:text-indigo-800 font-medium"
                                                data-quote-id="<?php echo $quote->getId(); ?>"
                                                data-quote-title="<?php echo esc_attr($quote->getTitle() ?: 'Untitled Quote'); ?>"
                                                data-logs-count="<?php echo $logs_count; ?>">
                                            View all <?php echo $logs_count; ?> logs
                                        </button>
                                    <?php else: ?>
                                        <span class="text-gray-400 text-xs">No activity</span>
                                    <?php endif; ?>
                                <?php } catch (\Exception $e) { ?>
                                    <span class="text-gray-400 text-xs">Error loading logs</span>
                                <?php } ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                                <!-- Actions column - actions are shown in the row-actions div above -->
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Bottom Pagination -->
    <?php if (isset($pagination) && $pagination['total_pages'] > 1): ?>
    <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 (($pagination['current_page'] - 1) * $pagination['per_page']) + 1; ?></span>
                    to
                    <span class="font-medium"><?php echo min($pagination['current_page'] * $pagination['per_page'], $pagination['total_quotes']); ?></span>
                    of
                    <span class="font-medium"><?php echo $pagination['total_quotes']; ?></span>
                    results
                </span>
            </div>
            <div class="flex items-center space-x-2">
                <span class="text-sm text-gray-500">Page <?php echo $pagination['current_page']; ?> of <?php echo $pagination['total_pages']; ?></span>
                <div class="flex space-x-1">
                    <?php
                    $prev_page = $pagination['current_page'] > 1 ? $pagination['current_page'] - 1 : 1;
                    $next_page = $pagination['current_page'] < $pagination['total_pages'] ? $pagination['current_page'] + 1 : $pagination['total_pages'];
                    $current_url = add_query_arg($_GET, admin_url('admin.php'));
                    $current_url = remove_query_arg('paged', $current_url);
                    $start_page = max(1, $pagination['current_page'] - 2);
                    $end_page = min($pagination['total_pages'], $pagination['current_page'] + 2);
                    if ($pagination['current_page'] > 1): ?>
                        <a class="bg-white text-gray-500 hover:bg-gray-50 px-3 py-2 text-sm font-medium border border-gray-300 rounded-md" href="<?php echo esc_url(add_query_arg('paged', $prev_page, $current_url)); ?>">‹ Previous</a>
                    <?php endif;
                    for ($i = $start_page; $i <= $end_page; $i++):
                        if ($i == $pagination['current_page']): ?>
                            <span class="px-3 py-2 text-sm font-medium border border-gray-300 rounded-md bg-indigo-50 border-indigo-500 text-indigo-600"><?php echo $i; ?></span>
                        <?php else: ?>
                            <a class="px-3 py-2 text-sm font-medium border border-gray-300 bg-white text-gray-500 hover:bg-gray-50 rounded-md" href="<?php echo esc_url(add_query_arg('paged', $i, $current_url)); ?>"><?php echo $i; ?></a>
                        <?php endif;
                    endfor;
                    if ($pagination['current_page'] < $pagination['total_pages']): ?>
                        <a class="bg-white text-gray-500 hover:bg-gray-50 px-3 py-2 text-sm font-medium border border-gray-300 rounded-md" href="<?php echo esc_url(add_query_arg('paged', $next_page, $current_url)); ?>">Next ›</a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

<script>
jQuery(document).ready(function($) {
    // Open modal for both buttons
    $('#create-quote-btn, #create-first-quote-btn').on('click', function(e) {
        e.preventDefault(); // Prevent the default link behavior
        $('#new-quote-modal').removeClass('hidden');
        $('#new_quote_title').focus();
    });

    // Close modal
    $('#close-new-quote-modal, #cancel-new-quote').on('click', function() {
        $('#new-quote-modal').addClass('hidden');
        $('#new-quote-form')[0].reset();
        $('#new-quote-message').addClass('hidden').html('');
    });

    // Close modal on backdrop click
    $('#new-quote-modal').on('click', function(e) {
        if (e.target === this) {
            $(this).addClass('hidden');
            $('#new-quote-form')[0].reset();
            $('#new-quote-message').addClass('hidden').html('');
        }
    });

    // Submit form
    $('#new-quote-form').on('submit', function(e) {
        e.preventDefault();

        var $form = $(this);
        var $submitBtn = $form.find('button[type="submit"]');
        var $message = $('#new-quote-message');
        var title = $('#new_quote_title').val().trim();

        if (!title) {
            $message.removeClass('hidden').html('<div class="text-red-600 text-sm">Please enter a quote title.</div>');
            return;
        }

        // Show loading state
        $submitBtn.prop('disabled', true).html('Creating...');
        $message.addClass('hidden');

        $.ajax({
            url: easyInvoice.ajaxUrl,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'easy_invoice_create_new_quote',
                title: title,
                nonce: '<?php echo wp_create_nonce('easy_invoice_admin_nonce'); ?>'
            },
            success: function(response) {
                if (response.success && response.data && response.data.quote_id) {
                    // Show success message below the form
                    $message.removeClass('hidden').html('<div class="text-green-600 text-sm">Quote created successfully! Redirecting...</div>');

                    // Redirect to the builder page with the new quote ID
                    setTimeout(function() {
                        window.location.href = 'admin.php?page=easy-invoice-quote-builder&id=' + response.data.quote_id;
                    }, 1000);
                } else {
                    $message.removeClass('hidden').html('<div class="text-red-600 text-sm">' + (response.data && response.data.message ? response.data.message : 'Error creating quote.') + '</div>');
                    $submitBtn.prop('disabled', false).html('Create Quote');
                }
            },
            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 Quote');
            }
        });
    });

    // Create sample quote
    $('#easy-quote-create-sample').on('click', function() {
        var $btn = $(this);
        var originalText = $btn.text();
        $btn.prop('disabled', true).text('Creating...');

        $.ajax({
            url: easyInvoice.ajaxUrl,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'easy_invoice_create_sample_quote',
                nonce: '<?php echo wp_create_nonce('easy_invoice_admin_nonce'); ?>'
            },
            success: function(response) {
                if (response.success && response.data && response.data.quote_id) {
                    window.location.href = 'admin.php?page=easy-invoice-quote-builder&id=' + response.data.quote_id;
                } else {
                    EasyInvoiceConfirmation.show({
                        title: 'Error',
                        message: response.data && response.data.message ? response.data.message : 'Failed to create sample quote.',
                        confirmText: 'OK',
                        confirmClass: 'bg-red-600 hover:bg-red-700'
                    });
                }
            },
            error: function() {
                EasyInvoiceConfirmation.show({
                    title: 'Error',
                    message: 'Failed to create sample quote.',
                    confirmText: 'OK',
                    confirmClass: 'bg-red-600 hover:bg-red-700'
                });
            },
            complete: function() {
                $btn.prop('disabled', false).text(originalText);
            }
        });
    });

    // Update existing quotes
    $('#update-existing-quotes-btn').on('click', function() {
        var $btn = $(this);
        var originalText = $btn.text();
        $btn.prop('disabled', true).text('Updating...');

        $.ajax({
            url: easyInvoice.ajaxUrl,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'easy_invoice_update_existing_quotes',
                nonce: '<?php echo wp_create_nonce('easy_invoice_admin_nonce'); ?>'
            },
            success: function(response) {
                if (response.success) {
                    EasyInvoiceConfirmation.show({
                        title: 'Success',
                        message: response.data.message,
                        confirmText: 'OK',
                        confirmClass: 'bg-green-600 hover:bg-green-700'
                    });
                    // Reload the page to show updated data
                    setTimeout(function() {
                        location.reload();
                    }, 1500);
                } else {
                    EasyInvoiceConfirmation.show({
                        title: 'Error',
                        message: response.data && response.data.message ? response.data.message : 'Failed to update quotes.',
                        confirmText: 'OK',
                        confirmClass: 'bg-red-600 hover:bg-red-700'
                    });
                }
            },
            error: function() {
                EasyInvoiceConfirmation.show({
                    title: 'Error',
                    message: 'Failed to update quotes.',
                    confirmText: 'OK',
                    confirmClass: 'bg-red-600 hover:bg-red-700'
                });
            },
            complete: function() {
                $btn.prop('disabled', false).text(originalText);
            }
        });
    });



    // Select all checkboxes
    $('#select-all').on('change', function() {
        $('.quote-checkbox').prop('checked', $(this).is(':checked'));
        updateBulkActionButton();
    });

    // Individual checkbox change
    $(document).on('change', '.quote-checkbox', function() {
        var totalCheckboxes = $('.quote-checkbox').length;
        var checkedCheckboxes = $('.quote-checkbox:checked').length;

        if (checkedCheckboxes === 0) {
            $('#select-all').prop('indeterminate', false).prop('checked', false);
        } else if (checkedCheckboxes === totalCheckboxes) {
            $('#select-all').prop('indeterminate', false).prop('checked', true);
        } else {
            $('#select-all').prop('indeterminate', true);
        }

        updateBulkActionButton();
    });

    // Update bulk action button state
    function updateBulkActionButton() {
        var checkedCount = $('.quote-checkbox:checked').length;
        var $applyBtn = $('#bulk-action-form button[type=submit]');

        if (checkedCount > 0) {
            $applyBtn.prop('disabled', false).text('Apply (' + checkedCount + ')');
        } else {
            $applyBtn.prop('disabled', true).text('Apply');
        }
    }

    // Bulk action form submission
    $('#bulk-action-form').on('submit', function(e) {
        e.preventDefault();

        var selectedQuotes = $('.quote-checkbox:checked').map(function() {
            return $(this).val();
        }).get();

        var action = $(this).find('select[name="bulk_action"]').val();

        if (selectedQuotes.length === 0) {
            EasyInvoiceConfirmation.show({
                title: 'No Quotes Selected',
                message: 'Please select quotes to perform this action.',
                confirmText: 'OK',
                confirmClass: 'bg-blue-600 hover:bg-blue-700'
            });
            return;
        }

        if (!action) {
            EasyInvoiceConfirmation.show({
                title: 'No Action Selected',
                message: 'Please select a bulk action.',
                confirmText: 'OK',
                confirmClass: 'bg-blue-600 hover:bg-blue-700'
            });
            return;
        }

        EasyInvoiceConfirmation.confirmAction(action, selectedQuotes.length + ' quote(s)', function() {
            var $form = $(this);
            var $btn = $form.find('button[type=submit]');
            var originalText = $btn.text();

            $btn.prop('disabled', true).text('Processing...');

            $.ajax({
                                    url: easyInvoice.ajaxUrl,
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        action: 'easy_invoice_bulk_quote_action',
                    quote_ids: selectedQuotes,
                    bulk_action: action,
                    nonce: '<?php echo wp_create_nonce('easy_invoice_admin_nonce'); ?>'
                },
                success: function(response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        EasyInvoiceConfirmation.show({
                            title: 'Error',
                            message: response.data && response.data.message ? response.data.message : 'Failed to perform bulk action.',
                            confirmText: 'OK',
                            confirmClass: 'bg-red-600 hover:bg-red-700'
                        });
                    }
                },
                error: function() {
                    EasyInvoiceConfirmation.show({
                        title: 'Error',
                        message: 'Failed to perform bulk action.',
                        confirmText: 'OK',
                        confirmClass: 'bg-red-600 hover:bg-red-700'
                    });
                },
                complete: function() {
                    $btn.prop('disabled', false).text(originalText);
                }
            });
        });
    });

    // Quote row actions
    $(document).on('click', '.draft-quote', function(e) {
        e.preventDefault();
        const quoteId = $(this).data('quote-id');
        const quoteNumber = $(this).data('quote-number');

        EasyInvoiceConfirmation.confirmAction('draft', 'quote ' + quoteNumber, function() {
            $.ajax({
                url: easyInvoice.ajaxUrl,
                type: 'POST',
                dataType: 'json',
                data: {
                    action: 'easy_invoice_draft_quote',
                    quote_id: quoteId,
                    nonce: '<?php echo wp_create_nonce('easy_invoice_admin_nonce'); ?>'
                },
                success: function(response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        EasyInvoiceConfirmation.show({
                            title: 'Error',
                            message: response.data && response.data.message ? response.data.message : 'Failed to move quote to draft.',
                            confirmText: 'OK',
                            confirmClass: 'bg-red-600 hover:bg-red-700'
                        });
                    }
                },
                error: function() {
                    EasyInvoiceConfirmation.show({
                        title: 'Error',
                        message: 'Failed to move quote to draft.',
                        confirmText: 'OK',
                        confirmClass: 'bg-red-600 hover:bg-red-700'
                    });
                }
            });
        });
    });

    $(document).on('click', '.trash-quote', function(e) {
        e.preventDefault();
        const quoteId = $(this).data('quote-id');
        const quoteNumber = $(this).data('quote-number');

        EasyInvoiceConfirmation.confirmAction('trash', 'quote ' + quoteNumber, function() {
            $.ajax({
                url: easyInvoice.ajaxUrl,
                type: 'POST',
                dataType: 'json',
                data: {
                    action: 'easy_invoice_trash_quote',
                    quote_id: quoteId,
                    nonce: '<?php echo wp_create_nonce('easy_invoice_admin_nonce'); ?>'
                },
                success: function(response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        EasyInvoiceConfirmation.show({
                            title: 'Error',
                            message: response.data && response.data.message ? response.data.message : 'Failed to move quote to trash.',
                            confirmText: 'OK',
                            confirmClass: 'bg-red-600 hover:bg-red-700'
                        });
                    }
                },
                error: function() {
                    EasyInvoiceConfirmation.show({
                        title: 'Error',
                        message: 'Failed to move quote to trash.',
                        confirmText: 'OK',
                        confirmClass: 'bg-red-600 hover:bg-red-700'
                    });
                }
            });
        });
    });

    $(document).on('click', '.email-quote', function(e) {
        e.preventDefault();
        const quoteId = $(this).data('quote-id');
        const quoteNumber = $(this).data('quote-number');

        // Use the new confirmation system instead of browser confirm
        if (typeof EasyInvoiceConfirmation !== 'undefined') {
            EasyInvoiceConfirmation.confirmAction('send email', 'quote ' + quoteNumber, 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_quote_email",
                        quote_id: quoteId,
                        nonce: '<?php echo wp_create_nonce('easy_invoice_send_quote_email'); ?>'
                    },
                    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 quote " + quoteNumber + " 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_quote_email",
                        quote_id: quoteId,
                        nonce: '<?php echo wp_create_nonce('easy_invoice_send_quote_email'); ?>'
                    },
                    success: function(response) {
                        if (response.success) {
                            EasyInvoiceToast.success("Email sent successfully!");
                        } else {
                            // Handle both response.data.message and response.data (direct string)
                            const errorMessage = (response.data && response.data.message) ? response.data.message : (response.data || "Error sending email");
                            EasyInvoiceToast.error(errorMessage);
                        }
                        // 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");
                    }
                });
            }
        }
    });

    $(document).on('click', '.download-pdf-quote', function(e) {
        e.preventDefault();
        const quoteId = $(this).data('quote-id');
        const quoteNumber = $(this).data('quote-number');

        // Show loading state
        var $link = $(this);
        var originalText = $link.text();
        $link.text("Generating PDF...").css("opacity", "0.7");

        // Get quote data via AJAX and generate PDF
        $.ajax({
            url: easyInvoice.ajaxUrl,
            type: "POST",
            data: {
                action: "easy_invoice_download_quote_pdf",
                quote_id: quoteId,
                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");
            }
        });
    });

    // Delete quote
    $(document).on('click', '.delete-quote-btn', function() {
        const quoteId = $(this).data('quote-id');
        const $row = $(this).closest('tr');

        EasyInvoiceConfirmation.confirmAction('delete', 'this quote', function() {
            $.ajax({
                url: easyInvoice.ajaxUrl,
                type: 'POST',
                dataType: 'json',
                data: {
                    action: 'easy_invoice_delete_quote',
                    quote_id: quoteId,
                    nonce: '<?php echo wp_create_nonce('easy_invoice_admin_nonce'); ?>'
                },
                success: function(response) {
                    if (response.success) {
                        $row.fadeOut(300, function() {
                            $(this).remove();
                            // Check if table is empty
                            if ($('tbody tr').length === 0) {
                                location.reload();
                            }
                        });
                    } else {
                        EasyInvoiceConfirmation.show({
                            title: 'Error',
                            message: response.data && response.data.message ? response.data.message : 'Failed to delete quote.',
                            confirmText: 'OK',
                            confirmClass: 'bg-red-600 hover:bg-red-700'
                        });
                    }
                },
                error: function() {
                    EasyInvoiceConfirmation.show({
                        title: 'Error',
                        message: 'Failed to delete quote.',
                        confirmText: 'OK',
                        confirmClass: 'bg-red-600 hover:bg-red-700'
                    });
                }
            });
        });
    });

    // Status filter change
    $('#status-filter').on('change', function() {
        var status = $(this).val();
        var currentUrl = new URL(window.location);

        if (status) {
            currentUrl.searchParams.set('status', status);
        } else {
            currentUrl.searchParams.delete('status');
        }

        window.location.href = currentUrl.toString();
    });

    // Initialize
    updateBulkActionButton();

    // Empty Trash functionality
    $('#empty-trash-btn').on('click', function(e) {
        e.preventDefault();

        // Check if EasyInvoiceConfirmation is available
        if (typeof EasyInvoiceConfirmation === 'undefined') {
            console.error('EasyInvoiceConfirmation is not defined');
            EasyInvoiceToast.error('Confirmation modal not loaded. Please refresh the page and try again.');
            return;
        }

        EasyInvoiceConfirmation.show({
            title: 'Empty Trash',
            message: 'Are you sure you want to permanently delete all quotes in the trash? This action cannot be undone.',
            confirmText: 'Empty Trash',
            confirmClass: 'bg-red-600 hover:bg-red-700',
            cancelText: 'Cancel',
            cancelClass: 'bg-gray-300 hover:bg-gray-400',
            onConfirm: function() {
                // User confirmed - proceed with emptying trash
                var $btn = $('#empty-trash-btn');
                var originalText = $btn.text();

                $btn.prop('disabled', true).text('Emptying...');

                $.ajax({
                    url: easyInvoice.ajaxUrl,
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        action: 'easy_invoice_empty_trash',
                        nonce: '<?php echo wp_create_nonce('easy_invoice_nonce'); ?>'
                    },
                    success: function(response) {
                        if (response.success) {
                            EasyInvoiceToast.success('Trash emptied successfully');
                            setTimeout(function() {
                                location.reload();
                            }, 1000);
                        } else {
                            EasyInvoiceToast.error(response.data && response.data.message ? response.data.message : 'Failed to empty trash.');
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('Empty trash AJAX error:', error);
                        EasyInvoiceToast.error('Failed to empty trash. Please try again.');
                    },
                    complete: function() {
                        $btn.prop('disabled', false).text(originalText);
                    }
                });
            }
        });
    });

    $(document).on('click', '.restore-quote', function(e) {
        e.preventDefault();
        const quoteId = $(this).data('quote-id');
        const quoteNumber = $(this).data('quote-number');
        EasyInvoiceConfirmation.confirmAction('restore', 'quote ' + quoteNumber, function() {
            $.ajax({
                url: easyInvoice.ajaxUrl,
                type: 'POST',
                dataType: 'json',
                data: {
                    action: 'easy_invoice_restore_quote',
                    quote_id: quoteId,
                    nonce: '<?php echo wp_create_nonce('easy_invoice_admin_nonce'); ?>'
                },
                success: function(response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        EasyInvoiceConfirmation.show({
                            title: 'Error',
                            message: response.data && response.data.message ? response.data.message : 'Failed to restore quote.',
                            confirmText: 'OK',
                            confirmClass: 'bg-red-600 hover:bg-red-700'
                        });
                    }
                },
                error: function() {
                    EasyInvoiceConfirmation.show({
                        title: 'Error',
                        message: 'Failed to restore quote.',
                        confirmText: 'OK',
                        confirmClass: 'bg-red-600 hover:bg-red-700'
                    });
                }
            });
        });
    });

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

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

    $(document).on('click', '.duplicate-quote', function(e) {
        e.preventDefault();
        const quoteId = $(this).data('quote-id');
        const quoteNumber = $(this).data('quote-number');

        EasyInvoiceConfirmation.confirmAction('duplicate', 'quote ' + quoteNumber, function() {
            $.ajax({
                url: easyInvoice.ajaxUrl,
                type: 'POST',
                dataType: 'json',
                data: {
                    action: 'easy_invoice_duplicate_quote',
                    quote_id: quoteId,
                    nonce: '<?php echo wp_create_nonce('easy_invoice_admin_nonce'); ?>'
                },
                success: function(response) {
                    if (response.success && response.data && response.data.quote_id) {
                        EasyInvoiceConfirmation.show({
                            title: 'Success',
                            message: 'Quote duplicated successfully! You will be redirected to the new quote.',
                            confirmText: 'OK',
                            confirmClass: 'bg-green-600 hover:bg-green-700',
                            onConfirm: function() {
                                window.location.href = 'admin.php?page=easy-invoice-quote-builder&id=' + response.data.quote_id;
                            }
                        });
                    } else {
                        EasyInvoiceConfirmation.show({
                            title: 'Error',
                            message: response.data && response.data.message ? response.data.message : 'Failed to duplicate quote.',
                            confirmText: 'OK',
                            confirmClass: 'bg-red-600 hover:bg-red-700'
                        });
                    }
                },
                error: function() {
                    EasyInvoiceConfirmation.show({
                        title: 'Error',
                        message: 'Failed to duplicate quote.',
                        confirmText: 'OK',
                        confirmClass: 'bg-red-600 hover:bg-red-700'
                    });
                }
            });
        });
    });

   // View Logs functionality
   $(document).on('click', '.view-logs-btn', function(e) {
        e.preventDefault();
        const quoteId = $(this).data('quote-id');
        const quoteTitle = $(this).data('quote-title');
        const logsCount = $(this).data('logs-count');

        // Show loading state
        $('#logs-modal .modal-body').html('<div class="flex justify-center items-center py-8"><div class="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600"></div></div>');
        $('#logs-modal').removeClass('hidden');

        // Fetch logs via AJAX
        $.ajax({
            url: easyInvoice.ajaxUrl,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'easy_invoice_get_quote_logs',
                quote_id: quoteId,
                nonce: '<?php echo wp_create_nonce('easy_invoice_admin_nonce'); ?>'
            },
            success: function(response) {
                if (response.success && response.data && response.data.logs) {
                    let logsHtml = '<div class="space-y-4">';

                    response.data.logs.forEach(function(log) {
                        const date = new Date(log.created_date);
                        const formattedDate = date.toLocaleDateString('en-US', {
                            year: 'numeric',
                            month: 'short',
                            day: 'numeric',
                            hour: '2-digit',
                            minute: '2-digit'
                        });

                        logsHtml += `
                            <div class="border-l-4 border-indigo-500 pl-4 py-2">
                                <div class="flex items-start justify-between">
                                    <div class="flex-1">
                                        <div class="text-sm font-medium text-gray-900">${log.description}</div>
                                        <div class="text-xs text-gray-500 mt-1">
                                            <span class="font-medium">${log.user_name}</span> • ${formattedDate}
                                        </div>
                                        ${log.ip_address ? `<div class="text-xs text-gray-400 mt-1">IP: ${log.ip_address}</div>` : ''}
                                    </div>
                                    <div class="ml-4">
                                        <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-indigo-100 text-indigo-800">
                                            ${log.action}
                                        </span>
                                    </div>
                                </div>
                            </div>
                        `;
                    });

                    logsHtml += '</div>';
                    $('#logs-modal .modal-body').html(logsHtml);
                } else {
                    $('#logs-modal .modal-body').html('<div class="text-center py-8 text-gray-500">No logs found for this quote.</div>');
                }
            },
            error: function() {
                $('#logs-modal .modal-body').html('<div class="text-center py-8 text-red-500">Error loading logs. Please try again.</div>');
            }
        });
    });

    // Close logs modal
    $(document).on('click', '#close-logs-modal', function(e) {
        e.preventDefault();
        $('#logs-modal').addClass('hidden');
    });

    // Close modal when clicking outside
    $(document).on('click', '#logs-modal', function(e) {
        if (e.target === this) {
            $('#logs-modal').addClass('hidden');
        }
    });
});
</script>

<style>
/* Modern row actions styling (copied from invoice listing) */
.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 */
}
.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;
}

#easy-invoice-confirmation-modal .bg-white {
    max-height: 90vh;
    overflow-y: auto;
}
#easy-invoice-confirmation-modal .flex.justify-end {
    flex-wrap: wrap;
}

.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>
