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

// Get year for export
$export_year = isset($_GET['start_date']) && !empty($_GET['start_date']) 
    ? gmdate('Y', strtotime($_GET['start_date'])) 
    : gmdate('Y');

// Get current tab
$expense_tab = isset($_GET['expense_tab']) ? sanitize_text_field($_GET['expense_tab']) : 'all';

// Get recurring expenses for tab and count
$recurring_expenses = array();
$recurring_frequencies = FS_Expense::get_recurring_frequencies();
if ($expense_tab === 'recurring') {
    $recurring_expenses = FS_Expense::get_recurring_expenses();
}
$recurring_count = 0;
{
    global $wpdb;
    $exp_table = $wpdb->prefix . 'fs_expenses';
    $recurring_count = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$exp_table} WHERE is_recurring = 1 AND parent_expense_id IS NULL");
}
?>
<?php if (empty($GLOBALS['fs_in_finances'])): ?>
<div class="wrap fs-wrap">
<?php endif; ?>
    <div class="fs-page-header">
        <h1 class="fs-page-title"><?php esc_html_e('Expenses', 'freelance-studio'); ?></h1>
        <div style="flex:1;"></div>
        <div class="fs-header-actions">
            <?php if (!empty($expenses) && $expense_tab !== 'recurring'): ?>
            <div class="fs-export-dropdown">
                <button type="button" class="fs-btn fs-btn-secondary fs-export-btn">
                    <span class="dashicons dashicons-download"></span>
                    <?php esc_html_e('Export for Tax Preparer', 'freelance-studio'); ?>
                    <span class="dashicons dashicons-arrow-down-alt2"></span>
                </button>
                <div class="fs-export-menu">
                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=expenses&export=tax_deductions&format=csv&year=' . $export_year) ); ?>" class="fs-export-option">
                        <span class="dashicons dashicons-media-spreadsheet"></span>
                        <?php esc_html_e('Download CSV', 'freelance-studio'); ?>
                    </a>
                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=expenses&export=tax_deductions&format=pdf&year=' . $export_year) ); ?>" class="fs-export-option">
                        <span class="dashicons dashicons-pdf"></span>
                        <?php esc_html_e('Download PDF', 'freelance-studio'); ?>
                    </a>
                </div>
            </div>
            <?php endif; ?>
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=expenses&action=add') ); ?>" class="fs-btn fs-btn-primary"><?php esc_html_e('New expense', 'freelance-studio'); ?></a>
        </div>
    </div>
    
    <!-- Tab Navigation -->
    <div class="fs-tab-nav">
        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=expenses') ); ?>" class="fs-tab <?php echo esc_attr( $expense_tab === 'all' ? 'active' : '' ); ?>">
            <?php esc_html_e('All Expenses', 'freelance-studio'); ?>
        </a>
        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=expenses&expense_tab=recurring') ); ?>" class="fs-tab <?php echo esc_attr( $expense_tab === 'recurring' ? 'active' : '' ); ?>">
            <?php esc_html_e('Recurring', 'freelance-studio'); ?>
            <?php if ($recurring_count > 0): ?>
                <span class="fs-tab-count"><?php echo  intval( $recurring_count ); ?></span>
            <?php endif; ?>
        </a>
    </div>

    <?php if ($message): ?>
        <?php
        $notice_class = 'success';
        $notice_text = __('Done!', 'freelance-studio');
        switch ($message) {
            case 'created':
                $notice_text = __('Expense added successfully.', 'freelance-studio');
                break;
            case 'updated':
                $notice_text = __('Expense updated successfully.', 'freelance-studio');
                break;
            case 'deleted':
                $notice_text = __('Expense deleted.', 'freelance-studio');
                break;
            case 'duplicated':
                $notice_text = __('Expense duplicated successfully.', 'freelance-studio');
                break;
            case 'error':
                $notice_class = 'error';
                $notice_text = __('Something went wrong. Please try again.', 'freelance-studio');
                break;
        }
        ?>
        <div class="fs-notice <?php echo  esc_attr( $notice_class ); ?>"><?php echo  esc_attr( $notice_text ); ?></div>
    <?php endif; ?>
    
    <?php if ($expense_tab === 'recurring'): ?>
    <!-- Recurring Expenses Tab -->
    <?php if ( function_exists( 'fs_studio_is_free_plan' ) && fs_studio_is_free_plan() ): ?>
        <div class="fs-pro-overlay-wrapper" style="min-height: 200px;">
            <div class="fs-pro-overlay">
                <div class="fs-pro-overlay-content">
                    <span class="fs-upgrade-badge">PRO</span>
                    <h3><?php esc_html_e( 'Recurring Expenses', 'freelance-studio' ); ?></h3>
                    <p><?php esc_html_e( 'Automatically track subscriptions and regular expenses. Available with Freelance Studio Pro.', 'freelance-studio' ); ?></p>
                    <a href="<?php echo function_exists( 'freelance_studio_fs' ) ? esc_url( freelance_studio_fs()->get_upgrade_url() ) : '#'; ?>" class="fs-btn fs-btn-primary fs-btn-small">
                        <?php esc_html_e( 'Upgrade to Pro', 'freelance-studio' ); ?>
                    </a>
                </div>
            </div>
            <div class="fs-empty-state" aria-hidden="true" style="opacity:0.5; pointer-events:none;">
                <div class="fs-empty-state-icon"><span class="dashicons dashicons-controls-repeat"></span></div>
                <h3><?php esc_html_e('Recurring expenses', 'freelance-studio'); ?></h3>
                <p><?php esc_html_e('Track subscriptions like Adobe, hosting, and other regular expenses automatically.', 'freelance-studio'); ?></p>
            </div>
        </div>
    <?php elseif (empty($recurring_expenses)): ?>
        <div class="fs-empty-state">
            <div class="fs-empty-state-icon"><span class="dashicons dashicons-controls-repeat"></span></div>
            <h3><?php esc_html_e('No recurring expenses', 'freelance-studio'); ?></h3>
            <p><?php esc_html_e('Create a recurring expense by enabling the "Recurring" option when adding an expense.', 'freelance-studio'); ?></p>
        </div>
    <?php else: ?>
        <!-- Mobile Recurring Expenses -->
        <div class="fs-invoice-mobile-list fs-mobile-only">
            <?php foreach ($recurring_expenses as $rexp): ?>
                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=expenses&action=edit&id=' . $rexp->id) ); ?>" class="fs-invoice-mobile-row">
                    <div class="fs-invoice-mobile-left">
                        <span class="fs-invoice-mobile-client"><?php echo esc_html($rexp->expense_name); ?></span>
                        <span class="fs-invoice-mobile-number"><?php echo esc_html($rexp->category); ?> · <?php echo esc_html($recurring_frequencies[$rexp->recurring_frequency] ?? $rexp->recurring_frequency); ?></span>
                    </div>
                    <div class="fs-invoice-mobile-right">
                        <span class="fs-invoice-mobile-amount"><?php echo  esc_html( FS_View_Context::format_currency($rexp->amount) ); ?></span>
                        <?php if ($rexp->recurring_end_date): ?>
                            <span class="fs-invoice-mobile-date"><?php esc_html_e('Ends:', 'freelance-studio'); ?> <?php echo  esc_html( FS_View_Context::format_date($rexp->recurring_end_date, 'm/d/y') ); ?></span>
                        <?php else: ?>
                            <span class="fs-invoice-mobile-date"><?php esc_html_e('No end date', 'freelance-studio'); ?></span>
                        <?php endif; ?>
                    </div>
                </a>
            <?php endforeach; ?>
        </div>

        <!-- Desktop Recurring Table -->
        <div class="fs-form-section fs-desktop-only">
            <table class="fs-table widefat">
                <thead><tr>
                    <th><?php esc_html_e('Expense', 'freelance-studio'); ?></th>
                    <th><?php esc_html_e('Category', '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('Project', 'freelance-studio'); ?></th>
                    <th><?php esc_html_e('End Date', 'freelance-studio'); ?></th>
                    <th class="column-actions"></th>
                </tr></thead>
                <tbody>
                    <?php foreach ($recurring_expenses as $rexp): ?>
                        <tr>
                            <td><a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=expenses&action=edit&id=' . $rexp->id) ); ?>"><strong><?php echo esc_html($rexp->expense_name); ?></strong></a></td>
                            <td><?php echo esc_html($rexp->category); ?></td>
                            <td><?php echo  esc_html( FS_View_Context::format_currency($rexp->amount) ); ?></td>
                            <td><?php echo esc_html($recurring_frequencies[$rexp->recurring_frequency] ?? $rexp->recurring_frequency); ?></td>
                            <td><?php echo $rexp->project_name ? esc_html($rexp->project_name) : '—'; ?></td>
                            <td>
                                <?php if ($rexp->recurring_end_date): ?>
                                    <?php echo  esc_html( FS_View_Context::format_date($rexp->recurring_end_date) ); ?>
                                <?php else: ?>
                                    <span class="fs-muted"><?php esc_html_e('No end date', 'freelance-studio'); ?></span>
                                <?php endif; ?>
                            </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=expenses&action=edit&id=' . $rexp->id) ); ?>"><?php esc_html_e('Edit', 'freelance-studio'); ?></a>
                                        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=expenses&action=duplicate&id=' . $rexp->id) ); ?>"><?php esc_html_e('Duplicate', 'freelance-studio'); ?></a>
                                        <hr>
                                        <a href="#" class="fs-delete-btn text-danger" data-type="expense" data-id="<?php echo  intval( $rexp->id ); ?>"><?php esc_html_e('Delete', 'freelance-studio'); ?></a>
                                    </div>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
    
    <?php else: ?>
    <!-- All Expenses Tab -->
    <?php if ($total_expenses > 0): ?>
        <div class="fs-notice info"><strong><?php esc_html_e('Total:', 'freelance-studio'); ?></strong> <?php echo  esc_html( FS_View_Context::format_currency($total_expenses) ); ?></div>
    <?php endif; ?>
    
    <div class="fs-filters">
        <form method="get">
            <input type="hidden" name="page" value="fs-finances">
            <input type="hidden" name="tab" value="expenses">
            <select name="category"><option value=""><?php esc_html_e('All Categories', 'freelance-studio'); ?></option>
                <?php foreach ($categories as $k => $l): ?><option value="<?php echo esc_attr($k); ?>" <?php selected($_GET['category'] ?? '', $k); ?>><?php echo esc_html($l); ?></option><?php endforeach; ?>
            </select>
            <input type="date" name="start_date" value="<?php echo esc_attr($_GET['start_date'] ?? ''); ?>" placeholder="Start">
            <input type="date" name="end_date" value="<?php echo esc_attr($_GET['end_date'] ?? ''); ?>" placeholder="End">
            <button type="submit" class="button"><?php esc_html_e('Filter', 'freelance-studio'); ?></button>
        </form>
    </div>
    
    <?php if (empty($expenses)): ?>
        <div class="fs-empty-state"><div class="fs-empty-state-icon">🧾</div><h3><?php esc_html_e('No expenses yet', 'freelance-studio'); ?></h3>
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=expenses&action=add') ); ?>" class="fs-btn fs-btn-primary"><?php esc_html_e('New expense', 'freelance-studio'); ?></a>
        </div>
    <?php else: ?>
        <!-- Mobile Expense List -->
        <div class="fs-invoice-mobile-list fs-mobile-only">
            <?php foreach ($expenses as $exp): 
                $is_recurring = isset($exp->is_recurring) && $exp->is_recurring;
                $is_recurring_child = isset($exp->parent_expense_id) && $exp->parent_expense_id;
            ?>
                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=expenses&action=edit&id=' . $exp->id) ); ?>" class="fs-invoice-mobile-row">
                    <div class="fs-invoice-mobile-left">
                        <span class="fs-invoice-mobile-client">
                            <?php echo esc_html($exp->expense_name); ?>
                            <?php if ($is_recurring): ?> <span title="<?php esc_attr_e('Recurring', 'freelance-studio'); ?>">🔄</span><?php endif; ?>
                            <?php if ($is_recurring_child): ?> <span title="<?php esc_attr_e('Auto-generated', 'freelance-studio'); ?>">↩</span><?php endif; ?>
                        </span>
                        <span class="fs-invoice-mobile-number"><?php echo esc_html($exp->category); ?><?php if ($exp->project_name): ?> · <?php echo esc_html($exp->project_name); ?><?php endif; ?></span>
                    </div>
                    <div class="fs-invoice-mobile-right">
                        <span class="fs-invoice-mobile-amount"><?php echo  esc_html( FS_View_Context::format_currency($exp->amount) ); ?></span>
                        <span class="fs-invoice-mobile-date"><?php echo  esc_html( FS_View_Context::format_date($exp->expense_date, 'm/d/y') ); ?></span>
                    </div>
                </a>
            <?php endforeach; ?>
        </div>

        <!-- Desktop Expense Table -->
        <div class="fs-form-section fs-desktop-only">
            <table class="fs-table widefat">
                <thead><tr><th><?php esc_html_e('Date', 'freelance-studio'); ?></th><th><?php esc_html_e('Description', 'freelance-studio'); ?></th><th><?php esc_html_e('Category', 'freelance-studio'); ?></th><th><?php esc_html_e('Project', 'freelance-studio'); ?></th><th><?php esc_html_e('Amount', 'freelance-studio'); ?></th><th><?php esc_html_e('Receipt', 'freelance-studio'); ?></th><th class="column-actions"></th></tr></thead>
                <tbody>
                    <?php foreach ($expenses as $exp): 
                        $receipt_info = FS_Expense::get_receipt_info($exp->id);
                        $is_recurring = isset($exp->is_recurring) && $exp->is_recurring;
                        $is_recurring_child = isset($exp->parent_expense_id) && $exp->parent_expense_id;
                    ?>
                        <tr>
                            <td><?php echo  esc_html( FS_View_Context::format_date($exp->expense_date) ); ?></td>
                            <td>
                                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=expenses&action=edit&id=' . $exp->id) ); ?>"><?php echo esc_html($exp->expense_name); ?></a>
                                <?php if ($is_recurring): ?>
                                    <span class="fs-recurring-badge" title="<?php esc_attr_e('Recurring expense', 'freelance-studio'); ?>">🔄</span>
                                <?php elseif ($is_recurring_child): ?>
                                    <span class="fs-recurring-child" title="<?php esc_attr_e('Auto-generated from recurring expense', 'freelance-studio'); ?>">↩</span>
                                <?php endif; ?>
                            </td>
                            <td><?php echo esc_html($exp->category); ?></td>
                            <td><?php echo $exp->project_name ? esc_html($exp->project_name) : '—'; ?></td>
                            <td><?php echo  esc_html( FS_View_Context::format_currency($exp->amount) ); ?></td>
                            <td>
                                <?php if ($receipt_info): ?>
                                    <a href="<?php echo esc_url($receipt_info['file_url']); ?>" target="_blank" title="<?php esc_attr_e('View Receipt', 'freelance-studio'); ?>">📎</a>
                                <?php else: ?>
                                    —
                                <?php endif; ?>
                            </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=expenses&action=edit&id=' . $exp->id) ); ?>"><?php esc_html_e('Edit', 'freelance-studio'); ?></a>
                                        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=expenses&action=duplicate&id=' . $exp->id) ); ?>"><?php esc_html_e('Duplicate', 'freelance-studio'); ?></a>
                                        <hr>
                                        <a href="#" class="fs-delete-btn text-danger" data-type="expense" data-id="<?php echo  intval( $exp->id ); ?>"><?php esc_html_e('Delete', 'freelance-studio'); ?></a>
                                    </div>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
    <?php endif; /* end recurring vs all */ ?>
    
    <?php
    // Pagination
    $base_url = admin_url('admin.php?page=fs-finances&tab=expenses');
    $pg_params = array();
    if (!empty($category_filter)) $pg_params['category'] = $category_filter;
    if (!empty($project_filter)) $pg_params['project_id'] = $project_filter;
    if (!empty($start_date)) $pg_params['start_date'] = $start_date;
    if (!empty($end_date)) $pg_params['end_date'] = $end_date;
    if ($per_page !== 25) $pg_params['per_page'] = $per_page;
    if (!empty($pg_params)) $base_url = add_query_arg($pg_params, $base_url);
    $item_label = __('expenses', 'freelance-studio');
    include JEEB_FS_PLUGIN_DIR . 'includes/views/partials/pagination.php';
    ?>
<?php if (empty($GLOBALS['fs_in_finances'])): ?>
</div>
<?php endif; ?>
