<?php
/**
 * Invoices List View
 */
if (!defined('ABSPATH')) exit;

$statuses = FS_Invoice::get_statuses();
?>
<?php if (empty($GLOBALS['fs_in_finances'])): ?>
<div class="wrap fs-wrap">
<?php endif; ?>
    <div class="fs-list-header">
        <h1><?php esc_html_e('Invoices', 'freelance-studio'); ?></h1>
        <div class="fs-header-actions">
            <button type="button" class="fs-btn fs-btn-secondary" id="fs-export-invoices-btn">
                <span class="dashicons dashicons-download" style="margin-right: 5px;"></span><?php esc_html_e('Export CSV', 'freelance-studio'); ?>
            </button>
            <button type="button" class="fs-btn fs-open-invoice-wizard" id="fs-invoice-wizard-btn">
                <?php esc_html_e('Invoice Wizard', 'freelance-studio'); ?>
            </button>
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=invoices&action=add') ); ?>" class="fs-btn fs-btn-primary"><?php esc_html_e('New Invoice', 'freelance-studio'); ?></a>
        </div>
    </div>
    <?php if ($message): ?>
        <div class="fs-notice <?php echo in_array($message, array('error', 'not_found')) ? 'error' : 'success'; ?>"><?php echo esc_html($messages[$message] ?? 'Done'); ?></div>
    <?php endif; ?>
    
    <?php
    // Show invoice sends counter for free plan
    if ( function_exists( 'fs_studio_is_free_plan' ) && fs_studio_is_free_plan() ):
        $sends_count = fs_studio_get_usage_count( 'invoice_sends' );
        $limits = fs_studio_free_limits();
        if ( $sends_count >= $limits['invoice_sends'] ):
            fs_studio_upgrade_notice( 'invoice_sends', 'banner' );
        else:
    ?>
        <div class="fs-usage-counter">
            <span class="fs-usage-counter-text">
                <?php /* translators: 1. current send count, 2. monthly send limit */ ?>
                <?php echo esc_html( sprintf( __(  'Invoice sends this month: %1$d of %2$d', 'freelance-studio' ), $sends_count, $limits['invoice_sends'] ) ); ?>
            </span>
            <div class="fs-usage-bar">
                <div class="fs-usage-bar-fill" style="width: <?php echo  esc_attr( min( 100, ( $sends_count / $limits['invoice_sends'] ) * 100 ) ); ?>%"></div>
            </div>
            <a href="<?php echo  esc_url( freelance_studio_fs()->get_upgrade_url() ); ?>" class="fs-usage-upgrade-link"><?php esc_html_e( 'Upgrade for unlimited', 'freelance-studio' ); ?> &rarr;</a>
        </div>
    <?php
        endif;
    endif;
    ?>
    
    <?php if ($total_outstanding > 0): ?>
        <div class="fs-notice info">
            <strong><?php esc_html_e('Outstanding:', 'freelance-studio'); ?></strong> <?php echo  esc_html( FS_View_Context::format_currency($total_outstanding) ); ?>
            <?php /* translators: 1. count/number */ ?>
            <?php if ($overdue_count > 0): ?> | <span class="text-danger"><?php echo wp_kses_post( sprintf( __('%d overdue', 'freelance-studio'), $overdue_count) ); ?></span><?php endif; ?>
        </div>
    <?php endif; ?>
    
    <div class="fs-filters">
        <form method="get">
            <input type="hidden" name="page" value="fs-finances">
            <input type="hidden" name="tab" value="invoices">
            <select name="status"><option value=""><?php esc_html_e('All Statuses', 'freelance-studio'); ?></option>
                <?php foreach ($statuses as $k => $l): ?><option value="<?php echo esc_attr($k); ?>" <?php selected($_GET['status'] ?? '', $k); ?>><?php echo esc_html($l); ?></option><?php endforeach; ?>
            </select>
            <select name="client_id"><option value=""><?php esc_html_e('All Clients', 'freelance-studio'); ?></option>
                <?php foreach ($clients as $c): ?><option value="<?php echo  intval( $c->id ); ?>" <?php selected($_GET['client_id'] ?? 0, $c->id); ?>><?php echo esc_html($c->company_name ?: $c->name); ?></option><?php endforeach; ?>
            </select>
            <button type="submit" class="button"><?php esc_html_e('Filter', 'freelance-studio'); ?></button>
        </form>
    </div>
    
    <?php if (empty($invoices)): ?>
        <div class="fs-empty-state"><div class="fs-empty-state-icon">📄</div><h3><?php esc_html_e('No invoices yet', 'freelance-studio'); ?></h3>
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=invoices&action=add') ); ?>" class="button button-primary"><?php esc_html_e('Create Invoice', 'freelance-studio'); ?></a>
        </div>
    <?php else: ?>
        <!-- Batch Actions Bar -->
        <div class="fs-batch-actions" id="fs-batch-actions" style="display: none;">
            <span class="fs-batch-count"><span id="fs-selected-count">0</span> <?php esc_html_e('selected', 'freelance-studio'); ?></span>
            <button type="button" class="fs-btn fs-btn-success fs-btn-small" id="fs-batch-mark-paid">
                <?php esc_html_e('Mark as Paid', 'freelance-studio'); ?>
            </button>
            <button type="button" class="fs-btn fs-btn-secondary fs-btn-small" id="fs-batch-clear">
                <?php esc_html_e('Clear Selection', 'freelance-studio'); ?>
            </button>
        </div>
        
        <!-- Mobile Invoice List -->
        <div class="fs-invoice-mobile-list fs-mobile-only">
            <?php foreach ($invoices as $inv): 
                $client_display = $inv->client_company ?: $inv->client_name;
            ?>
                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=invoices&action=view&id=' . $inv->id) ); ?>" class="fs-invoice-mobile-row">
                    <div class="fs-invoice-mobile-left">
                        <span class="fs-invoice-mobile-client"><?php echo esc_html($client_display); ?></span>
                        <span class="fs-invoice-mobile-number"><?php echo esc_html($inv->invoice_number); ?></span>
                        <?php echo  wp_kses_post( FS_View_Context::status_badge($inv->status) ); ?>
                    </div>
                    <div class="fs-invoice-mobile-right">
                        <span class="fs-invoice-mobile-amount"><?php echo  esc_html( FS_View_Context::format_currency($inv->total) ); ?></span>
                        <?php 
                        $is_past_due = !empty($inv->due_date) && strtotime($inv->due_date) < strtotime('today') && !in_array($inv->status, array('paid', 'cancelled', 'draft'));
                        ?>
                        <span class="fs-invoice-mobile-date<?php echo  esc_attr( $is_past_due ? ' fs-text-danger' : '' ); ?>"><?php esc_html_e('Due:', 'freelance-studio'); ?> <?php echo  esc_html( FS_View_Context::format_date($inv->due_date, 'm/d/y') ); ?></span>
                    </div>
                </a>
            <?php endforeach; ?>
        </div>

        <div class="fs-form-section fs-desktop-only">
            <div class="fs-table-responsive">
                <table class="fs-table widefat">
                <thead>
                    <tr>
                        <th class="column-cb" style="width: 30px;"><input type="checkbox" id="fs-select-all-invoices"></th>
                        <th><?php esc_html_e('Invoice #', 'freelance-studio'); ?></th>
                        <th><?php esc_html_e('Client', 'freelance-studio'); ?></th>
                        <th><?php esc_html_e('Project', 'freelance-studio'); ?></th>
                        <th><?php esc_html_e('Due', 'freelance-studio'); ?></th>
                        <th><?php esc_html_e('Amount', 'freelance-studio'); ?></th>
                        <th><?php esc_html_e('Status', 'freelance-studio'); ?></th>
                        <th class="column-actions"></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($invoices as $inv): ?>
                        <tr data-invoice-id="<?php echo  intval( $inv->id ); ?>">
                            <td class="column-cb">
                                <?php if ($inv->status !== 'paid'): ?>
                                    <input type="checkbox" class="fs-invoice-checkbox" value="<?php echo  intval( $inv->id ); ?>">
                                <?php endif; ?>
                            </td>
                            <td><a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=invoices&action=view&id=' . $inv->id) ); ?>"><strong><?php echo esc_html($inv->invoice_number); ?></strong></a></td>
                            <td><?php echo esc_html($inv->client_company ?: $inv->client_name); ?></td>
                            <td><?php echo $inv->project_name ? esc_html($inv->project_name) : '—'; ?></td>
                            <td><?php echo  esc_html( FS_View_Context::format_date($inv->due_date) ); ?></td>
                            <td><?php echo  esc_html( FS_View_Context::format_currency($inv->total) ); ?></td>
                            <td>
                                <select class="fs-inline-status-select status-<?php echo esc_attr($inv->status); ?>" data-invoice-id="<?php echo  intval( $inv->id ); ?>" data-original="<?php echo esc_attr($inv->status); ?>">
                                    <?php foreach ($statuses as $status_key => $status_label): ?>
                                        <option value="<?php echo esc_attr($status_key); ?>" <?php selected($inv->status, $status_key); ?>><?php echo esc_html($status_label); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </td>
                            <td class="column-actions">
                                <div class="fs-row-menu">
                                    <button type="button" class="fs-row-menu-trigger">⋯</button>
                                    <div class="fs-row-menu-dropdown">
                                        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=invoices&action=view&id=' . $inv->id) ); ?>"><?php esc_html_e('Preview', 'freelance-studio'); ?></a>
                                        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=invoices&action=edit&id=' . $inv->id) ); ?>"><?php esc_html_e('Edit', 'freelance-studio'); ?></a>
                                        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=invoices&action=pdf&id=' . $inv->id) ); ?>" target="_blank"><?php esc_html_e('Download PDF', 'freelance-studio'); ?></a>
                                        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=invoices&action=duplicate&id=' . $inv->id) ); ?>"><?php esc_html_e('Duplicate', 'freelance-studio'); ?></a>
                                        <?php if ($inv->status !== 'paid'): ?>
                                            <hr>
                                            <a href="#" class="fs-delete-btn text-danger" data-type="invoice" data-id="<?php echo  intval( $inv->id ); ?>"><?php esc_html_e('Delete', 'freelance-studio'); ?></a>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            </div>
        </div>
        
        <?php if ($total_pages > 1): ?>
        <div class="fs-pagination">
            <span class="fs-pagination-info">
                <?php printf(
                    /* translators: 1. start number, 2. end number, 3. total entries */
                    esc_html__('Showing %1$d–%2$d of %3$d invoices', 'freelance-studio'),
                    $offset + 1,
                    min($offset + $per_page, $total_invoices),
                    $total_invoices
                ); ?>
            </span>
            <div class="fs-pagination-links">
                <?php
                $base_url = admin_url('admin.php?page=fs-finances&tab=invoices');
                $query_params = array();
                if (!empty($status_filter)) $query_params['status'] = $status_filter;
                if (!empty($client_filter)) $query_params['client_id'] = $client_filter;
                if ($per_page !== 25) $query_params['per_page'] = $per_page;
                $base_url = add_query_arg($query_params, $base_url);
                ?>
                <?php if ($current_page > 1): ?>
                    <a href="<?php echo esc_url(add_query_arg('paged', $current_page - 1, $base_url)); ?>" class="fs-btn fs-btn-secondary fs-btn-small">&laquo; <?php esc_html_e('Prev', 'freelance-studio'); ?></a>
                <?php endif; ?>
                
                <?php
                $start_page = max(1, $current_page - 2);
                $end_page = min($total_pages, $current_page + 2);
                
                if ($start_page > 1): ?>
                    <a href="<?php echo esc_url(add_query_arg('paged', 1, $base_url)); ?>" class="fs-pagination-link">1</a>
                    <?php if ($start_page > 2): ?><span class="fs-pagination-ellipsis">&hellip;</span><?php endif; ?>
                <?php endif; ?>
                
                <?php for ($i = $start_page; $i <= $end_page; $i++): ?>
                    <?php if ($i == $current_page): ?>
                        <span class="fs-pagination-current"><?php echo esc_html($i); ?></span>
                    <?php else: ?>
                        <a href="<?php echo esc_url(add_query_arg('paged', $i, $base_url)); ?>" class="fs-pagination-link"><?php echo esc_html($i); ?></a>
                    <?php endif; ?>
                <?php endfor; ?>
                
                <?php if ($end_page < $total_pages): ?>
                    <?php if ($end_page < $total_pages - 1): ?><span class="fs-pagination-ellipsis">&hellip;</span><?php endif; ?>
                    <a href="<?php echo esc_url(add_query_arg('paged', $total_pages, $base_url)); ?>" class="fs-pagination-link"><?php echo esc_html($total_pages); ?></a>
                <?php endif; ?>
                
                <?php if ($current_page < $total_pages): ?>
                    <a href="<?php echo esc_url(add_query_arg('paged', $current_page + 1, $base_url)); ?>" class="fs-btn fs-btn-secondary fs-btn-small"><?php esc_html_e('Next', 'freelance-studio'); ?> &raquo;</a>
                <?php endif; ?>
            </div>
            <div class="fs-pagination-perpage">
                <select onchange="window.location.href=this.value;">
                    <?php foreach (array(10, 25, 50, 100) as $pp): ?>
                        <option value="<?php echo esc_url(add_query_arg(array('per_page' => $pp, 'paged' => 1), $base_url)); ?>" <?php selected($per_page, $pp); ?>><?php echo esc_html($pp); ?> <?php esc_html_e('per page', 'freelance-studio'); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
        <?php endif; ?>
    <?php endif; ?>
