<?php
/**
 * Tasks List View - All Tasks Across All Projects
 *
 * @package Freelance_Studio
 */

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

// Get user's role setting for "Me" label
$my_role = get_option('fs_my_role', 'freelancer');
$role_labels = array(
    'freelancer' => __('Freelancer', 'freelance-studio'),
    'designer' => __('Designer', 'freelance-studio'),
    'developer' => __('Developer', 'freelance-studio'),
    'project_manager' => __('Project Manager', 'freelance-studio'),
    'consultant' => __('Consultant', 'freelance-studio'),
    'agency' => __('Agency', 'freelance-studio'),
);
$my_role_label = isset($role_labels[$my_role]) ? $role_labels[$my_role] : __('Freelancer', 'freelance-studio');

// Get filter values
$filter_status = isset($_GET['status']) ? sanitize_text_field($_GET['status']) : '';
$filter_assignee = isset($_GET['assignee']) ? sanitize_text_field($_GET['assignee']) : '';
$filter_project = isset($_GET['project_id']) ? intval($_GET['project_id']) : 0;
$filter_priority = isset($_GET['priority']) ? sanitize_text_field($_GET['priority']) : '';
$filter_task_type = isset($_GET['task_type']) ? sanitize_text_field($_GET['task_type']) : '';
$filter_client = isset($_GET['client_id']) ? intval($_GET['client_id']) : 0;

// Pagination - per_page is user-configurable (10, 25, or 50), defaults to 25
$per_page_options = array(10, 25, 50);
$per_page_saved = (int) get_user_meta(get_current_user_id(), 'fs_tasks_per_page', true);
$per_page = in_array($per_page_saved, $per_page_options, true) ? $per_page_saved : 25;
// Allow overriding via URL (from the per-page selector form)
if (isset($_GET['per_page']) && in_array((int) $_GET['per_page'], $per_page_options, true)) {
    $per_page = (int) $_GET['per_page'];
    if ($per_page !== $per_page_saved) {
        update_user_meta(get_current_user_id(), 'fs_tasks_per_page', $per_page);
    }
}
$current_page = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;

// Get persistent sort preference from user meta (falls back to URL params, then defaults)
$saved_sort_orderby = get_user_meta(get_current_user_id(), 'fs_task_sort_orderby', true);
$saved_sort_order = get_user_meta(get_current_user_id(), 'fs_task_sort_order', true);

$current_sort = isset($_GET['orderby']) ? sanitize_text_field($_GET['orderby']) : ($saved_sort_orderby ?: 'due_date');
$current_order = isset($_GET['order']) ? sanitize_text_field($_GET['order']) : ($saved_sort_order ?: 'ASC');
$current_tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'active';

// If sort came from URL (user clicked a header), persist it
if (isset($_GET['orderby'])) {
    $url_orderby = sanitize_text_field($_GET['orderby']);
    $url_order = isset($_GET['order']) ? sanitize_text_field($_GET['order']) : 'ASC';
    if ($url_orderby !== $saved_sort_orderby || $url_order !== $saved_sort_order) {
        update_user_meta(get_current_user_id(), 'fs_task_sort_orderby', $url_orderby);
        update_user_meta(get_current_user_id(), 'fs_task_sort_order', $url_order);
    }
}

// Get kanban column labels for status display
$saved_kanban_labels = get_option('fs_kanban_column_labels', array());
$kanban_status_labels = FS_View_Context::get_task_status_labels();
$kanban_status_colors = FS_View_Context::get_task_status_colors();

// Build query args - exclude tasks from archived projects
$args = array(
    'orderby' => $current_sort,
    'order' => $current_order,
    'exclude_archived_projects' => true,
    'smart_recurring' => true,
);

// Handle Active vs Archived tab
if ($current_tab === 'archived') {
    $args['status'] = 'archived';
} elseif ($current_tab !== 'recurring') {
    $args['exclude_archived'] = true;
    if ($filter_status) {
        $args['status'] = $filter_status;
    }
}

// Get archived count for tab badge
$archived_count_args = array(
    'status' => 'archived',
    'exclude_archived_projects' => true,
);
$archived_tasks_count = count(FS_Task::get_all($archived_count_args));

// Get recurring task templates count
$recurring_templates = array();
if ($current_tab === 'recurring') {
    global $wpdb;
    $tasks_table = $wpdb->prefix . 'fs_tasks';
    $projects_table = $wpdb->prefix . 'fs_projects';
    $clients_table = $wpdb->prefix . 'fs_clients';
    $recurring_templates = $wpdb->get_results("
        SELECT t.*, p.name as project_name, c.name as client_name, c.company_name as client_company
        FROM {$tasks_table} t
        LEFT JOIN {$projects_table} p ON t.project_id = p.id
        LEFT JOIN {$clients_table} c ON COALESCE(t.client_id, p.client_id) = c.id
        WHERE t.is_recurring = 1 AND t.parent_task_id IS NULL
        ORDER BY t.created_at DESC
    ");
}
$recurring_count = 0;
{
    global $wpdb;
    $tasks_table = $wpdb->prefix . 'fs_tasks';
    $recurring_count = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$tasks_table} WHERE is_recurring = 1 AND parent_task_id IS NULL");
}

// Only fetch tasks when not on recurring tab
$tasks = array();
$total_tasks = 0;
$completed_tasks = 0;
$my_tasks = 0;
$client_tasks = 0;
$overdue_tasks = 0;
$clients = array();

// Always fetch projects for the task modal (needed on all tabs)
$projects = FS_Project::get_all(array('status' => array('active', 'pending')));

