<?php
/**
 * Recurring Invoices List View
 *
 * @package Freelance_Studio
 */

if (!defined('ABSPATH')) {
    exit;
}

// Status badge class mapping
$status_badge_classes = array(
    'active' => 'status-active',
    'paused' => 'status-pending',
    'completed' => 'status-completed',
    'cancelled' => 'status-cancelled',
);
?>

<?php if (empty($GLOBALS['fs_in_finances'])): ?>
<div class="wrap fs-wrap">
<?php endif; ?>
    <div class="fs-list-header">
        <h1><?php esc_html_e('Recurring Invoices', 'freelance-studio'); ?></h1>
        <div class="fs-header-actions">
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=recurring&action=add') ); ?>" class="fs-btn fs-btn-primary">
                <?php esc_html_e('New Recurring Invoice', 'freelance-studio'); ?>
            </a>
        </div>
    </div>

    <!-- Status Tabs -->
    <ul class="subsubsub">
        <li>
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=recurring') ); ?>" class="<?php echo esc_attr( empty($status) ? 'current' : '' ); ?>">
                <?php esc_html_e('All', 'freelance-studio'); ?> <span class="count">(<?php echo  esc_html( $counts['all'] ); ?>)</span>
            </a> |
        </li>
        <li>
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=recurring&status=active') ); ?>" class="<?php echo esc_attr( $status === 'active' ? 'current' : '' ); ?>">
                <?php esc_html_e('Active', 'freelance-studio'); ?> <span class="count">(<?php echo  esc_html( $counts['active'] ); ?>)</span>
            </a> |
        </li>
        <li>
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=recurring&status=paused') ); ?>" class="<?php echo esc_attr( $status === 'paused' ? 'current' : '' ); ?>">
                <?php esc_html_e('Paused', 'freelance-studio'); ?> <span class="count">(<?php echo  esc_html( $counts['paused'] ); ?>)</span>
            </a>
        </li>
    </ul>

    <!-- Filters -->
    <div class="fs-filters" style="clear: both; padding-top: 10px;">
        <form method="get" action="">
            <input type="hidden" name="page" value="fs-recurring-invoices">
            <?php if ($status): ?>
                <input type="hidden" name="status" value="<?php echo esc_attr($status); ?>">
            <?php endif; ?>
            
            <select name="client_id">
                <option value=""><?php esc_html_e('All Clients', 'freelance-studio'); ?></option>
                <?php foreach ($clients as $client): ?>
                    <option value="<?php echo esc_attr($client->id); ?>" <?php selected($client_id, $client->id); ?>>
                        <?php echo esc_html($client->company_name ?: $client->name); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            
            <button type="submit" class="button"><?php esc_html_e('Filter', 'freelance-studio'); ?></button>
        </form>
    </div>

    <?php if (empty($recurring_invoices)): ?>
        <div class="fs-empty-state">
            <div class="fs-empty-state-icon">🔄</div>
            <h3><?php esc_html_e('No recurring invoices yet', 'freelance-studio'); ?></h3>
            <p><?php esc_html_e('Set up automatic recurring invoices for retainers or ongoing services.', 'freelance-studio'); ?></p>
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=recurring&action=add') ); ?>" class="button button-primary">
                <?php esc_html_e('Create Recurring Invoice', 'freelance-studio'); ?>
            </a>
        </div>
    <?php else: ?>
        <!-- Mobile Recurring Invoice List -->
        <div class="fs-invoice-mobile-list fs-mobile-only">
            <?php foreach ($recurring_invoices as $ri): 
                $client_display = $ri->company_name ?: $ri->client_name;
                $badge_class = $status_badge_classes[$ri->status] ?? 'status-draft';
                $freq_label = $frequencies[$ri->frequency] ?? $ri->frequency;
            ?>
                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=recurring&action=view&id=' . $ri->id) ); ?>" class="fs-invoice-mobile-row">
                    <div class="fs-invoice-mobile-left">
                        <span class="fs-invoice-mobile-client"><?php echo esc_html($ri->name); ?></span>
                        <span class="fs-invoice-mobile-number"><?php echo esc_html($client_display); ?> · <?php echo esc_html($freq_label); ?></span>
                        <span class="fs-status-badge <?php echo  esc_attr( $badge_class ); ?>">
                            <?php echo esc_html(strtoupper($statuses[$ri->status] ?? $ri->status)); ?>
                        </span>
                    </div>
                    <div class="fs-invoice-mobile-right">
                        <span class="fs-invoice-mobile-amount"><?php echo  esc_html( FS_View_Context::format_currency($ri->amount) ); ?></span>
                        <?php if ($ri->next_invoice_date && $ri->status === 'active'): ?>
                            <?php $is_due = strtotime($ri->next_invoice_date) <= strtotime('today'); ?>
                            <span class="fs-invoice-mobile-date<?php echo  esc_attr( $is_due ? ' fs-text-danger' : '' ); ?>"><?php esc_html_e('Next:', 'freelance-studio'); ?> <?php echo  esc_html( FS_View_Context::format_date($ri->next_invoice_date, 'm/d/y') ); ?></span>
                        <?php else: ?>
                            <span class="fs-invoice-mobile-date"><?php echo intval($ri->invoices_generated); ?> <?php esc_html_e('generated', 'freelance-studio'); ?></span>
                        <?php endif; ?>
                    </div>
                </a>
            <?php endforeach; ?>
        </div>

        <!-- List Table -->
        <div class="fs-form-section fs-desktop-only">
            <table class="fs-table widefat">
                <thead>
                    <tr>
                        <th><?php esc_html_e('Name', 'freelance-studio'); ?></th>
                        <th><?php esc_html_e('Client', 'freelance-studio'); ?></th>
                        <th><?php esc_html_e('Amount', 'freelance-studio'); ?></th>
                        <th><?php esc_html_e('Frequency', 'freelance-studio'); ?></th>
                        <th><?php esc_html_e('Next Invoice', 'freelance-studio'); ?></th>
                        <th><?php esc_html_e('Generated', 'freelance-studio'); ?></th>
                        <th><?php esc_html_e('Status', 'freelance-studio'); ?></th>
                        <th class="column-actions"></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($recurring_invoices as $ri): ?>
                        <tr>
                            <td>
                                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=recurring&action=view&id=' . $ri->id) ); ?>">
                                    <strong><?php echo esc_html($ri->name); ?></strong>
                                </a>
                                <?php if ($ri->project_name): ?>
                                    <br><small class="fs-muted"><?php echo esc_html($ri->project_name); ?></small>
                                <?php endif; ?>
                            </td>
                            <td><?php echo esc_html($ri->company_name ?: $ri->client_name); ?></td>
                            <td><?php echo  esc_html( FS_View_Context::format_currency($ri->amount) ); ?></td>
                            <td><?php echo esc_html($frequencies[$ri->frequency] ?? $ri->frequency); ?></td>
                            <td>
                                <?php if ($ri->next_invoice_date): ?>
                                    <?php 
                                    $next_date = strtotime($ri->next_invoice_date);
                                    $is_due = $next_date <= strtotime('today');
                                    ?>
                                    <span class="<?php echo $is_due ? 'fs-text-warning' : ''; ?>">
                                        <?php echo esc_html(gmdate('M j, Y', $next_date)); ?>
                                    </span>
                                    <?php if ($is_due && $ri->status === 'active'): ?>
                                        <br><small class="fs-text-warning"><?php esc_html_e('Due!', 'freelance-studio'); ?></small>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <span class="fs-muted">—</span>
                                <?php endif; ?>
                            </td>
                            <td><?php echo intval($ri->invoices_generated); ?></td>
                            <td>
                                <?php $badge_class = $status_badge_classes[$ri->status] ?? 'status-draft'; ?>
                                <span class="fs-status-badge <?php echo  esc_attr( $badge_class ); ?>">
                                    <?php echo esc_html(strtoupper($statuses[$ri->status] ?? $ri->status)); ?>
                                </span>
                            </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=recurring&action=view&id=' . $ri->id) ); ?>"><?php esc_html_e('View', 'freelance-studio'); ?></a>
                                        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=recurring&action=edit&id=' . $ri->id) ); ?>"><?php esc_html_e('Edit', 'freelance-studio'); ?></a>
                                        <?php if ($ri->status === 'active'): ?>
                                            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=recurring&action=generate&id=' . $ri->id) ); ?>" onclick="return confirm('<?php esc_html_e('Generate an invoice now?', 'freelance-studio'); ?>');"><?php esc_html_e('Generate Now', 'freelance-studio'); ?></a>
                                        <?php endif; ?>
                                        <hr>
                                        <a href="#" class="fs-delete-recurring text-danger" data-id="<?php echo esc_attr($ri->id); ?>"><?php esc_html_e('Delete', 'freelance-studio'); ?></a>
                                    </div>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
<?php if (empty($GLOBALS['fs_in_finances'])): ?>
</div>
<?php endif; ?>

<script>
jQuery(document).ready(function($) {
    $('.fs-delete-recurring').on('click', function(e) {
        e.preventDefault();
        if (!confirm('<?php esc_html_e('Are you sure you want to delete this recurring invoice?', 'freelance-studio'); ?>')) {
            return;
        }
        
        var id = $(this).data('id');
        var $row = $(this).closest('tr');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_delete_recurring_invoice',
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
                id: id
            },
            success: function(response) {
                if (response.success) {
                    $row.fadeOut(300, function() { $(this).remove(); });
                } else {
                    alert(response.data || 'Error deleting recurring invoice');
                }
            }
        });
    });
});
</script>
