<?php
// Extract data passed from controller
$clients = $clients ?? [];
$stats = $stats ?? [];
$current_page = $current_page ?? 1;
$per_page = $per_page ?? 20;
$total_clients = $total_clients ?? 0;
$total_pages = $total_pages ?? 1;

// $clients variable contains Client objects

?>
<div class="p-8">
    <!-- Header with Actions -->
    <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('Clients', 'easy-invoice'); ?></h1>
                <p class="mt-1 text-sm text-gray-500"><?php _e('Manage all client records', 'easy-invoice'); ?></p>
            </div>
            <div class="flex items-center space-x-3">
                <?php if (!easy_invoice_has_pro()): ?>
                <button type="button" id="export-all-clients-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-clients-btn').on('click', function(e) {
                        e.preventDefault();
                        // Show premium popup using the proper confirmation modal
                        if (typeof EasyInvoiceConfirmation !== 'undefined') {
                            EasyInvoiceConfirmation.showFeatureUpgrade('Export All Clients', 'Export all your clients to CSV, Excel, or PDF format for backup, analysis, or sharing with your team.');
                        } else {
                            // Fallback to toast if confirmation modal is not available
                            EasyInvoiceToast.error('<?php echo esc_js(__('Exporting all clients 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_clients" />
                    <input type="hidden" name="_wpnonce" value="<?php echo wp_create_nonce('easy_invoice_export_all_clients'); ?>" />
                    <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 id="add-new-client-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('Add New Client', 'easy-invoice'); ?>
        </button>
            </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-blue-100 p-3 mr-4">
                    <svg class="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 21V19C17 17.9391 16.5786 16.9217 15.8284 16.1716C15.0783 15.4214 14.0609 15 13 15H5C3.93913 15 2.92172 15.4214 2.17157 16.1716C1.42143 16.9217 1 17.9391 1 19V21" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        <circle cx="9" cy="7" r="4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        <path d="M23 21V19C23 18.1137 22.6485 17.2628 22.0237 16.6425C21.3989 16.0221 20.5471 15.6722 19.66 15.6722C18.7729 15.6722 17.9211 16.0221 17.2963 16.6425C16.6715 17.2628 16.32 18.1137 16.32 19V21" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        <path d="M16.32 11.6722C18.36 11.6722 20 10.0322 20 7.99219C20 5.95219 18.36 4.31219 16.32 4.31219" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                </div>
                <div>
            <h3 class="text-sm font-medium text-gray-500">Total Clients</h3>
                    <p class="mt-1 text-2xl font-bold text-gray-900"><?php echo isset($stats['total_clients']) ? $stats['total_clients'] : count($clients); ?></p>
                </div>
            </div>
        </div>
        <div class="bg-white rounded-lg shadow p-6 transition-transform duration-300 hover:shadow-md hover:-translate-y-1">
            <div class="flex items-center">
                <div class="rounded-full bg-indigo-100 p-3 mr-4">
                    <svg class="w-6 h-6 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 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 isset($stats['total_invoices']) ? $stats['total_invoices'] : 0; ?></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 
                            $currency_count = count($stats['total_revenue']);
                            foreach ($stats['total_revenue'] as $index => $data): 
                                $is_last = $index === $currency_count - 1;
                                // Get currency code from the data array or use a fallback
                                $currency_code = isset($data['currency_code']) ? $data['currency_code'] : 'USD';
                            ?>
                                <div class="<?php echo $currency_count > 1 ? 'text-sm' : 'text-lg'; ?> font-bold text-gray-900 <?php echo !$is_last ? 'mb-1' : ''; ?>">
                                    <?php echo $data['symbol'] . number_format($data['amount'], 2); ?>
                                    <span class="text-xs font-normal text-gray-500"><?php echo strtoupper($currency_code ?? 'USD'); ?></span>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <p class="mt-1 text-lg font-bold text-gray-900">$0.00</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <div class="bg-white rounded-lg shadow p-6 transition-transform duration-300 hover:shadow-md hover:-translate-y-1">
            <div class="flex items-center">
                <div class="rounded-full bg-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 isset($stats['pending_invoices']) ? $stats['pending_invoices'] : 0; ?></p>
                </div>
            </div>
        </div>
    </div>

    <!-- Top Pagination -->
    <?php if ($total_clients > 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_clients)); ?></span>
                    of 
                    <span class="font-medium"><?php echo number_format($total_clients); ?></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(
                        'page' => 'easy-invoice-clients'
                    )
                );
                
                $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; ?>

    <!-- Clients Table -->
    <div class="bg-white rounded-lg shadow">
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200 client-list-table">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100" data-sort="id">
                            <div class="flex items-center space-x-1">
                                <span>Client ID</span>
                                <div class="sort-indicator">
                                    <i class="fas fa-sort text-gray-400"></i>
                                </div>
                            </div>
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100" data-sort="business_name">
                            <div class="flex items-center space-x-1">
                                <span>Business Name</span>
                                <div class="sort-indicator">
                                    <i class="fas fa-sort text-gray-400"></i>
                                </div>
                            </div>
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100" data-sort="name">
                            <div class="flex items-center space-x-1">
                                <span>Client Name</span>
                                <div class="sort-indicator">
                                    <i class="fas fa-sort text-gray-400"></i>
                                </div>
                            </div>
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100" data-sort="email">
                            <div class="flex items-center space-x-1">
                                <span>Email</span>
                                <div class="sort-indicator">
                                    <i class="fas fa-sort text-gray-400"></i>
                                </div>
                            </div>
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100" data-sort="phone">
                            <div class="flex items-center space-x-1">
                                <span>Phone</span>
                                <div class="sort-indicator">
                                    <i class="fas fa-sort text-gray-400"></i>
                                </div>
                            </div>
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100" data-sort="username">
                            <div class="flex items-center space-x-1">
                                <span>Username</span>
                                <div class="sort-indicator">
                                    <i class="fas fa-sort text-gray-400"></i>
                                </div>
                            </div>
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100" data-sort="role">
                            <div class="flex items-center space-x-1">
                                <span>Role</span>
                                <div class="sort-indicator">
                                    <i class="fas fa-sort text-gray-400"></i>
                                </div>
                            </div>
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Actions
                        </th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php if (empty($clients)): ?>
                        <tr>
                            <td colspan="7" class="px-6 py-4 whitespace-nowrap text-center text-sm text-gray-500">
                                No clients found
                            </td>
                        </tr>
                    <?php endif; ?>
                    <?php foreach ($clients as $client): ?>
                        <?php 
                            // Get business name separately
                            $businessName = $client->getBusinessClientName();
                            
                            // Get contact name (first + last name)
                            $contactName = trim($client->getFirstName() . ' ' . $client->getLastName());
                            if(empty($contactName)) {
                                $contactName = $client->getUsername();
                            }
                            
                            $clientId = $client->getId();
                            
                            // Get client role
                            $user = get_user_by('ID', $clientId);
                            $client_role = $user ? $user->roles[0] ?? 'client' : 'client';
                            
                            // Role styling
                            $role_class = 'bg-blue-100 text-blue-800';
                            $role_icon = 'fas fa-user';
                            
                            switch ($client_role) {
                                case 'administrator':
                                    $role_class = 'bg-red-100 text-red-800';
                                    $role_icon = 'fas fa-crown';
                                    break;
                                case 'editor':
                                    $role_class = 'bg-purple-100 text-purple-800';
                                    $role_icon = 'fas fa-user-edit';
                                    break;
                                case 'author':
                                    $role_class = 'bg-green-100 text-green-800';
                                    $role_icon = 'fas fa-user-edit';
                                    break;
                                case 'contributor':
                                    $role_class = 'bg-yellow-100 text-yellow-800';
                                    $role_icon = 'fas fa-user-plus';
                                    break;
                                case 'subscriber':
                                    $role_class = 'bg-gray-100 text-gray-800';
                                    $role_icon = 'fas fa-user';
                                    break;
                                default:
                                    $role_class = 'bg-blue-100 text-blue-800';
                                    $role_icon = 'fas fa-user';
                            }
                        ?>
                        <tr>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-sm text-gray-500 font-mono font-semibold"><?php echo esc_html($clientId); ?></div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-sm font-medium text-gray-900"><?php echo esc_html($businessName ?: '-'); ?></div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-sm font-medium text-gray-900"><?php echo esc_html($contactName); ?></div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-sm text-gray-500"><?php echo esc_html($client->getEmail()); ?></div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-sm text-gray-500"><?php echo esc_html($client->getPhone()); ?></div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-sm text-gray-500"><?php echo esc_html($client->getUsername()); ?></div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium <?php echo $role_class; ?>">
                                    <i class="<?php echo $role_icon; ?> mr-1"></i>
                                    <?php echo esc_html(ucfirst($client_role)); ?>
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                <div class="flex items-center space-x-2">
                                    <a href="?page=easy-invoice-client-view&client_id=<?php echo esc_attr($clientId); ?>" 
                                       class="inline-flex items-center px-2.5 py-1.5 border border-transparent text-xs font-medium rounded text-indigo-700 bg-indigo-100 hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors duration-200"
                                       title="View Client">
                                        <i class="fas fa-eye mr-1"></i>
                                        View
                                    </a>
                                    <a href="?page=easy-invoice-client-edit&client_id=<?php echo esc_attr($clientId); ?>" 
                                       class="inline-flex items-center px-2.5 py-1.5 border border-transparent text-xs font-medium rounded text-blue-700 bg-blue-100 hover:bg-blue-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors duration-200"
                                       title="Edit Client">
                                        <i class="fas fa-edit mr-1"></i>
                                        Edit
                                    </a>
                                    <?php if ($client_role === 'administrator'): ?>
                                        <button type="button" 
                                                class="inline-flex items-center px-2.5 py-1.5 border border-transparent text-xs font-medium rounded text-gray-400 bg-gray-100 cursor-not-allowed opacity-50"
                                                title="Cannot delete administrator"
                                                disabled>
                                            <i class="fas fa-trash mr-1"></i>
                                            Delete
                                        </button>
                                    <?php else: ?>
                                        <button type="button" 
                                                class="delete-client inline-flex items-center px-2.5 py-1.5 border border-transparent text-xs font-medium rounded text-red-700 bg-red-100 hover:bg-red-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 transition-colors duration-200"
                                                data-id="<?php echo esc_attr($clientId); ?>"
                                                title="Delete Client">
                                            <i class="fas fa-trash mr-1"></i>
                                            Delete
                                        </button>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Bottom Pagination -->
    <?php if ($total_clients > 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_clients)); ?></span>
                    of 
                    <span class="font-medium"><?php echo number_format($total_clients); ?></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(
                        'page' => 'easy-invoice-clients'
                    )
                );
                
                $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; ?>
    
    <!-- Add New Client Modal -->
    <div id="add_client_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-3xl 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">Add New Client</h2>
            
            <?php 
            // Unset the $client variable from the foreach loop to ensure clean add form
            unset($client);
            include_once EASY_INVOICE_PLUGIN_DIR . 'templates/client-form.php'; 
            ?>
        </div>
    </div>