if ($current_tab !== 'recurring') {
    if ($filter_project) {
        $args['project_id'] = $filter_project;
    }

    if ($filter_priority) {
        $args['priority'] = $filter_priority;
    }

    if ($filter_task_type) {
        $args['task_type'] = $filter_task_type;
    }

    if ($filter_client) {
        $args['client_id'] = $filter_client;
    }

    // Assignee filter requires PHP-level filtering (not in model), so fetch all then paginate
    if ($filter_assignee) {
        $all_tasks = FS_Task::get_all($args);
        $all_tasks = array_values(array_filter($all_tasks, function($task) use ($filter_assignee) {
            return ($task->assigned_to ?? 'freelancer') === $filter_assignee;
        }));
        $total_tasks_count = count($all_tasks);
        $tasks = array_slice($all_tasks, ($current_page - 1) * $per_page, $per_page);
    } else {
        $total_tasks_count = FS_Task::count_all($args);
        $args['limit']  = $per_page;
        $args['offset'] = ($current_page - 1) * $per_page;
        $tasks = FS_Task::get_all($args);
        $all_tasks = null; // not needed
    }

    $total_pages = max(1, ceil($total_tasks_count / $per_page));

    // Get all clients for filter dropdown
    $clients = FS_Client::get_all(array('status' => 'active'));

    // Stats: fetch unfiltered/unpaginated counts for stat cards (active tab only)
    $total_tasks     = $total_tasks_count;
    $completed_tasks = 0;
    $my_tasks        = 0;
    $client_tasks    = 0;
    $overdue_tasks   = 0;

    if ($current_tab === 'active') {
        // These stats need full result set — use count_all with targeted args
        $base_count_args = array(
            'exclude_archived_projects' => true,
            'smart_recurring'           => true,
            'exclude_archived'          => true,
        );
        $completed_tasks = FS_Task::count_all(array_merge($base_count_args, array('status' => 'completed')));
        $overdue_tasks_all = FS_Task::get_all(array_merge($base_count_args, array()));
        $overdue_tasks = count(array_filter($overdue_tasks_all, function($t) {
            return $t->due_date && strtotime($t->due_date) < time() && $t->status !== 'completed';
        }));
        $my_tasks = count(array_filter($overdue_tasks_all, function($t) {
            return ($t->assigned_to ?? 'freelancer') === 'freelancer' && $t->status !== 'completed';
        }));
        $client_tasks = count(array_filter($overdue_tasks_all, function($t) {
            return ($t->assigned_to ?? 'freelancer') === 'client' && $t->status !== 'completed';
        }));
    }
}

$priorities = FS_Task::get_priorities();
$statuses = FS_Task::get_statuses();
// These are set inside the fetch block below; defaults here are only used on the recurring tab
if (!isset($total_pages)) $total_pages = 1;
if (!isset($total_tasks_count)) $total_tasks_count = 0;
?>

