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

// Avatar color helper
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_sort = isset($_GET['orderby']) ? sanitize_text_field($_GET['orderby']) : 'created_at';
$current_order = isset($_GET['order']) ? sanitize_text_field($_GET['order']) : 'DESC';

$has_filters = $current_status || $current_client;
?>
<div class="wrap fs-wrap">
    <div class="fs-page-header">
        <h1 class="fs-page-title"><?php esc_html_e('Proposals', 'freelance-studio'); ?></h1>
        <div style="flex:1;"></div>
        <?php if ( function_exists( 'fs_studio_limit_reached' ) && fs_studio_limit_reached( 'active_proposals' ) ): ?>
            <span class="fs-btn fs-btn-primary fs-btn-pro-gate" onclick="alert('<?php echo esc_js( __( 'Free plan allows 1 active proposal. Upgrade to Pro for unlimited proposals.', 'freelance-studio' ) ); ?>')">
                <?php esc_html_e('New proposal', 'freelance-studio'); ?>
            </span>
        <?php else: ?>
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-proposals&action=add') ); ?>" class="fs-btn fs-btn-primary">
                <?php esc_html_e('New proposal', 'freelance-studio'); ?>
            </a>
        <?php endif; ?>
    </div>

    <!-- Tab Navigation -->
    <div class="fs-tab-nav">
        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-proposals') ); ?>" 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  intval( $active_count ); ?></span>
        </a>
        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-proposals&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  intval( $archived_count ); ?></span>
        </a>
    </div>

    <?php
    // Show usage counter for free plan
    if ( function_exists( 'fs_studio_is_free_plan' ) && fs_studio_is_free_plan() ):
        $proposal_count = fs_studio_get_usage_count( 'active_proposals' );
        $limits = fs_studio_free_limits();
        if ( $proposal_count >= $limits['active_proposals'] ):
            fs_studio_upgrade_notice( 'proposals', 'banner' );
        else:
    ?>
        <div class="fs-usage-counter">
            <span class="fs-usage-counter-text">
                <?php /* translators: 1. count/number, 2. count/number */ ?>
                <?php echo esc_html( sprintf( __(  'Using %1$d of %2$d free active proposals', 'freelance-studio' ), $proposal_count, $limits['active_proposals'] ) ); ?>
            </span>
            <div class="fs-usage-bar">
                <div class="fs-usage-bar-fill" style="width: <?php echo  esc_attr( min( 100, ( $proposal_count / $limits['active_proposals'] ) * 100 ) ); ?>%"></div>
            </div>
            <a href="<?php echo  esc_url( freelance_studio_fs()->get_upgrade_url() ); ?>" class="fs-usage-upgrade-link"><?php esc_html_e( 'Upgrade for unlimited', 'freelance-studio' ); ?> &rarr;</a>
        </div>
    <?php
        endif;
    endif;
    ?>

    <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(
                        'created_at' => __('Date Created', 'freelance-studio'),
                        'start_date' => __('Start Date', 'freelance-studio'),
                        'valid_until' => __('Expiry Date', 'freelance-studio'),
                        'title' => __('Title', 'freelance-studio'),
                        'total_amount' => __('Amount', '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('error', 'not_found')) ? '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">
            <input type="hidden" name="page" value="fs-proposals">
            <select name="status" class="fs-filter-select">
                <option value=""><?php esc_html_e('All Statuses', 'freelance-studio'); ?></option>
                <?php foreach ($statuses as $k => $l): ?>
                    <option value="<?php echo esc_attr($k); ?>" <?php selected($current_status, $k); ?>><?php echo esc_html($l); ?></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  intval( $c->id ); ?>" <?php selected($current_client, $c->id); ?>><?php echo esc_html($c->company_name ?: $c->name); ?></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-proposals') ); ?>" class="button"><?php esc_html_e('Clear', 'freelance-studio'); ?></a>
            <?php endif; ?>
        </form>
    </div>
    
    <?php if (empty($proposals)): ?>
        <div class="fs-empty-state">
            <div class="fs-empty-state-icon">📋</div>
            <h3><?php esc_html_e('No proposals yet', 'freelance-studio'); ?></h3>
            <p><?php esc_html_e('Create your first proposal to send to a client.', 'freelance-studio'); ?></p>
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-proposals&action=add') ); ?>" class="button button-primary">
                <?php esc_html_e('New proposal', 'freelance-studio'); ?>
            </a>
        </div>
    <?php else: ?>

        <!-- Mobile Card View -->
        <div class="fs-projects-grid fs-mobile-only">
            <?php foreach ($proposals as $proposal): 
                $is_expired = FS_Proposal::is_expired($proposal);
                $display_status = $is_expired && $proposal->status !== 'approved' && $proposal->status !== 'rejected' ? 'expired' : $proposal->status;
                $client_display = $proposal->client_company ?: $proposal->client_name;
            ?>
                <div class="fs-project-card">
                    <div class="fs-project-card-header">
                        <div class="fs-client-avatar fs-avatar-sm" style="background-color: <?php echo esc_attr(fs_get_avatar_color($client_display ?: $proposal->title)); ?>;">
                            <span class="dashicons dashicons-media-text"></span>
                        </div>
                        <div class="fs-project-card-info">
                            <h3 class="fs-project-card-name">
                                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-proposals&action=view&id=' . $proposal->id) ); ?>">
                                    <?php echo esc_html($proposal->title); ?>
                                </a>
                            </h3>
                            <p class="fs-project-card-client"><?php echo esc_html($client_display); ?></p>
                        </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-proposals&action=view&id=' . $proposal->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-proposals&action=edit&id=' . $proposal->id) ); ?>">
                                    <span class="dashicons dashicons-edit"></span> <?php esc_html_e('Edit', 'freelance-studio'); ?>
                                </a>
                                <?php if ($proposal->status === 'draft'): ?>
                                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-proposals&action=send&id=' . $proposal->id) ); ?>">
                                        <span class="dashicons dashicons-email"></span> <?php esc_html_e('Send to client', 'freelance-studio'); ?>
                                    </a>
                                <?php endif; ?>
                                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-proposals&action=duplicate&id=' . $proposal->id) ); ?>">
                                    <span class="dashicons dashicons-admin-page"></span> <?php esc_html_e('Duplicate', 'freelance-studio'); ?>
                                </a>
                                <?php if ($proposal->status === 'approved'): ?>
                                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-proposals&action=convert&id=' . $proposal->id) ); ?>">
                                        <span class="dashicons dashicons-yes-alt"></span> <?php esc_html_e('Convert to contract', 'freelance-studio'); ?>
                                    </a>
                                <?php endif; ?>
                                <?php if ($proposal->status !== 'converted'): ?>
                                    <hr>
                                    <?php if ($current_tab === 'archived'): ?>
                                    <a href="<?php echo esc_url( wp_nonce_url( admin_url('admin.php?page=fs-proposals&do_unarchive=1&id=' . $proposal->id) ), 'fs_unarchive_proposal'); ?>">
                                        <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-proposals&do_archive=1&id=' . $proposal->id) ), 'fs_archive_proposal'); ?>">
                                        <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="proposal" data-id="<?php echo  intval( $proposal->id ); ?>">
                                        <span class="dashicons dashicons-trash"></span> <?php esc_html_e('Delete', 'freelance-studio'); ?>
                                    </a>
                                <?php endif; ?>
                            </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($display_status) ); ?></span>
                        </div>
                        <div class="fs-client-stat">
                            <span class="fs-stat-label"><?php esc_html_e('EXPIRES', 'freelance-studio'); ?></span>
                            <span class="fs-stat-value"><?php echo  esc_html( $proposal->valid_until ? FS_View_Context::format_date($proposal->valid_until) : '—' ); ?></span>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <!-- Desktop Table View -->
        <div class="fs-table-responsive fs-desktop-only">
            <table class="fs-table fs-proposal-table widefat">
            <thead>
                <tr>
                    <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-expires"><?php esc_html_e('Ends / Expires', 'freelance-studio'); ?></th>
                    <th class="column-status"><?php esc_html_e('Status', 'freelance-studio'); ?></th>
                    <th class="column-actions"></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($proposals as $proposal): 
                    $is_expired = FS_Proposal::is_expired($proposal);
                    $display_status = $is_expired && $proposal->status !== 'approved' && $proposal->status !== 'rejected' ? 'expired' : $proposal->status;
                ?>
                    <tr>
                        <td class="column-project">
                            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-proposals&action=view&id=' . $proposal->id) ); ?>">
                                <strong><?php echo esc_html($proposal->title); ?></strong>
                            </a>
                            <div class="fs-row-subtitle"><?php esc_html_e('Proposal & Contract', 'freelance-studio'); ?></div>
                        </td>
                        <td class="column-client">
                            <?php echo esc_html($proposal->client_company ?: $proposal->client_name); ?>
                        </td>
                        <td class="column-starts">
                            <?php echo  esc_html( $proposal->start_date ? FS_View_Context::format_date($proposal->start_date) : '-' ); ?>
                        </td>
                        <td class="column-expires">
                            <?php echo  esc_html( $proposal->valid_until ? FS_View_Context::format_date($proposal->valid_until) : '-' ); ?>
                        </td>
                        <td class="column-status">
                            <?php echo  wp_kses_post( FS_View_Context::status_badge($display_status) ); ?>
                        </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-proposals&action=view&id=' . $proposal->id) ); ?>"><?php esc_html_e('View', 'freelance-studio'); ?></a>
                                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-proposals&action=edit&id=' . $proposal->id) ); ?>"><?php esc_html_e('Edit', 'freelance-studio'); ?></a>
                                    <?php if ($proposal->status === 'draft'): ?>
                                        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-proposals&action=send&id=' . $proposal->id) ); ?>"><?php esc_html_e('Send to client', 'freelance-studio'); ?></a>
                                    <?php endif; ?>
                                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-proposals&action=duplicate&id=' . $proposal->id) ); ?>"><?php esc_html_e('Duplicate', 'freelance-studio'); ?></a>
                                    <?php if ($proposal->status === 'approved'): ?>
                                        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-proposals&action=convert&id=' . $proposal->id) ); ?>"><?php esc_html_e('Convert to contract', 'freelance-studio'); ?></a>
                                    <?php endif; ?>
                                    <?php if ($proposal->status !== 'converted'): ?>
                                        <hr>
                                        <?php if ($current_tab === 'archived'): ?>
                                        <a href="<?php echo esc_url( wp_nonce_url( admin_url('admin.php?page=fs-proposals&do_unarchive=1&id=' . $proposal->id) ), 'fs_unarchive_proposal'); ?>"><?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-proposals&do_archive=1&id=' . $proposal->id) ), 'fs_archive_proposal'); ?>"><?php esc_html_e('Archive', 'freelance-studio'); ?></a>
                                        <?php endif; ?>
                                        <a href="#" class="fs-delete-btn text-danger" data-type="proposal" data-id="<?php echo  intval( $proposal->id ); ?>"><?php esc_html_e('Delete', 'freelance-studio'); ?></a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        </div>
    <?php endif; ?>
    
    <?php
    // Pagination
    $base_url = admin_url('admin.php?page=fs-proposals');
    $pg_params = array();
    if ($current_tab !== 'active') $pg_params['tab'] = $current_tab;
    if (!empty($status_filter)) $pg_params['status'] = $status_filter;
    if (!empty($client_filter)) $pg_params['client_id'] = $client_filter;
    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 = __('proposals', 'freelance-studio');
    include JEEB_FS_PLUGIN_DIR . 'includes/views/partials/pagination.php';
    ?>
</div>