</div>

<script type="text/javascript">
    jQuery(document).ready(function($) {
        // Client functionality is now handled by client-manager.js
        // Only keep delete functionality here since it's specific to the clients listing page
        
        // Table sorting functionality
        let currentSort = { column: 'id', direction: 'desc' };
            
        // Initialize sorting
        function initSorting() {
            // Set initial sort indicator
            updateSortIndicator('id', 'desc');
            
            // Add click handlers to sortable headers
            $('th[data-sort]').on('click', function() {
                const column = $(this).data('sort');
                const currentDirection = currentSort.column === column ? currentSort.direction : 'desc';
                const newDirection = currentDirection === 'asc' ? 'desc' : 'asc';
                
                currentSort = { column: column, direction: newDirection };
                updateSortIndicator(column, newDirection);
                sortTable(column, newDirection);
            });
        }
        
        // Update sort indicator
        function updateSortIndicator(activeColumn, direction) {
            // Reset all indicators
            $('.sort-indicator i').removeClass('fa-sort-up fa-sort-down').addClass('fa-sort text-gray-400');
            
            // Set active indicator
            $(`th[data-sort="${activeColumn}"] .sort-indicator i`)
                .removeClass('fa-sort text-gray-400')
                .addClass(direction === 'asc' ? 'fa-sort-up text-indigo-600' : 'fa-sort-down text-indigo-600');
                        }
        
        // Sort table function
        function sortTable(column, direction) {
            const tbody = $('tbody');
            const rows = tbody.find('tr').toArray();
            
            rows.sort(function(a, b) {
                let aValue, bValue;
                
                switch(column) {
                    case 'id':
                        aValue = parseInt($(a).find('td:first-child div').text());
                        bValue = parseInt($(b).find('td:first-child div').text());
                        break;
                    case 'business_name':
                        aValue = $(a).find('td:nth-child(2) div').text().toLowerCase();
                        bValue = $(b).find('td:nth-child(2) div').text().toLowerCase();
                        break;
                    case 'name':
                        aValue = $(a).find('td:nth-child(3) div').text().toLowerCase();
                        bValue = $(b).find('td:nth-child(3) div').text().toLowerCase();
                        break;
                    case 'email':
                        aValue = $(a).find('td:nth-child(4) div').text().toLowerCase();
                        bValue = $(b).find('td:nth-child(4) div').text().toLowerCase();
                        break;
                    case 'phone':
                        aValue = $(a).find('td:nth-child(5) div').text().toLowerCase();
                        bValue = $(b).find('td:nth-child(5) div').text().toLowerCase();
                        break;
                    case 'username':
                        aValue = $(a).find('td:nth-child(6) div').text().toLowerCase();
                        bValue = $(b).find('td:nth-child(6) div').text().toLowerCase();
                        break;
                    case 'role':
                        aValue = $(a).find('td:nth-child(7) span').text().toLowerCase();
                        bValue = $(b).find('td:nth-child(7) span').text().toLowerCase();
                        break;
                    default:
                        return 0;
                }
                
                if (direction === 'asc') {
                    return aValue > bValue ? 1 : -1;
                    } else {
                    return aValue < bValue ? 1 : -1;
                }
        });
        
            // Reorder rows with animation
            tbody.find('tr').fadeOut(200, function() {
                tbody.empty();
                $.each(rows, function(index, row) {
                    tbody.append(row);
                });
                tbody.find('tr').fadeIn(200);
            });
                        }
        
        // Initialize sorting
        initSorting();
        
        // Delete client functionality
        $(".delete-client").on("click", function(e) {
            e.preventDefault();
            
            const clientId = $(this).data("id");
            const clientName = $(this).closest("tr").find("td:first-child div").text().trim();
            
            // Use the new confirmation system instead of browser confirm
            if (typeof EasyInvoiceConfirmation !== 'undefined') {
                EasyInvoiceConfirmation.confirmAction('delete', 'client "' + clientName + '"', function() {
                    $.ajax({
                        url: easyInvoice.ajaxUrl,
                        type: "POST",
                        data: {
                            action: "easy_invoice_delete_client",
                            client_id: clientId,
                            nonce: easyInvoice.nonce
                        },
                        success: function(response) {
                            if (response.success) {
                                EasyInvoiceToast.success(response.data.message || 'Client deleted successfully');
                                $("[data-id='" + clientId + "']").closest("tr").fadeOut(400, function() {
                                    $(this).remove();
                                    
                                    // Update total clients count
                                    var currentCount = parseInt($("h3:contains('Total Clients')").next().text()) || 0;
                                    $("h3:contains('Total Clients')").next().text(Math.max(0, currentCount - 1));
                                    
                                    // Check if table is empty and show "No clients found"
                                    if ($("tbody tr").length === 0) {
                                        $("tbody").html('<tr><td colspan="6" class="px-6 py-4 whitespace-nowrap text-center text-sm text-gray-500">No clients found</td></tr>');
                                    }
                                });
                            } else {
                                EasyInvoiceToast.error(response.data.message || 'Error deleting client');
                            }
                        },
                        error: function() {
                            EasyInvoiceToast.error('Error connecting to server');
                        }
                    });
                });
            } else {
                // Fallback to browser confirm if toast system not available
                if (confirm("Are you sure you want to delete the client \"" + clientName + "\"? This action cannot be undone.")) {
                    $.ajax({
                        url: easyInvoice.ajaxUrl,
                        type: "POST",
                        data: {
                            action: "easy_invoice_delete_client",
                            client_id: clientId,
                            nonce: easyInvoice.nonce
                        },
                        success: function(response) {
                            if (response.success) {
                                // Use unified toast system
                                if (typeof EasyInvoiceToast !== 'undefined') {
                                    EasyInvoiceToast.success("Client \"" + clientName + "\" has been deleted");
                                } else {
                                    alert("Client \"" + clientName + "\" has been deleted");
                                }
                                
                                // Remove the row from the table
                                $("[data-id='" + clientId + "']").closest("tr").fadeOut(300, function() {
                                    $(this).remove();
                                    
                                    // Update total clients count
                                    var currentCount = parseInt($("h3:contains('Total Clients')").next().text()) || 0;
                                    $("h3:contains('Total Clients')").next().text(Math.max(0, currentCount - 1));
                                    
                                    // Check if table is empty and show "No clients found"
                                    if ($("tbody tr").length === 0) {
                                        $("tbody").html('<tr><td colspan="6" class="px-6 py-4 whitespace-nowrap text-center text-sm text-gray-500">No clients found</td></tr>');
                                    }
                                });
                            } else {
                                // Use unified toast system
                                if (typeof EasyInvoiceToast !== 'undefined') {
                                    EasyInvoiceToast.error(response.data.message || "Error deleting client");
                                } else {
                                    alert(response.data.message || "Error deleting client");
                                }
                            }
                        },
                        error: function() {
                            // Use unified toast system
                            if (typeof EasyInvoiceToast !== 'undefined') {
                                EasyInvoiceToast.error("Error connecting to server");
                            } else {
                                alert("Error connecting to server");
                            }
                        }
                    });
                }
            }
        });
    });
</script>