<?php
/**
 * Projects List View
 *
 * @package Freelance_Studio
 */

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

$messages = array(
    'created' => __('Project created successfully.', 'freelance-studio'),
    'updated' => __('Project updated successfully.', 'freelance-studio'),
    'deleted' => __('Project deleted successfully.', 'freelance-studio'),
    'not_found' => __('Project not found.', 'freelance-studio'),
    'archived' => __('Project archived successfully.', 'freelance-studio'),
    'unarchived' => __('Project restored from archive.', 'freelance-studio'),
);

// Get invoiced amounts for each project
function get_project_invoiced_amount($project_id) {
    global $wpdb;
    $invoices_table = $wpdb->prefix . 'fs_invoices';
    $junction_table = $wpdb->prefix . 'fs_invoice_projects';
    
    // Check junction table first (multi-project invoices store per-project subtotals here)
    $junction_exists = $wpdb->get_var("SHOW TABLES LIKE '{$junction_table}'");
    
    if ($junction_exists) {
        // Get all invoice IDs linked to this project (via junction table OR direct project_id)
        // Use junction subtotals where available for accurate per-project amounts
        $amount = (float) $wpdb->get_var($wpdb->prepare(
            "SELECT COALESCE(SUM(i.total), 0) FROM {$invoices_table} i
             WHERE i.project_id = %d AND i.status != 'cancelled'
             AND i.id NOT IN (SELECT DISTINCT invoice_id FROM {$junction_table})",
            $project_id
        ));
        
        // Add amounts from junction table (multi-project invoices)
        // For multi-project invoices, we use the junction subtotal proportionally
        $junction_amount = (float) $wpdb->get_var($wpdb->prepare(
            "SELECT COALESCE(SUM(
                CASE 
                    WHEN i.total = i.subtotal THEN jp.subtotal
                    WHEN i.subtotal > 0 THEN jp.subtotal * (i.total / i.subtotal)
                    ELSE jp.subtotal
                END
            ), 0)
            FROM {$junction_table} jp
            JOIN {$invoices_table} i ON jp.invoice_id = i.id
            WHERE jp.project_id = %d AND i.status != 'cancelled'",
            $project_id
        ));
        
        return $amount + $junction_amount;
    }
    
    // Fallback if junction table doesn't exist yet
    return (float) $wpdb->get_var($wpdb->prepare(
        "SELECT COALESCE(SUM(total), 0) FROM {$invoices_table} WHERE project_id = %d AND status != 'cancelled'",
        $project_id
    ));
}

// Avatar color helper for project cards
if (!function_exists('fs_get_avatar_color')) {
    function fs_get_avatar_color($string) {
        $colors = array('#1FBBA6','#81A5DF','#FFA26E','#7B68A6','#D2E768','#E85A5A','#5D4E80','#77D5C9');
        $hash = crc32($string ?: '');
        return $colors[abs($hash) % count($colors)];
    }
}

// Get current filter/sort values
$current_status = isset($_GET['status']) ? sanitize_text_field($_GET['status']) : '';
$current_client = isset($_GET['client_id']) ? intval($_GET['client_id']) : 0;
$current_billing = isset($_GET['billing_type']) ? sanitize_text_field($_GET['billing_type']) : '';
$current_sort = isset($_GET['orderby']) ? sanitize_text_field($_GET['orderby']) : 'start_date';
$current_order = isset($_GET['order']) ? sanitize_text_field($_GET['order']) : 'DESC';
$current_tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'active';

$has_filters = $current_status || $current_client || $current_billing;
?>