</div>

<!-- Batch Mark Paid Modal -->
<div id="fs-batch-paid-modal" class="fs-modal" style="display: none;">
    <div class="fs-modal-content" style="max-width: 400px;">
        <div class="fs-modal-header">
            <h3><?php esc_html_e('Mark Invoices as Paid', 'freelance-studio'); ?></h3>
            <button type="button" class="fs-modal-close">&times;</button>
        </div>
        <div class="fs-modal-body">
            <p><?php esc_html_e('You are about to mark the selected invoices as paid.', 'freelance-studio'); ?></p>
            <div class="fs-form-row">
                <label for="fs-batch-paid-date"><?php esc_html_e('Payment Date', 'freelance-studio'); ?></label>
                <input type="date" id="fs-batch-paid-date" value="<?php echo  esc_attr( gmdate('Y-m-d') ); ?>" class="regular-text">
            </div>
        </div>
        <div class="fs-modal-footer">
            <button type="button" class="fs-btn fs-btn-secondary fs-modal-close"><?php esc_html_e('Cancel', 'freelance-studio'); ?></button>
            <button type="button" class="fs-btn fs-btn-success" id="fs-confirm-batch-paid"><?php esc_html_e('Mark as Paid', 'freelance-studio'); ?></button>
        </div>
    </div>
</div>

<?php // Include Invoice Wizard Modal ?>
<?php include JEEB_FS_PLUGIN_DIR . 'includes/views/partials/invoice-wizard-modal.php'; ?>

<?php if (empty($GLOBALS['fs_in_finances'])): ?>
</div>
<?php endif; ?>