<div class="wrap fs-wrap">
    <div class="fs-page-header">
        <h1 class="fs-page-title"><?php esc_html_e('Tasks', 'freelance-studio'); ?></h1>
        <div class="fs-view-toggle">
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-tasks&view=list') ); ?>" class="fs-btn fs-btn-primary" title="<?php esc_attr_e('List View', 'freelance-studio'); ?>">
                <span class="dashicons dashicons-list-view"></span>
            </a>
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-tasks&view=kanban') ); ?>" class="fs-btn fs-btn-secondary" title="<?php esc_attr_e('Kanban Board', 'freelance-studio'); ?>">
                <span class="dashicons dashicons-screenoptions"></span>
            </a>
        </div>
        <div style="flex:1;"></div>
        <button type="button" class="fs-btn fs-btn-primary" id="add-list-task-btn">
            <?php esc_html_e('New task', 'freelance-studio'); ?>
        </button>
    </div>
    
    <!-- Active/Archived/Recurring Tabs -->
    <div class="fs-tasks-tabs">
        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-tasks&view=list&tab=active') ); ?>" 
           class="fs-tasks-tab <?php echo $current_tab === 'active' ? 'active' : ''; ?>">
            <?php esc_html_e('Active', 'freelance-studio'); ?>
        </a>
        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-tasks&view=list&tab=archived') ); ?>" 
           class="fs-tasks-tab <?php echo $current_tab === 'archived' ? 'active' : ''; ?>">
            <?php esc_html_e('Archived', 'freelance-studio'); ?>
            <?php if ($archived_tasks_count > 0): ?>
                <span class="fs-tasks-tab-count"><?php echo  intval( $archived_tasks_count ); ?></span>
            <?php endif; ?>
        </a>
        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-tasks&view=list&tab=recurring') ); ?>" 
           class="fs-tasks-tab <?php echo $current_tab === 'recurring' ? 'active' : ''; ?>">
            <?php esc_html_e('Recurring', 'freelance-studio'); ?>
            <?php if ($recurring_count > 0): ?>
                <span class="fs-tasks-tab-count"><?php echo  intval( $recurring_count ); ?></span>
            <?php endif; ?>
        </a>
    </div>

    <?php if ($current_tab === 'archived' && $archived_tasks_count > 0): ?>
    <div class="fs-archived-actions">
        <button type="button" class="fs-btn fs-btn-danger fs-btn-small" id="fs-purge-archived-tasks">
            <span class="dashicons dashicons-trash"></span>
            <?php /* translators: 1. count/number */ ?>
            <?php echo wp_kses_post( sprintf( _n( 'Purge %d Archived Task', 'Purge All %d Archived Tasks', $archived_tasks_count, 'freelance-studio' ), $archived_tasks_count ) ); ?>
        </button>
        <span class="fs-archived-actions-hint"><?php esc_html_e('Permanently deletes all archived tasks. This cannot be undone.', 'freelance-studio'); ?></span>
    </div>
    <?php endif; ?>
    
    <?php if ($current_tab === 'active'): ?>
    <!-- Stats Cards -->
    <div class="fs-tasks-stats-row">
        <div class="fs-tasks-stat-card combined-tasks">
            <div class="fs-combined-stat-main">
                <span class="fs-tasks-stat-number"><?php echo  esc_html( $total_tasks - $completed_tasks ); ?></span>
                <span class="fs-tasks-stat-label"><?php esc_html_e('Open Tasks', 'freelance-studio'); ?></span>
            </div>
            <div class="fs-combined-stat-breakdown">
                <div class="fs-combined-stat-item my-tasks">
                    <span class="fs-combined-stat-value"><?php echo  esc_html( $my_tasks ); ?></span>
                    <span class="fs-combined-stat-label"><?php esc_html_e('My Tasks', 'freelance-studio'); ?></span>
                </div>
                <div class="fs-combined-stat-item client-tasks">
                    <span class="fs-combined-stat-value"><?php echo  esc_html( $client_tasks ); ?></span>
                    <span class="fs-combined-stat-label"><?php esc_html_e('Client Tasks', 'freelance-studio'); ?></span>
                </div>
            </div>
        </div>
        <?php if ($overdue_tasks > 0): ?>
        <div class="fs-tasks-stat-card overdue">
            <span class="fs-tasks-stat-number"><?php echo  esc_html( $overdue_tasks ); ?></span>
            <span class="fs-tasks-stat-label"><?php esc_html_e('Overdue', 'freelance-studio'); ?></span>
        </div>
        <?php endif; ?>
        <div class="fs-tasks-stat-card completed">
            <span class="fs-tasks-stat-number"><?php echo  esc_html( $completed_tasks ); ?></span>
            <span class="fs-tasks-stat-label"><?php esc_html_e('Completed', 'freelance-studio'); ?></span>
        </div>
    </div>
    <?php endif; ?>
    
    <?php if ($current_tab === 'recurring'): ?>
    <!-- Recurring Task Templates -->
    <?php
    $recurring_frequencies = FS_Task::get_recurring_frequencies();
    ?>
    <?php if (empty($recurring_templates)): ?>
        <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 tasks', 'freelance-studio'); ?></h3>
            <p><?php esc_html_e('Create a recurring task from any project\'s Tasks tab by enabling the "Recurring" option when adding a task.', 'freelance-studio'); ?></p>
        </div>
    <?php else: ?>
        <table class="wp-list-table widefat striped fs-table" style="table-layout: auto;">
            <thead>
                <tr>
                    <th class="column-title"><?php esc_html_e('Task', 'freelance-studio'); ?></th>
                    <th class="column-project"><?php esc_html_e('Project', 'freelance-studio'); ?></th>
                    <th class="column-frequency"><?php esc_html_e('Frequency', 'freelance-studio'); ?></th>
                    <th class="column-end-date"><?php esc_html_e('End Date', 'freelance-studio'); ?></th>
                    <th class="column-actions"></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($recurring_templates as $rtask): ?>
                <tr>
                    <td class="column-title">
                        <strong><?php echo esc_html($rtask->title); ?></strong>
                        <?php if (!empty($rtask->description)): ?>
                            <br><small class="fs-muted"><?php echo esc_html(wp_trim_words($rtask->description, 10)); ?></small>
                        <?php endif; ?>
                    </td>
                    <td class="column-project">
                        <?php if ($rtask->project_name): ?>
                            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-projects&action=view&id=' . $rtask->project_id . '&tab=tasks') ); ?>">
                                <?php echo esc_html($rtask->project_name); ?>
                            </a>
                            <?php if ($rtask->client_company || $rtask->client_name): ?>
                                <br><small class="fs-muted"><?php echo esc_html($rtask->client_company ?: $rtask->client_name); ?></small>
                            <?php endif; ?>
                        <?php else: ?>
                            <span class="fs-muted">—</span>
                        <?php endif; ?>
                    </td>
                    <td class="column-frequency">
                        <?php echo esc_html($recurring_frequencies[$rtask->recurring_frequency] ?? $rtask->recurring_frequency); ?>
                    </td>
                    <td class="column-end-date">
                        <?php if ($rtask->recurring_end_date): ?>
                            <?php echo  esc_html( FS_View_Context::format_date($rtask->recurring_end_date, 'm/d/y') ); ?>
                        <?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="#" class="edit-task-btn" data-id="<?php echo esc_attr($rtask->id); ?>"><?php esc_html_e('Edit', 'freelance-studio'); ?></a>
                                <?php if ($rtask->project_id): ?>
                                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-projects&action=view&id=' . $rtask->project_id . '&tab=tasks') ); ?>"><?php esc_html_e('View in Project', 'freelance-studio'); ?></a>
                                <?php endif; ?>
                                <hr>
                                <a href="#" class="delete-task-btn text-danger" data-id="<?php echo esc_attr($rtask->id); ?>"><?php esc_html_e('Delete', 'freelance-studio'); ?></a>
                            </div>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
    
    <?php else: ?>
    <!-- Filters -->
    <div class="fs-list-header">
        <form method="get" class="fs-filters-form">
            <input type="hidden" name="page" value="fs-tasks">
            <input type="hidden" name="view" value="list">
            <input type="hidden" name="tab" value="<?php echo esc_attr($current_tab); ?>">
            <input type="hidden" name="orderby" value="<?php echo esc_attr($current_sort); ?>">
            <input type="hidden" name="order" value="<?php echo esc_attr($current_order); ?>">
            <input type="hidden" name="paged" value="1">
            <input type="hidden" name="per_page" value="<?php echo esc_attr($per_page); ?>">
            
            <select name="task_type" class="fs-filter-select">
                <option value=""><?php esc_html_e('All Task Types', 'freelance-studio'); ?></option>
                <option value="project" <?php selected($filter_task_type, 'project'); ?>><?php esc_html_e('Project Tasks', 'freelance-studio'); ?></option>
                <option value="client" <?php selected($filter_task_type, 'client'); ?>><?php esc_html_e('Client Tasks', 'freelance-studio'); ?></option>
            </select>
            
            <select name="client_id" class="fs-filter-select">
                <option value=""><?php esc_html_e('All Clients', 'freelance-studio'); ?></option>
                <?php foreach ($clients as $client_option): ?>
                    <option value="<?php echo esc_attr($client_option->id); ?>" <?php selected($filter_client, $client_option->id); ?>>
                        <?php echo esc_html(FS_Client::get_display_name($client_option)); ?>
                        <?php if (!empty($client_option->is_internal)): ?> (<?php esc_html_e('Internal', 'freelance-studio'); ?>)<?php endif; ?>
                    </option>
                <?php endforeach; ?>
            </select>
            
            <select name="project_id" class="fs-filter-select">
                <option value=""><?php esc_html_e('All Projects', 'freelance-studio'); ?></option>
                <?php foreach ($projects as $project): ?>
                    <option value="<?php echo esc_attr($project->id); ?>" <?php selected($filter_project, $project->id); ?>>
                        <?php echo esc_html($project->name); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            
            <select name="status" class="fs-filter-select">
                <option value=""><?php esc_html_e('All Statuses', 'freelance-studio'); ?></option>
                <?php foreach ($kanban_status_labels as $key => $label): ?>
                    <option value="<?php echo esc_attr($key); ?>" <?php selected($filter_status, $key); ?>>
                        <?php echo esc_html($label); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            
            <select name="assignee" class="fs-filter-select">
                <option value=""><?php esc_html_e('All Assignees', 'freelance-studio'); ?></option>
                <option value="freelancer" <?php selected($filter_assignee, 'freelancer'); ?>><?php esc_html_e('My Tasks', 'freelance-studio'); ?></option>
                <option value="client" <?php selected($filter_assignee, 'client'); ?>><?php esc_html_e('Client Tasks', 'freelance-studio'); ?></option>
            </select>
            
            <select name="priority" class="fs-filter-select">
                <option value=""><?php esc_html_e('All Priorities', 'freelance-studio'); ?></option>
                <?php foreach ($priorities as $key => $label): ?>
                    <option value="<?php echo esc_attr($key); ?>" <?php selected($filter_priority, $key); ?>>
                        <?php echo esc_html($label); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            
            <button type="submit" class="button"><?php esc_html_e('Filter', 'freelance-studio'); ?></button>
            
            <?php if ($filter_status || $filter_assignee || $filter_project || $filter_priority || $filter_task_type || $filter_client): ?>
                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-tasks') ); ?>" class="button"><?php esc_html_e('Clear', 'freelance-studio'); ?></a>
            <?php endif; ?>
        </form>
    </div>
    
    <!-- Tasks Table -->
    <?php if (empty($tasks)): ?>
        <div class="fs-empty-state">
            <div class="fs-empty-state-icon">
                <span class="dashicons dashicons-<?php echo $current_tab === 'archived' ? 'archive' : 'yes-alt'; ?>"></span>
            </div>
            <?php if ($current_tab === 'archived'): ?>
                <h3><?php esc_html_e('No archived tasks', 'freelance-studio'); ?></h3>
                <p><?php esc_html_e('When you archive completed tasks from the Kanban board or task list, they\'ll appear here.', 'freelance-studio'); ?></p>
            <?php else: ?>
                <h3><?php esc_html_e('No tasks found', 'freelance-studio'); ?></h3>
                <p><?php esc_html_e('Tasks are created within projects. Go to a project and add tasks from the Tasks tab.', 'freelance-studio'); ?></p>
                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-projects') ); ?>" class="button button-primary"><?php esc_html_e('View Projects', 'freelance-studio'); ?></a>
            <?php endif; ?>
        </div>
    <?php else: ?>
        <table class="wp-list-table widefat striped fs-table fs-tasks-list-table" style="table-layout: auto;">
            <thead>
                <tr>
                    <th class="column-status" style="width: 40px;"></th>
                    <th class="column-title">
                        <a href="<?php echo esc_url(add_query_arg(array('orderby' => 'title', 'order' => ($current_sort === 'title' && $current_order === 'ASC') ? 'DESC' : 'ASC'))); ?>" class="fs-sortable-header <?php echo $current_sort === 'title' ? 'active' : ''; ?>">
                            <?php esc_html_e('Task', 'freelance-studio'); ?>
                            <span class="fs-sort-indicator"><?php echo $current_sort === 'title' ? ($current_order === 'DESC' ? '↓' : '↑') : '↕'; ?></span>
                        </a>
                    </th>
                    <th class="column-context">
                        <a href="<?php echo esc_url(add_query_arg(array('orderby' => 'client_name', 'order' => ($current_sort === 'client_name' && $current_order === 'ASC') ? 'DESC' : 'ASC'))); ?>" class="fs-sortable-header <?php echo $current_sort === 'client_name' ? 'active' : ''; ?>">
                            <?php esc_html_e('Project / Client', 'freelance-studio'); ?>
                            <span class="fs-sort-indicator"><?php echo $current_sort === 'client_name' ? ($current_order === 'DESC' ? '↓' : '↑') : '↕'; ?></span>
                        </a>
                    </th>
                    <th class="column-assignee" style="white-space: nowrap;"><?php esc_html_e('Assigned To', 'freelance-studio'); ?></th>
                    <th class="column-priority" style="white-space: nowrap;">
                        <a href="<?php echo esc_url(add_query_arg(array('orderby' => 'priority', 'order' => ($current_sort === 'priority' && $current_order === 'DESC') ? 'ASC' : 'DESC'))); ?>" class="fs-sortable-header <?php echo $current_sort === 'priority' ? 'active' : ''; ?>">
                            <?php esc_html_e('Priority', 'freelance-studio'); ?>
                            <span class="fs-sort-indicator"><?php echo $current_sort === 'priority' ? ($current_order === 'DESC' ? '↓' : '↑') : '↕'; ?></span>
                        </a>
                    </th>
                    <th class="column-kanban-status" style="white-space: nowrap;">
                        <a href="<?php echo esc_url(add_query_arg(array('orderby' => 'status', 'order' => ($current_sort === 'status' && $current_order === 'ASC') ? 'DESC' : 'ASC'))); ?>" class="fs-sortable-header <?php echo $current_sort === 'status' ? 'active' : ''; ?>">
                            <?php esc_html_e('Status', 'freelance-studio'); ?>
                            <span class="fs-sort-indicator"><?php echo $current_sort === 'status' ? ($current_order === 'DESC' ? '↓' : '↑') : '↕'; ?></span>
                        </a>
                    </th>
                    <th class="column-due" style="white-space: nowrap;">
                        <a href="<?php echo esc_url(add_query_arg(array('orderby' => 'due_date', 'order' => ($current_sort === 'due_date' && $current_order === 'ASC') ? 'DESC' : 'ASC'))); ?>" class="fs-sortable-header <?php echo $current_sort === 'due_date' ? 'active' : ''; ?>">
                            <?php esc_html_e('Due Date', 'freelance-studio'); ?>
                            <span class="fs-sort-indicator"><?php echo $current_sort === 'due_date' ? ($current_order === 'DESC' ? '↓' : '↑') : '↕'; ?></span>
                        </a>
                    </th>
                    <th class="column-actions" style="width: 60px;"></th>
                </tr>
            </thead>
            <tbody>
                <?php 
                $priority_colors = array(
                    'low' => '#6b7280',
                    'medium' => '#f59e0b',
                    'high' => '#f97316',
                    'urgent' => '#ef4444',
                );
                
                foreach ($tasks as $task): 
                    $is_completed = $task->status === 'completed';
                    $is_overdue = $task->due_date && strtotime($task->due_date) < time() && !$is_completed;
                    $is_client_task = ($task->assigned_to ?? 'freelancer') === 'client';
                    $priority_color = $priority_colors[$task->priority] ?? '#6b7280';
                    $is_client_level_task = empty($task->project_id) && !empty($task->client_id);
                    $client_display_name = !empty($task->client_company_name) ? $task->client_company_name : $task->client_name;
                    $is_internal_task = !empty($task->client_is_internal);
                ?>
                <tr class="<?php echo $is_completed ? 'task-completed' : ''; ?> <?php echo $is_overdue ? 'task-overdue' : ''; ?>">
                    <td class="column-status">
                        <label class="fs-task-checkbox-wrapper">
                            <input type="checkbox" 
                                   class="fs-task-toggle" 
                                   data-id="<?php echo esc_attr($task->id); ?>" 
                                   <?php checked($is_completed); ?>>
                            <span class="fs-task-checkbox-custom"></span>
                        </label>
                    </td>
                    <td class="column-title">
                        <div class="fs-task-title-cell">
                            <span class="fs-task-title <?php echo $is_completed ? 'completed' : ''; ?>">
                                <?php echo esc_html($task->title); ?>
                            </span>
                            <?php if (!empty($task->is_non_billable)): ?>
                                <span class="fs-non-billable-badge"><?php esc_html_e('Non-billable', 'freelance-studio'); ?></span>
                            <?php endif; ?>
                            <?php if ($task->description): ?>
                                <span class="fs-task-description"><?php echo esc_html(wp_trim_words($task->description, 10)); ?></span>
                            <?php endif; ?>
                        </div>
                    </td>
                    <td class="column-context">
                        <?php if (!empty($task->project_id) && !empty($task->project_name)): ?>
                            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-projects&action=view&id=' . $task->project_id . '&tab=tasks') ); ?>">
                                <?php echo esc_html($task->project_name); ?>
                            </a>
                            <?php if ($client_display_name): ?>
                                <span class="fs-task-client-subtext"><?php echo esc_html($client_display_name); ?></span>
                            <?php endif; ?>
                        <?php elseif ($is_client_level_task): ?>
                            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-clients&action=view&id=' . $task->client_id . '&tab=tasks') ); ?>">
                                <?php echo esc_html($client_display_name); ?>
                                <?php if ($is_internal_task): ?>
                                    <span class="fs-internal-badge"><?php esc_html_e('Internal', 'freelance-studio'); ?></span>
                                <?php endif; ?>
                            </a>
                            <span class="fs-task-client-subtext"><?php esc_html_e('Client Task', 'freelance-studio'); ?></span>
                        <?php else: ?>
                            <span class="fs-internal-badge"><?php esc_html_e('Internal', 'freelance-studio'); ?></span>
                        <?php endif; ?>
                    </td>
                    <td class="column-assignee">
                        <span class="fs-assignee-badge <?php echo $is_client_task ? 'client' : 'designer'; ?>">
                            <span class="dashicons <?php echo $is_client_task ? 'dashicons-businessperson' : 'dashicons-admin-users'; ?>"></span>
                            <?php echo  esc_html( $is_client_task ? __('Client', 'freelance-studio') : __('Me', 'freelance-studio') ); ?>
                        </span>
                    </td>
                    <td class="column-priority">
                        <span class="fs-priority-badge" style="background-color: <?php echo  esc_attr( $priority_color ); ?>15; color: <?php echo  esc_attr( $priority_color ); ?>;">
                            <?php echo esc_html($priorities[$task->priority] ?? $task->priority); ?>
                        </span>
                    </td>
                    <td class="column-kanban-status">
                        <?php if ($current_tab === 'archived'): ?>
                            <?php 
                            $status_label = $kanban_status_labels[$task->status] ?? ucfirst(str_replace('_', ' ', $task->status));
                            $status_color = $kanban_status_colors[$task->status] ?? '#6b7280';
                            ?>
                            <span class="fs-kanban-status-badge" style="background-color: <?php echo  esc_attr( $status_color ); ?>15; color: <?php echo  esc_attr( $status_color ); ?>; border: 1px solid <?php echo  esc_attr( $status_color ); ?>30;">
                                <?php echo esc_html($status_label); ?>
                            </span>
                        <?php else: ?>
                            <select class="fs-inline-status-select fs-task-status-select fs-dashboard-task-status task-status-<?php echo esc_attr($task->status); ?>" 
                                    data-task-id="<?php echo esc_attr($task->id); ?>" 
                                    data-original="<?php echo esc_attr($task->status); ?>">
                                <?php 
                                // Show relevant statuses (exclude archived - that's done via menu)
                                $inline_statuses = array_diff_key($kanban_status_labels, array('archived' => 1, 'cancelled' => 1));
                                foreach ($inline_statuses as $skey => $slabel): ?>
                                    <option value="<?php echo esc_attr($skey); ?>" <?php selected($task->status, $skey); ?>>
                                        <?php echo esc_html($slabel); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        <?php endif; ?>
                    </td>
                    <td class="column-due">
                        <?php if ($task->due_date): ?>
                            <span class="fs-due-date <?php echo $is_overdue ? 'overdue' : ''; ?>">
                                <?php if ($is_overdue): ?>
                                    <span class="dashicons dashicons-warning"></span>
                                <?php endif; ?>
                                <?php echo esc_html(gmdate('M j, Y', strtotime($task->due_date))); ?>
                            </span>
                        <?php else: ?>
                            <span class="fs-no-date">—</span>
                        <?php endif; ?>
                    </td>
                    <td class="column-actions">
                        <?php if ($current_tab === 'archived'): ?>
                            <button type="button" class="fs-btn fs-btn-primary fs-btn-small restore-task-btn" 
                                    data-id="<?php echo esc_attr($task->id); ?>"
                                    title="<?php esc_attr_e('Restore Task', 'freelance-studio'); ?>">
                                <?php esc_html_e('Restore', 'freelance-studio'); ?>
                            </button>
                            <div class="fs-row-menu">
                                <button type="button" class="fs-row-menu-trigger">⋯</button>
                                <div class="fs-row-menu-dropdown">
                                    <a href="#" class="delete-task-btn" data-id="<?php echo esc_attr($task->id); ?>"><?php esc_html_e('Delete Permanently', 'freelance-studio'); ?></a>
                                </div>
                            </div>
                        <?php else: ?>
                        <?php if ($task->status === 'requested'): ?>
                            <button type="button" class="fs-btn fs-btn-primary fs-btn-small accept-task-request" 
                                    data-id="<?php echo esc_attr($task->id); ?>"
                                    title="<?php esc_attr_e('Accept Request', 'freelance-studio'); ?>">
                                <?php esc_html_e('Accept', 'freelance-studio'); ?>
                            </button>
                        <?php elseif (!$is_completed): ?>
                            <?php if ( ! function_exists( 'fs_studio_is_free_plan' ) || ! fs_studio_is_free_plan() ): ?>
                            <button type="button" class="fs-task-start-timer" 
                                    data-task-id="<?php echo esc_attr($task->id); ?>"
                                    data-project-id="<?php echo esc_attr($task->project_id); ?>"
                                    data-task-name="<?php echo esc_attr($task->title); ?>"
                                    title="<?php esc_attr_e('Start Timer', 'freelance-studio'); ?>">
                                <span class="dashicons dashicons-clock"></span>
                            </button>
                            <?php endif; ?>
                        <?php endif; ?>
                        <div class="fs-row-menu">
                            <button type="button" class="fs-row-menu-trigger">⋯</button>
                            <div class="fs-row-menu-dropdown">
                                <a href="#" class="edit-task-btn" data-id="<?php echo esc_attr($task->id); ?>"><?php esc_html_e('Edit', 'freelance-studio'); ?></a>
                                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-projects&action=view&id=' . $task->project_id . '&tab=tasks') ); ?>"><?php esc_html_e('View in Project', 'freelance-studio'); ?></a>
                                <a href="#" class="archive-task-btn" data-id="<?php echo esc_attr($task->id); ?>"><?php esc_html_e('Archive', 'freelance-studio'); ?></a>
                            </div>
                        </div>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        
        <!-- Mobile Task Cards (matches dashboard design) -->
        <div class="fs-task-mobile-list" style="display:none;">
            <?php foreach ($tasks as $task): 
                $is_completed = $task->status === 'completed';
                $is_overdue = $task->due_date && strtotime($task->due_date) < time() && !$is_completed;
                $is_client_task = ($task->assigned_to ?? 'freelancer') === 'client';
                $priority_color = $priority_colors[$task->priority] ?? '#6b7280';
                $client_display_name = !empty($task->client_company_name) ? $task->client_company_name : $task->client_name;
            ?>
            <div class="fs-task-mobile-item" data-task-id="<?php echo esc_attr($task->id); ?>">
                <label class="fs-task-checkbox-wrapper">
                    <input type="checkbox" class="fs-task-toggle" data-id="<?php echo esc_attr($task->id); ?>" <?php checked($is_completed); ?>>
                    <span class="fs-task-checkbox-custom"></span>
                </label>
                <div class="fs-task-mobile-info">
                    <div class="fs-task-mobile-title <?php echo $is_completed ? 'completed' : ''; ?>"><?php echo esc_html($task->title); ?></div>
                    <div class="fs-task-mobile-meta">
                        <?php if (!empty($task->project_name)): ?>
                            <span><?php echo esc_html($task->project_name); ?></span>
                        <?php elseif ($client_display_name): ?>
                            <span><?php echo esc_html($client_display_name); ?></span>
                        <?php endif; ?>
                        <span class="fs-priority-badge" style="background-color: <?php echo  esc_attr( $priority_color ); ?>15; color: <?php echo  esc_attr( $priority_color ); ?>; font-size:10px; padding:1px 6px;">
                            <?php echo esc_html($priorities[$task->priority] ?? $task->priority); ?>
                        </span>
                        <?php if ($task->due_date): ?>
                            <span class="<?php echo  esc_attr( $is_overdue ? 'overdue' : '' ); ?>"><?php echo  esc_attr( gmdate('M j', strtotime($task->due_date)) ); ?></span>
                        <?php endif; ?>
                        <?php if ($is_overdue): ?>
                            <span class="fs-status-badge status-overdue" style="font-size:9px; padding:2px 6px;"><?php esc_html_e('Overdue', 'freelance-studio'); ?></span>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="fs-task-mobile-actions">
                    <?php if ($current_tab === 'archived'): ?>
                        <button type="button" class="fs-btn fs-btn-primary fs-btn-small restore-task-btn" data-id="<?php echo esc_attr($task->id); ?>">
                            <?php esc_html_e('Restore', 'freelance-studio'); ?>
                        </button>
                    <?php elseif (!$is_completed && !empty($task->project_id)): ?>
                        <?php if ( ! function_exists( 'fs_studio_is_free_plan' ) || ! fs_studio_is_free_plan() ): ?>
                        <button type="button" class="fs-task-start-timer" 
                                data-task-id="<?php echo esc_attr($task->id); ?>"
                                data-project-id="<?php echo esc_attr($task->project_id); ?>"
                                data-task-name="<?php echo esc_attr($task->title); ?>">
                            <span class="dashicons dashicons-clock" style="font-size:16px; width:16px; height:16px; color:var(--fs-gray-400);"></span>
                        </button>
                        <?php endif; ?>
                    <?php endif; ?>
                    <div class="fs-row-menu">
                        <button type="button" class="fs-row-menu-trigger">⋯</button>
                        <div class="fs-row-menu-dropdown">
                            <a href="#" class="edit-task-btn" data-id="<?php echo esc_attr($task->id); ?>"><?php esc_html_e('Edit', 'freelance-studio'); ?></a>
                            <?php if (!empty($task->project_id)): ?>
                                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-projects&action=view&id=' . $task->project_id . '&tab=tasks') ); ?>"><?php esc_html_e('View in Project', 'freelance-studio'); ?></a>
                            <?php endif; ?>
                            <?php if ($current_tab !== 'archived'): ?>
                                <a href="#" class="archive-task-btn" data-id="<?php echo esc_attr($task->id); ?>"><?php esc_html_e('Archive', 'freelance-studio'); ?></a>
                            <?php else: ?>
                                <a href="#" class="delete-task-btn text-danger" data-id="<?php echo esc_attr($task->id); ?>"><?php esc_html_e('Delete', 'freelance-studio'); ?></a>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>

        <?php if ($total_pages > 1 || $total_tasks_count > 10): ?>
        <div class="fs-pagination">
            <div class="fs-pagination-info">
                <?php if ($total_tasks_count > 0): ?>
                <?php
                $start = ($current_page - 1) * $per_page + 1;
                $end   = min($current_page * $per_page, $total_tasks_count);
                printf( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                    /* translators: 1. showing value, 2. – value, 3. of value */
                    esc_html__('Showing %1$s–%2$s of %3$s tasks', 'freelance-studio'),
                    number_format_i18n($start), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                    number_format_i18n($end), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                    number_format_i18n($total_tasks_count) // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                );
                ?>
                <?php endif; ?>
            </div>
            <div class="fs-pagination-links">
                <?php
                $base_url = add_query_arg(array_filter(array(
                    'page'       => 'fs-tasks',
                    'view'       => 'list',
                    'tab'        => $current_tab,
                    'orderby'    => $current_sort,
                    'order'      => $current_order,
                    'per_page'   => $per_page,
                    'status'     => $filter_status,
                    'assignee'   => $filter_assignee,
                    'project_id' => $filter_project ?: '',
                    'priority'   => $filter_priority,
                    'task_type'  => $filter_task_type,
                    'client_id'  => $filter_client ?: '',
                )), admin_url('admin.php'));

                if ($total_pages > 1):
                    if ($current_page > 1):
                        $prev_url = add_query_arg('paged', $current_page - 1, $base_url);
                        echo '<a href="' . esc_url($prev_url) . '" class="fs-pagination-link"><span class="dashicons dashicons-arrow-left-alt2" style="font-size:14px;width:14px;height:14px;line-height:1;"></span></a>';
                    endif;

                    $window = 2;
                    $last_printed = 0;
                    for ($p = 1; $p <= $total_pages; $p++):
                        $in_window = ($p === 1 || $p === $total_pages || ($p >= $current_page - $window && $p <= $current_page + $window));
                        if ($in_window):
                            if ($last_printed && $p > $last_printed + 1):
                                echo '<span class="fs-pagination-info" style="padding:0 4px;">…</span>';
                            endif;
                            if ($p === $current_page):
                                echo wp_kses_post( '<span class="fs-pagination-current">' . $p . '</span>' );                            else:
                                $page_url = add_query_arg('paged', $p, $base_url);
                                echo wp_kses_post( '<a href="' . esc_url($page_url) . '" class="fs-pagination-link">' . $p . '</a>' );
                            endif;
                            $last_printed = $p;
                        endif;
                    endfor;

                    if ($current_page < $total_pages):
                        $next_url = add_query_arg('paged', $current_page + 1, $base_url);
                        echo '<a href="' . esc_url($next_url) . '" class="fs-pagination-link"><span class="dashicons dashicons-arrow-right-alt2" style="font-size:14px;width:14px;height:14px;line-height:1;"></span></a>';
                    endif;
                endif;
                ?>
            </div>
            <div class="fs-pagination-perpage">
                <?php foreach ($per_page_options as $opt):
                    $pp_url = add_query_arg(array('per_page' => $opt, 'paged' => 1), $base_url);
                ?>
                <a href="<?php echo esc_url($pp_url); ?>" class="fs-pagination-link <?php echo $per_page === $opt ? 'fs-pagination-current' : ''; ?>">
                    <?php echo  esc_html( $opt ); ?>
                </a>
                <?php endforeach; ?>
                <span class="fs-pagination-info" style="margin-left:4px;"><?php esc_html_e('per page', 'freelance-studio'); ?></span>
            </div>
        </div>
        <?php endif; ?>

    <?php endif; ?>
    <?php endif; /* end recurring vs active/archived */ ?>
</div>
<script>
window.fsTaskModal = {
    nonce: '<?php echo esc_attr( wp_create_nonce("fs_ajax_nonce") ); ?>',
    context: 'kanban',
    strings: {
        addTask: '<?php echo esc_js(__("Add Task", "freelance-studio")); ?>',
        editTask: '<?php echo esc_js(__("Edit Task", "freelance-studio")); ?>',
        createTask: '<?php echo esc_js(__("Add Task", "freelance-studio")); ?>',
        updateTask: '<?php echo esc_js(__("Update Task", "freelance-studio")); ?>',
        errorLoading: '<?php echo esc_js(__("Error loading task", "freelance-studio")); ?>',
        errorSaving: '<?php echo esc_js(__("Error saving task", "freelance-studio")); ?>',
        saving: '<?php echo esc_js(__("Saving...", "freelance-studio")); ?>'
    }
};
</script>

<script>
jQuery(document).ready(function($) {
    var ajaxNonce = '<?php echo esc_attr( wp_create_nonce("fs_ajax_nonce") ); ?>';
    
    // Inline task status change
    $(document).on('change', '.fs-task-status-select', function() {
        var $select = $(this);
        var taskId = $select.data('task-id');
        var newStatus = $select.val();
        var originalStatus = $select.data('original');
        
        $select.prop('disabled', true);
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_update_task_status',
                task_id: taskId,
                status: newStatus,
                nonce: ajaxNonce
            },
            success: function(response) {
                if (response.success) {
                    $select.data('original', newStatus);
                    $select.removeClass('task-status-' + originalStatus).addClass('task-status-' + newStatus);
                    $select.addClass('fs-status-updated');
                    setTimeout(function() {
                        $select.removeClass('fs-status-updated');
                    }, 1500);
                    
                    // If marked completed, update the row visually
                    var $row = $select.closest('tr');
                    if (newStatus === 'completed') {
                        $row.addClass('task-completed');
                        $row.find('.fs-task-checkbox-wrapper input').prop('checked', true);
                        $row.find('.fs-task-title').addClass('completed');
                    } else {
                        $row.removeClass('task-completed');
                        $row.find('.fs-task-checkbox-wrapper input').prop('checked', false);
                        $row.find('.fs-task-title').removeClass('completed');
                    }
                } else {
                    alert(response.data || '<?php echo esc_js(__("Error updating task status", "freelance-studio")); ?>');
                    $select.val(originalStatus);
                }
                $select.prop('disabled', false);
            },
            error: function() {
                alert('<?php echo esc_js(__("Error updating task status", "freelance-studio")); ?>');
                $select.val(originalStatus);
                $select.prop('disabled', false);
            }
        });
    });
    
    // Wire add task button to shared modal
    $('#add-list-task-btn').on('click', function() {
        openTaskModal();
    });
    
    // Purge all archived tasks
    $('#fs-purge-archived-tasks').on('click', function() {
        if (!confirm('<?php echo esc_js(__('Permanently delete ALL archived tasks? This cannot be undone.', 'freelance-studio')); ?>')) return;

        var $btn = $(this).prop('disabled', true).text('<?php echo esc_js(__('Deleting...', 'freelance-studio')); ?>');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: { action: 'fs_purge_archived_tasks', nonce: ajaxNonce },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert(response.data || '<?php echo esc_js(__('Error purging tasks', 'freelance-studio')); ?>');
                    $btn.prop('disabled', false);
                }
            },
            error: function() {
                alert('<?php echo esc_js(__('Error purging tasks', 'freelance-studio')); ?>');
                $btn.prop('disabled', false);
            }
        });
    });

    // Archive task from list
    $(document).on('click', '.archive-task-btn', function(e) {
        e.preventDefault();
        var taskId = $(this).data('id');
        var $row = $(this).closest('tr');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: { action: 'fs_archive_task', nonce: ajaxNonce, id: taskId },
            success: function(response) {
                if (response.success) {
                    $row.fadeOut(200, function() { location.reload(); });
                } else {
                    alert(response.data || '<?php echo esc_js(__("Error archiving task", "freelance-studio")); ?>');
                }
            }
        });
    });
    
    // Restore task from archived list
    $(document).on('click', '.restore-task-btn', function(e) {
        e.preventDefault();
        var taskId = $(this).data('id');
        var $row = $(this).closest('tr');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: { action: 'fs_restore_task', nonce: ajaxNonce, id: taskId },
            success: function(response) {
                if (response.success) {
                    $row.fadeOut(200, function() { location.reload(); });
                } else {
                    alert(response.data || '<?php echo esc_js(__("Error restoring task", "freelance-studio")); ?>');
                }
            }
        });
    });
    
    // Delete task permanently from archived list
    $(document).on('click', '.delete-task-btn', function(e) {
        e.preventDefault();
        if (!confirm('<?php echo esc_js(__("Permanently delete this task? This cannot be undone.", "freelance-studio")); ?>')) return;
        
        var taskId = $(this).data('id');
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: { action: 'fs_delete_task', nonce: ajaxNonce, id: taskId },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert(response.data || '<?php echo esc_js(__("Error deleting task", "freelance-studio")); ?>');
                }
            }
        });
    });
});
</script>

<!-- Task Modal (shared partial) -->
<?php
$task_modal_context = 'kanban';
$task_modal_projects = $projects;
include JEEB_FS_PLUGIN_DIR . 'includes/views/partials/task-modal.php';
?>