<div class="wrap fs-wrap">
    <div class="fs-page-header">
        <h1 class="fs-page-title"><?php esc_html_e('Projects', 'freelance-studio'); ?></h1>
        <div style="flex:1;"></div>
        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-projects&action=add') ); ?>" class="fs-btn fs-btn-primary">
            <?php esc_html_e('New project', 'freelance-studio'); ?>
        </a>
    </div>

    <!-- Tab Navigation -->
    <div class="fs-tab-nav">
        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-projects') ); ?>" class="fs-tab <?php echo esc_attr( $current_tab === 'active' ? 'active' : '' ); ?>">
            <?php esc_html_e('Active', 'freelance-studio'); ?>
            <span class="fs-tab-count"><?php echo  esc_html( isset($active_count) ? $active_count : 0 ); ?></span>
        </a>
        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-projects&tab=archived') ); ?>" class="fs-tab <?php echo esc_attr( $current_tab === 'archived' ? 'active' : '' ); ?>">
            <?php esc_html_e('Archived', 'freelance-studio'); ?>
            <span class="fs-tab-count"><?php echo  esc_html( isset($archived_count) ? $archived_count : 0 ); ?></span>
        </a>
    </div>

    <?php
    // Show free plan limit note for projects
    if ( function_exists( 'fs_studio_is_free_plan' ) && fs_studio_is_free_plan() ):
        $limits = fs_studio_free_limits();
    ?>
        <div class="fs-usage-counter">
            <span class="fs-usage-counter-text">
                <?php /* translators: 1. count/number */ ?>
                <?php echo esc_html( sprintf( __(  'Free plan: %d active project per client', 'freelance-studio' ), $limits['projects_per_client'] ) ); ?>
            </span>
            <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; ?>

    <div class="fs-list-header">
        <div class="fs-header-filters">
            <button type="button" class="fs-filter-toggle <?php echo $has_filters ? 'has-filters' : ''; ?>">
                <?php esc_html_e('Filter', 'freelance-studio'); ?>
                <?php if ($has_filters): ?><span class="fs-filter-count">●</span><?php endif; ?>
            </button>
            <div class="fs-sort-dropdown">
                <button type="button" class="fs-sort-trigger"><?php esc_html_e('Sort', 'freelance-studio'); ?> ▾</button>
                <div class="fs-sort-menu">
                    <?php
                    $sort_options = array(
                        'start_date' => __('Start Date', 'freelance-studio'),
                        'due_date' => __('Due Date', 'freelance-studio'),
                        'name' => __('Name', 'freelance-studio'),
                        'created_at' => __('Date Created', 'freelance-studio'),
                    );
                    foreach ($sort_options as $key => $label):
                        $is_active = $current_sort === $key;
                        $new_order = ($is_active && $current_order === 'DESC') ? 'ASC' : 'DESC';
                        $url = add_query_arg(array('orderby' => $key, 'order' => $new_order));
                    ?>
                        <a href="<?php echo esc_url($url); ?>" class="<?php echo $is_active ? 'active' : ''; ?>">
                            <?php echo esc_html($label); ?>
                            <?php if ($is_active): ?>
                                <span class="fs-sort-dir"><?php echo $current_order === 'DESC' ? '↓' : '↑'; ?></span>
                            <?php endif; ?>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
    
    <?php if ($message && isset($messages[$message])): ?>
        <div class="fs-notice <?php echo in_array($message, array('not_found', 'error')) ? 'error' : 'success'; ?>">
            <?php echo esc_html($messages[$message]); ?>
        </div>
    <?php endif; ?>
    
    <!-- Filter Panel -->
    <div class="fs-filters fs-filter-panel" <?php echo $has_filters ? '' : 'style="display:none;"'; ?>>
        <form method="get" action="">
            <input type="hidden" name="page" value="fs-projects">
            
            <select name="status" class="fs-filter-select">
                <option value=""><?php esc_html_e('All Statuses', 'freelance-studio'); ?></option>
                <?php foreach ($statuses as $key => $label): ?>
                    <option value="<?php echo esc_attr($key); ?>" <?php selected($current_status, $key); ?>>
                        <?php echo esc_html($label); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            
            <select name="client_id" class="fs-filter-select">
                <option value=""><?php esc_html_e('All Clients', 'freelance-studio'); ?></option>
                <?php foreach ($clients as $c): ?>
                    <option value="<?php echo esc_attr($c->id); ?>" <?php selected($current_client, $c->id); ?>>
                        <?php echo esc_html($c->company_name ?: $c->name); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            
            <select name="billing_type" class="fs-filter-select">
                <option value=""><?php esc_html_e('All Billing Types', 'freelance-studio'); ?></option>
                <?php 
                $billing_types = FS_Project::get_billing_types();
                foreach ($billing_types as $key => $label): ?>
                    <option value="<?php echo esc_attr($key); ?>" <?php selected($current_billing, $key); ?>>
                        <?php echo esc_html($label); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            
            <button type="submit" class="button"><?php esc_html_e('Apply', 'freelance-studio'); ?></button>
            
            <?php if ($has_filters): ?>
                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-projects') ); ?>" class="button"><?php esc_html_e('Clear', 'freelance-studio'); ?></a>
            <?php endif; ?>
        </form>
    </div>
    
    <?php if (empty($projects)): ?>
        <div class="fs-empty-state">
            <div class="fs-empty-state-icon">📁</div>
            <h3><?php esc_html_e('No projects yet', 'freelance-studio'); ?></h3>
            <p><?php esc_html_e('Create your first project to start tracking work.', 'freelance-studio'); ?></p>
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-projects&action=add') ); ?>" class="button button-primary">
                <?php esc_html_e('New project', 'freelance-studio'); ?>
            </a>
        </div>
    <?php else: ?>
        
        <!-- Mobile Card View -->
        <div class="fs-projects-grid fs-mobile-only">
            <?php foreach ($projects as $project): 
                $invoiced_amount = get_project_invoiced_amount($project->id);
                $client_logo_url = '';
                if (!empty($project->client_logo_id)) {
                    $client_logo_url = wp_get_attachment_image_url($project->client_logo_id, 'thumbnail');
                }
                if (empty($client_logo_url) && !empty($project->client_logo_url)) {
                    $client_logo_url = $project->client_logo_url;
                }
                $client_display = $project->client_company ?: $project->client_name ?: '';
            ?>
                <div class="fs-project-card">
                    <div class="fs-project-card-header">
                        <?php if ($client_logo_url): ?>
                            <div class="fs-client-avatar fs-client-avatar-logo fs-avatar-sm">
                                <img src="<?php echo esc_url($client_logo_url); ?>" alt="">
                            </div>
                        <?php else: ?>
                            <div class="fs-client-avatar fs-avatar-sm" style="background-color: <?php echo esc_attr(fs_get_avatar_color($client_display ?: $project->name)); ?>;">
                                <span class="dashicons dashicons-portfolio"></span>
                            </div>
                        <?php endif; ?>
                        <div class="fs-project-card-info">
                            <h3 class="fs-project-card-name">
                                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-projects&action=view&id=' . $project->id) ); ?>">
                                    <?php echo esc_html($project->name); ?>
                                </a>
                            </h3>
                            <?php if ($client_display): ?>
                                <p class="fs-project-card-client"><?php echo esc_html($client_display); ?></p>
                            <?php endif; ?>
                        </div>
                        <div class="fs-card-actions-menu">
                            <button type="button" class="fs-card-menu-trigger" aria-label="<?php esc_attr_e('Actions', 'freelance-studio'); ?>">
                                <span class="dashicons dashicons-ellipsis"></span>
                            </button>
                            <div class="fs-card-dropdown">
                                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-projects&action=view&id=' . $project->id) ); ?>">
                                    <span class="dashicons dashicons-visibility"></span> <?php esc_html_e('View', 'freelance-studio'); ?>
                                </a>
                                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-projects&action=edit&id=' . $project->id) ); ?>">
                                    <span class="dashicons dashicons-edit"></span> <?php esc_html_e('Edit', 'freelance-studio'); ?>
                                </a>
                                <?php if ($current_tab !== 'archived'): ?>
                                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=invoices&action=add&project_id=' . $project->id . '&client_id=' . $project->client_id) ); ?>">
                                    <span class="dashicons dashicons-media-spreadsheet"></span> <?php esc_html_e('Invoice project', 'freelance-studio'); ?>
                                </a>
                                <?php endif; ?>
                                <hr>
                                <?php if ($current_tab === 'archived'): ?>
                                <a href="<?php echo esc_url( wp_nonce_url( admin_url('admin.php?page=fs-projects&do_unarchive=1&id=' . $project->id), 'fs_unarchive_project') ); ?>">
                                    <span class="dashicons dashicons-undo"></span> <?php esc_html_e('Restore', 'freelance-studio'); ?>
                                </a>
                                <?php else: ?>
                                <a href="<?php echo esc_url( wp_nonce_url( admin_url('admin.php?page=fs-projects&do_archive=1&id=' . $project->id), 'fs_archive_project') ); ?>">
                                    <span class="dashicons dashicons-archive"></span> <?php esc_html_e('Archive', 'freelance-studio'); ?>
                                </a>
                                <?php endif; ?>
                                <a href="#" class="fs-delete-btn fs-text-danger" data-type="project" data-id="<?php echo  intval( $project->id ); ?>">
                                    <span class="dashicons dashicons-trash"></span> <?php esc_html_e('Delete', 'freelance-studio'); ?>
                                </a>
                            </div>
                        </div>
                    </div>
                    
                    <div class="fs-project-card-stats">
                        <div class="fs-client-stat">
                            <span class="fs-stat-label"><?php esc_html_e('STATUS', 'freelance-studio'); ?></span>
                            <span class="fs-stat-value"><?php echo  wp_kses_post( FS_View_Context::status_badge($project->status) ); ?></span>
                        </div>
                        <div class="fs-client-stat">
                            <span class="fs-stat-label"><?php esc_html_e('INVOICED', 'freelance-studio'); ?></span>
                            <span class="fs-stat-value"><?php echo  esc_html( FS_View_Context::format_currency($invoiced_amount) ); ?></span>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <!-- Desktop Table View -->
        <div class="fs-table-responsive fs-desktop-only">
            <!-- Bulk Actions Bar -->
            <div class="fs-bulk-actions-bar" id="fs-project-bulk-bar" style="display:none;">
                <label class="fs-bulk-select-all-label">
                    <input type="checkbox" id="fs-project-select-all-top">
                    <?php esc_html_e('Select all', 'freelance-studio'); ?>
                </label>
                <span class="fs-bulk-count" id="fs-project-bulk-count">0 <?php esc_html_e('selected', 'freelance-studio'); ?></span>
                <?php if ($current_tab === 'archived'): ?>
                <button type="button" class="fs-btn fs-btn-secondary fs-btn-small" id="fs-project-bulk-restore">
                    <span class="dashicons dashicons-undo"></span> <?php esc_html_e('Restore Selected', 'freelance-studio'); ?>
                </button>
                <?php else: ?>
                <button type="button" class="fs-btn fs-btn-secondary fs-btn-small" id="fs-project-bulk-archive">
                    <span class="dashicons dashicons-archive"></span> <?php esc_html_e('Archive Selected', 'freelance-studio'); ?>
                </button>
                <?php endif; ?>
            </div>
            <table class="fs-table fs-project-table widefat">
            <thead>
                <tr>
                    <th class="column-cb" style="width:40px;"><input type="checkbox" id="fs-project-select-all"></th>
                    <th class="column-project"><?php esc_html_e('Project', 'freelance-studio'); ?></th>
                    <th class="column-client"><?php esc_html_e('Client', 'freelance-studio'); ?></th>
                    <th class="column-starts"><?php esc_html_e('Starts', 'freelance-studio'); ?> ↓</th>
                    <th class="column-ends"><?php esc_html_e('Ends', 'freelance-studio'); ?></th>
                    <th class="column-status"><?php esc_html_e('Status', 'freelance-studio'); ?></th>
                    <th class="column-amount"><?php esc_html_e('Amount invoiced', 'freelance-studio'); ?></th>
                    <th class="column-actions"></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($projects as $project): 
                    $invoiced_amount = get_project_invoiced_amount($project->id);
                    $client_logo_url = '';
                    if (!empty($project->client_logo_id)) {
                        $client_logo_url = wp_get_attachment_image_url($project->client_logo_id, 'thumbnail');
                    }
                    if (empty($client_logo_url) && !empty($project->client_logo_url)) {
                        $client_logo_url = $project->client_logo_url;
                    }
                ?>
                    <tr>
                        <td class="column-cb"><input type="checkbox" class="fs-project-cb" value="<?php echo intval($project->id); ?>"></td>
                        <td class="column-project">
                            <div class="fs-project-name-cell">
                                <?php if ($client_logo_url): ?>
                                    <img src="<?php echo esc_url($client_logo_url); ?>" alt="" class="fs-client-logo-thumb">
                                <?php else: ?>
                                    <span class="fs-client-logo-placeholder">
                                        <span class="dashicons dashicons-portfolio"></span>
                                    </span>
                                <?php endif; ?>
                                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-projects&action=view&id=' . $project->id) ); ?>">
                                    <strong><?php echo esc_html($project->name); ?></strong>
                                </a>
                            </div>
                        </td>
                        <td class="column-client">
                            <?php echo esc_html($project->client_company ?: $project->client_name ?: '-'); ?>
                        </td>
                        <td class="column-starts">
                            <?php echo  esc_html( $project->start_date ? FS_View_Context::format_date($project->start_date) : '-' ); ?>
                        </td>
                        <td class="column-ends">
                            <?php echo  esc_html( $project->due_date ? FS_View_Context::format_date($project->due_date) : '-' ); ?>
                        </td>
                        <td class="column-status">
                            <?php echo  wp_kses_post( FS_View_Context::status_badge($project->status) ); ?>
                        </td>
                        <td class="column-amount">
                            <?php echo  esc_html( FS_View_Context::format_currency($invoiced_amount) ); ?>
                        </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-projects&action=view&id=' . $project->id) ); ?>"><?php esc_html_e('View', 'freelance-studio'); ?></a>
                                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-projects&action=edit&id=' . $project->id) ); ?>"><?php esc_html_e('Edit', 'freelance-studio'); ?></a>
                                    <?php if ($current_tab !== 'archived'): ?>
                                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=invoices&action=add&project_id=' . $project->id . '&client_id=' . $project->client_id) ); ?>"><?php esc_html_e('Invoice project', 'freelance-studio'); ?></a>
                                    <?php endif; ?>
                                    <hr>
                                    <?php if ($current_tab === 'archived'): ?>
                                    <a href="<?php echo esc_url( wp_nonce_url( admin_url('admin.php?page=fs-projects&do_unarchive=1&id=' . $project->id), 'fs_unarchive_project' ) ); ?>"><?php esc_html_e('Restore from Archive', 'freelance-studio'); ?></a>
                                    <?php else: ?>
                                    <a href="<?php echo esc_url( wp_nonce_url( admin_url('admin.php?page=fs-projects&do_archive=1&id=' . $project->id), 'fs_archive_project' ) ); ?>"><?php esc_html_e('Archive', 'freelance-studio'); ?></a>
                                    <?php endif; ?>
                                    <a href="#" class="fs-delete-btn text-danger" data-type="project" data-id="<?php echo  intval( $project->id ); ?>"><?php esc_html_e('Delete', 'freelance-studio'); ?></a>
                                </div>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        </div>
    <?php endif; ?>
    
    <?php
    // Pagination
    $base_url = admin_url('admin.php?page=fs-projects');
    $pg_params = array();
    if ($current_tab !== 'active') $pg_params['tab'] = $current_tab;
    if (!empty($current_status)) $pg_params['status'] = $current_status;
    if (!empty($current_client)) $pg_params['client_id'] = $current_client;
    if (!empty($current_billing)) $pg_params['billing_type'] = $current_billing;
    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 = __('projects', 'freelance-studio');
    include JEEB_FS_PLUGIN_DIR . 'includes/views/partials/pagination.php';
    ?>
</div>

<script>
jQuery(document).ready(function($) {
    var $bulkBar = $('#fs-project-bulk-bar');
    var $checkboxes = $('.fs-project-cb');
    var $selectAll = $('#fs-project-select-all, #fs-project-select-all-top');
    var $countLabel = $('#fs-project-bulk-count');

    function updateBulkBar() {
        var checked = $checkboxes.filter(':checked').length;
        if (checked > 0) {
            $bulkBar.slideDown(150);
            $countLabel.text(checked + ' <?php echo esc_js(__('selected', 'freelance-studio')); ?>');
        } else {
            $bulkBar.slideUp(150);
        }
        $selectAll.prop('checked', checked === $checkboxes.length && checked > 0);
    }

    $selectAll.on('change', function() {
        $checkboxes.prop('checked', $(this).is(':checked'));
        $selectAll.prop('checked', $(this).is(':checked'));
        updateBulkBar();
    });

    $checkboxes.on('change', updateBulkBar);

    function bulkAction(action_name) {
        var ids = $checkboxes.filter(':checked').map(function() { return $(this).val(); }).get();
        if (!ids.length) return;

        var msg = action_name === 'archive'
            ? '<?php echo esc_js(__('Archive', 'freelance-studio')); ?> ' + ids.length + ' <?php echo esc_js(__('projects?', 'freelance-studio')); ?>'
            : '<?php echo esc_js(__('Restore', 'freelance-studio')); ?> ' + ids.length + ' <?php echo esc_js(__('projects?', 'freelance-studio')); ?>';

        if (!confirm(msg)) return;

        $.ajax({
            url: typeof fs_ajax !== 'undefined' ? fs_ajax.ajax_url : ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_bulk_archive_projects',
                nonce: typeof fs_ajax !== 'undefined' ? fs_ajax.nonce : '',
                project_ids: ids,
                bulk_action: action_name
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert(response.data || 'Error');
                }
            }
        });
    }

    $('#fs-project-bulk-archive').on('click', function() { bulkAction('archive'); });
    $('#fs-project-bulk-restore').on('click', function() { bulkAction('restore'); });
});
</script>