<?php
/**
 * Project Portal View
 *
 * @package Freelance_Studio
 */

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

$primary_color = !empty($settings['primary_color']) ? $settings['primary_color'] : '#4173B0';
$business_name = !empty($settings['business_name']) ? $settings['business_name'] : get_bloginfo('name');
$client_name = $client->company_name ?: $client->name;

// Current tab
$current_tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'overview';
$tabs = array(
    'overview' => __('Overview', 'freelance-studio'),
    'milestones' => __('Milestones', 'freelance-studio'),
    'tasks' => __('Tasks', 'freelance-studio'),
    'files' => __('Files', 'freelance-studio'),
    'billing' => __('Billing', 'freelance-studio'),
);

// Filter tasks to only show client-visible ones
$visible_tasks = array_filter($tasks, function($task) {
    return !isset($task->is_client_visible) || $task->is_client_visible;
});

// Get client's tasks (assigned to client)
$client_tasks = array_filter($visible_tasks, function($task) {
    return ($task->assigned_to ?? 'freelancer') === 'client';
});

// Get pending client tasks only
$pending_client_tasks = array_filter($client_tasks, function($task) {
    return $task->status !== 'completed';
});

// Get milestones
$milestones = FS_Milestone::get_by_project($project->id);
$milestone_progress = FS_Milestone::get_project_progress($project->id);

// Project dates display
$date_range = '';
if ($project->start_date) {
    $date_range = date_i18n('M j, Y', strtotime($project->start_date));
}
if ($project->due_date) {
    $date_range .= ($date_range ? ' - ' : '') . date_i18n('M j, Y', strtotime($project->due_date));
}

// Get outstanding invoices for this project
$outstanding_invoices = array_filter($invoices, function($inv) {
    return in_array($inv->status, array('sent', 'viewed', 'partial'));
});

// Calculate project services total and unbilled time
$services_total = 0;
if (!empty($project->services)) {
    $services = json_decode($project->services, true) ?: array();
    foreach ($services as $svc) {
        $services_total += floatval($svc['amount'] ?? 0);
    }
}

// Get unbilled time entries
$time_entries = FS_Time_Entry::get_all(array('project_id' => $project->id, 'running' => false));
$unbilled_time_amount = 0;
$unbilled_hours = 0;
foreach ($time_entries as $entry) {
    if (!$entry->invoiced) {
        $unbilled_hours += FS_Time_Entry::get_rounded_hours($entry->duration);
        $unbilled_time_amount += $entry->billable_amount;
    }
}
?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo('charset'); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="robots" content="noindex, nofollow">
    <title><?php echo esc_html($project->name); ?> - <?php echo esc_html($client_name); ?></title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <?php // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet -- Public-facing portal page; Google Fonts loaded directly. ?>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        <?php include JEEB_FS_PLUGIN_DIR . 'includes/views/public/portal/portal-styles.php'; ?>
    </style>
</head>
<body class="fs-portal">
    <div class="fs-portal-container">
        <!-- Header -->
        <header class="fs-portal-header">
            <div class="fs-portal-header-inner">
                <div class="fs-portal-branding">
                    <a href="<?php echo esc_url(home_url('?fs_portal=' . $portal_token)); ?>" class="fs-portal-back">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M19 12H5M12 19l-7-7 7-7"/>
                        </svg>
                    </a>
                    <div class="fs-portal-breadcrumb">
                        <span class="fs-breadcrumb-client"><?php echo esc_html($client_name); ?></span>
                        <span class="fs-breadcrumb-sep">/</span>
                        <span class="fs-breadcrumb-project"><?php echo esc_html($project->name); ?></span>
                    </div>
                </div>
                <?php if ($date_range): ?>
                <div class="fs-portal-project-dates-header">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/>
                    </svg>
                    <?php echo esc_html($date_range); ?>
                </div>
                <?php endif; ?>
            </div>
        </header>
        
        <!-- Project Header -->
        <div class="fs-portal-project-header">
            <div class="fs-portal-project-header-inner">
                <div class="fs-portal-project-title-section">
                    <h1 class="fs-portal-project-title"><?php echo esc_html($project->name); ?></h1>
                    <?php if ($progress > 0): ?>
                    <div class="fs-portal-progress-badge">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <circle cx="12" cy="12" r="10"/>
                            <path d="M12 6v6l4 2"/>
                        </svg>
                        <?php echo  esc_html( $progress ); ?>% <?php esc_html_e('completed', 'freelance-studio'); ?>
                    </div>
                    <?php endif; ?>
                </div>
                
                <!-- Tabs -->
                <nav class="fs-portal-tabs">
                    <?php foreach ($tabs as $tab_id => $tab_label): 
                        $tab_url = add_query_arg('tab', $tab_id, home_url('?fs_project_portal=' . $portal_token . ':' . $project->id));
                    ?>
                    <a href="<?php echo esc_url($tab_url); ?>" class="fs-portal-tab <?php echo $current_tab === $tab_id ? 'active' : ''; ?>">
                        <?php echo esc_html($tab_label); ?>
                    </a>
                    <?php endforeach; ?>
                </nav>
            </div>
        </div>
        
        <!-- Main Content -->
        <main class="fs-portal-main">
            <div class="fs-portal-content">
                <?php if ($current_tab === 'overview'): ?>
                <!-- Overview Tab -->
                <div class="fs-portal-grid">
                    <!-- Left Column -->
                    <div class="fs-portal-main-col">
                        <!-- Outstanding Items -->
                        <?php if (!empty($outstanding_invoices) || !empty($pending_tasks)): ?>
                        <div class="fs-portal-card">
                            <div class="fs-portal-card-header">
                                <h2><?php esc_html_e('Outstanding Invoices', 'freelance-studio'); ?> <span class="fs-count-badge"><?php echo count($outstanding_invoices); ?></span></h2>
                            </div>
                            <div class="fs-portal-card-body">
                                <ul class="fs-portal-items-list">
                                    <?php foreach ($outstanding_invoices as $invoice): ?>
                                    <li class="fs-portal-item">
                                        <div class="fs-portal-item-icon fs-icon-invoice">
                                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                                <rect x="3" y="3" width="18" height="18" rx="2"/>
                                                <path d="M9 7h6M9 11h6M9 15h4"/>
                                            </svg>
                                        </div>
                                        <div class="fs-portal-item-content">
                                            <div class="fs-portal-item-title">
                                                <?php /* translators: 1. number/ID */ ?>
                                                <?php echo esc_html( sprintf( __( 'Invoice #%s', 'freelance-studio'), esc_html($invoice->invoice_number)) ); ?>
                                            </div>
                                            <div class="fs-portal-item-meta">
                                                <?php echo  esc_html( FS_View_Context::format_currency($invoice->balance_due) ); ?> due
                                                <?php if ($invoice->due_date): ?>
                                                    <?php echo  esc_html( date_i18n('M j', strtotime($invoice->due_date)) ); ?>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <a href="<?php echo esc_url(home_url('?fs_invoice=' . $invoice->view_token)); ?>" class="fs-portal-btn fs-portal-btn-primary">
                                            <?php esc_html_e('View', 'freelance-studio'); ?>
                                        </a>
                                    </li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <!-- Client Tasks -->
                        <?php if (!empty($pending_client_tasks)): ?>
                        <div class="fs-portal-card">
                            <div class="fs-portal-card-header">
                                <h2><?php esc_html_e('Client Tasks', 'freelance-studio'); ?> <span class="fs-count-badge"><?php echo count($pending_client_tasks); ?></span></h2>
                            </div>
                            <div class="fs-portal-card-body">
                                <ul class="fs-portal-tasks-list fs-portal-tasks-interactive">
                                    <?php 
                                    $displayed_tasks = array_slice($pending_client_tasks, 0, 5);
                                    foreach ($displayed_tasks as $task): 
                                        $is_completed = $task->status === 'completed';
                                        $is_overdue = $task->due_date && strtotime($task->due_date) < time() && !$is_completed;
                                    ?>
                                    <li class="fs-portal-task-card <?php echo $is_completed ? 'completed' : ''; ?> <?php echo $is_overdue ? 'overdue' : ''; ?>" data-task-id="<?php echo esc_attr($task->id); ?>">
                                        <div class="fs-portal-task-checkbox-wrap">
                                            <label class="fs-portal-custom-checkbox">
                                                <input type="checkbox" class="fs-portal-task-toggle" data-task-id="<?php echo esc_attr($task->id); ?>" <?php checked($is_completed); ?>>
                                                <span class="fs-portal-checkbox-mark"></span>
                                            </label>
                                        </div>
                                        <div class="fs-portal-task-info">
                                            <div class="fs-portal-task-title"><?php echo esc_html($task->title); ?></div>
                                            <?php if ($task->due_date): ?>
                                            <div class="fs-portal-task-meta <?php echo $is_overdue ? 'overdue' : ''; ?>">
                                                <?php if ($is_overdue): ?>
                                                    <?php /* translators: 1. overdue value */ ?>
                                                    <?php echo esc_html( sprintf( __( 'Overdue: %s', 'freelance-studio'), date_i18n('M j', strtotime($task->due_date))) ); ?>
                                                <?php else: ?>
                                                    <?php /* translators: 1. due value */ ?>
                                                    <?php echo esc_html( sprintf( __( 'Due %s', 'freelance-studio'), date_i18n('M j', strtotime($task->due_date))) ); ?>
                                                <?php endif; ?>
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                    </li>
                                    <?php endforeach; ?>
                                </ul>
                                <?php if (count($pending_client_tasks) > 5): ?>
                                <a href="<?php echo esc_url(add_query_arg('tab', 'tasks', home_url('?fs_project_portal=' . $portal_token . ':' . $project->id))); ?>" class="fs-portal-view-all">
                                    <?php esc_html_e('View all tasks', 'freelance-studio'); ?> →
                                </a>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                    
                    <!-- Right Column - Sidebar -->
                    <div class="fs-portal-sidebar">
                        <!-- Billing Summary -->
                        <div class="fs-portal-card">
                            <div class="fs-portal-card-header">
                                <h2><?php esc_html_e('Billing', 'freelance-studio'); ?></h2>
                                <a href="<?php echo esc_url(add_query_arg('tab', 'billing', home_url('?fs_project_portal=' . $portal_token . ':' . $project->id))); ?>" class="fs-portal-header-link">
                                    <?php esc_html_e('View Invoices', 'freelance-studio'); ?>
                                </a>
                            </div>
                            <div class="fs-portal-card-body">
                                <?php 
                                // Show deposit status if applicable
                                $has_deposit = ($project->deposit_amount > 0 || $project->deposit_percentage > 0);
                                if ($has_deposit): 
                                ?>
                                <div class="fs-portal-deposit-status <?php echo $project->deposit_paid ? 'paid' : 'unpaid'; ?>">
                                    <?php if ($project->deposit_paid): ?>
                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                            <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/>
                                            <polyline points="22 4 12 14.01 9 11.01"/>
                                        </svg>
                                        <?php esc_html_e('Deposit Paid', 'freelance-studio'); ?>
                                    <?php else: ?>
                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                            <circle cx="12" cy="12" r="10"/>
                                            <line x1="12" y1="8" x2="12" y2="12"/>
                                            <line x1="12" y1="16" x2="12.01" y2="16"/>
                                        </svg>
                                        <?php esc_html_e('Deposit Required', 'freelance-studio'); ?>: 
                                        <?php echo  esc_html( FS_View_Context::format_currency($project->deposit_amount) ); ?>
                                    <?php endif; ?>
                                </div>
                                <?php endif; ?>
                                
                                <!-- Project Total & Unbilled Time -->
                                <div class="fs-portal-billing-details">
                                    <?php if ($services_total > 0): ?>
                                    <div class="fs-portal-billing-row">
                                        <span class="fs-portal-billing-label"><?php esc_html_e('Project Total', 'freelance-studio'); ?></span>
                                        <span class="fs-portal-billing-value"><?php echo  esc_html( FS_View_Context::format_currency($services_total) ); ?></span>
                                    </div>
                                    <?php endif; ?>
                                    <?php if ($unbilled_time_amount > 0): ?>
                                    <div class="fs-portal-billing-row">
                                        <span class="fs-portal-billing-label"><?php esc_html_e('Unbilled Time', 'freelance-studio'); ?></span>
                                        <span class="fs-portal-billing-value"><?php echo  esc_html( FS_View_Context::format_currency($unbilled_time_amount) ); ?> <small>(<?php echo number_format($unbilled_hours, 1); ?> hrs)</small></span>
                                    </div>
                                    <?php endif; ?>
                                </div>
                                
                                <div class="fs-portal-billing-stats">
                                    <div class="fs-portal-stat">
                                        <div class="fs-portal-stat-label"><?php esc_html_e('Outstanding', 'freelance-studio'); ?></div>
                                        <div class="fs-portal-stat-value"><?php echo  esc_html( FS_View_Context::format_currency($billing_stats['outstanding']) ); ?></div>
                                    </div>
                                    <div class="fs-portal-stat">
                                        <div class="fs-portal-stat-label"><?php esc_html_e('Overdue', 'freelance-studio'); ?></div>
                                        <div class="fs-portal-stat-value <?php echo $billing_stats['overdue'] > 0 ? 'fs-text-danger' : ''; ?>">
                                            <?php echo  esc_html( FS_View_Context::format_currency($billing_stats['overdue']) ); ?>
                                        </div>
                                    </div>
                                    <div class="fs-portal-stat">
                                        <div class="fs-portal-stat-label"><?php esc_html_e('Paid', 'freelance-studio'); ?></div>
                                        <div class="fs-portal-stat-value fs-text-success"><?php echo  esc_html( FS_View_Context::format_currency($billing_stats['paid']) ); ?></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <?php elseif ($current_tab === 'milestones'): ?>
                <!-- Milestones Tab -->
                <div class="fs-portal-milestones-section">
                    <?php if (!empty($milestones)): ?>
                    <!-- Progress Overview -->
                    <div class="fs-portal-progress-overview">
                        <div class="fs-portal-progress-circle">
                            <svg viewBox="0 0 36 36">
                                <path class="fs-progress-bg" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"/>
                                <path class="fs-progress-fill" stroke-dasharray="<?php echo  esc_html( $milestone_progress ); ?>, 100" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"/>
                            </svg>
                            <div class="fs-progress-text">
                                <span class="fs-progress-number"><?php echo  esc_html( $milestone_progress ); ?>%</span>
                                <span class="fs-progress-label"><?php esc_html_e('Complete', 'freelance-studio'); ?></span>
                            </div>
                        </div>
                        <div class="fs-portal-progress-stats">
                            <div class="fs-progress-stat">
                                <span class="fs-progress-stat-number"><?php echo count(array_filter($milestones, function($m) { return $m->status === 'completed'; })); ?></span>
                                <span class="fs-progress-stat-label"><?php esc_html_e('Completed', 'freelance-studio'); ?></span>
                            </div>
                            <div class="fs-progress-stat">
                                <span class="fs-progress-stat-number"><?php echo count(array_filter($milestones, function($m) { return $m->status !== 'completed'; })); ?></span>
                                <span class="fs-progress-stat-label"><?php esc_html_e('Remaining', 'freelance-studio'); ?></span>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Milestones Timeline -->
                    <div class="fs-portal-milestones-timeline">
                        <?php 
                        $milestone_index = 0;
                        foreach ($milestones as $milestone): 
                            $milestone_index++;
                            $is_completed = $milestone->status === 'completed';
                            $is_current = !$is_completed && $milestone_index === count(array_filter($milestones, function($m) { return $m->status === 'completed'; })) + 1;
                        ?>
                        <div class="fs-portal-milestone-item <?php echo $is_completed ? 'completed' : ''; ?> <?php echo $is_current ? 'current' : ''; ?>">
                            <div class="fs-portal-milestone-marker">
                                <?php if ($is_completed): ?>
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3">
                                    <polyline points="20 6 9 17 4 12"/>
                                </svg>
                                <?php else: ?>
                                <span><?php echo  esc_html( $milestone_index ); ?></span>
                                <?php endif; ?>
                            </div>
                            <div class="fs-portal-milestone-content">
                                <div class="fs-portal-milestone-header">
                                    <h3 class="fs-portal-milestone-title"><?php echo esc_html($milestone->name); ?></h3>
                                    <?php if ($is_current): ?>
                                    <span class="fs-portal-current-badge"><?php esc_html_e('In Progress', 'freelance-studio'); ?></span>
                                    <?php endif; ?>
                                </div>
                                <?php if ($milestone->description): ?>
                                <p class="fs-portal-milestone-desc"><?php echo esc_html($milestone->description); ?></p>
                                <?php endif; ?>
                                <?php if ($milestone->due_date): ?>
                                <div class="fs-portal-milestone-date">
                                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                        <rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/>
                                    </svg>
                                    <?php if ($is_completed && $milestone->completed_date): ?>
                                        <?php /* translators: 1. completed value */ ?>
                                        <?php echo esc_html( sprintf( __( 'Completed %s', 'freelance-studio'), date_i18n('M j, Y', strtotime($milestone->completed_date))) ); ?>
                                    <?php else: ?>
                                        <?php /* translators: 1. due value */ ?>
                                        <?php echo esc_html( sprintf( __( 'Due %s', 'freelance-studio'), date_i18n('M j, Y', strtotime($milestone->due_date))) ); ?>
                                    <?php endif; ?>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php else: ?>
                    <div class="fs-portal-empty">
                        <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" style="opacity: 0.5;">
                            <path d="M3 3v18h18"/>
                            <path d="M18.7 8l-5.1 5.2-2.8-2.7L7 14.3"/>
                        </svg>
                        <p><?php esc_html_e('No milestones defined for this project yet.', 'freelance-studio'); ?></p>
                    </div>
                    <?php endif; ?>
                </div>
                
                <?php elseif ($current_tab === 'tasks'): ?>
                <!-- Tasks Tab - Enhanced -->
                <div class="fs-portal-tasks-section">
                    <!-- Request Task Button -->
                    <div class="fs-portal-task-request-header">
                        <button type="button" class="fs-portal-btn fs-portal-btn-primary fs-portal-btn-sm" id="fs-project-request-task-btn" data-project-id="<?php echo esc_attr($project->id); ?>">
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
                            <?php esc_html_e('Request Task', 'freelance-studio'); ?>
                        </button>
                    </div>
                    
                    <?php if (!empty($client_tasks)): ?>
                    <!-- Client's Tasks Card -->
                    <div class="fs-portal-card fs-portal-card-highlight">
                        <div class="fs-portal-card-header">
                            <h2>
                                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
                                    <circle cx="12" cy="7" r="4"/>
                                </svg>
                                <?php esc_html_e('Your Tasks', 'freelance-studio'); ?>
                                <span class="fs-count-badge"><?php echo count($client_tasks); ?></span>
                            </h2>
                            <p class="fs-portal-card-subtitle"><?php esc_html_e('Tasks assigned to you for completion', 'freelance-studio'); ?></p>
                        </div>
                        <div class="fs-portal-card-body">
                            <ul class="fs-portal-tasks-list fs-portal-tasks-interactive">
                                <?php foreach ($client_tasks as $task): 
                                    $is_completed = $task->status === 'completed';
                                    $is_overdue = $task->due_date && strtotime($task->due_date) < time() && !$is_completed;
                                ?>
                                <li class="fs-portal-task-card <?php echo $is_completed ? 'completed' : ''; ?> <?php echo $is_overdue ? 'overdue' : ''; ?>" data-task-id="<?php echo esc_attr($task->id); ?>">
                                    <div class="fs-portal-task-checkbox-wrap">
                                        <label class="fs-portal-custom-checkbox">
                                            <input type="checkbox" class="fs-portal-task-toggle" data-task-id="<?php echo esc_attr($task->id); ?>" <?php checked($is_completed); ?>>
                                            <span class="fs-portal-checkbox-mark"></span>
                                        </label>
                                    </div>
                                    <div class="fs-portal-task-info">
                                        <div class="fs-portal-task-title <?php echo $is_completed ? 'completed' : ''; ?>">
                                            <?php echo esc_html($task->title); ?>
                                        </div>
                                        <?php if ($task->description): ?>
                                        <div class="fs-portal-task-desc"><?php echo esc_html($task->description); ?></div>
                                        <?php endif; ?>
                                        <?php if ($task->due_date): ?>
                                        <div class="fs-portal-task-meta <?php echo $is_overdue ? 'overdue' : ''; ?>">
                                            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                                <rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/>
                                            </svg>
                                            <?php if ($is_overdue): ?>
                                                <?php /* translators: 1. overdue value */ ?>
                                                <?php echo esc_html( sprintf( __( 'Overdue: %s', 'freelance-studio'), date_i18n('M j', strtotime($task->due_date))) ); ?>
                                            <?php else: ?>
                                                <?php /* translators: 1. due value */ ?>
                                                <?php echo esc_html( sprintf( __( 'Due %s', 'freelance-studio'), date_i18n('M j', strtotime($task->due_date))) ); ?>
                                            <?php endif; ?>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                    <?php if ($is_completed): ?>
                                    <div class="fs-portal-task-done-badge">
                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                            <polyline points="20 6 9 17 4 12"/>
                                        </svg>
                                    </div>
                                    <?php endif; ?>
                                </li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- All Project Tasks -->
                    <?php 
                    $active_visible_tasks = array_filter($visible_tasks, function($t) { return !in_array($t->status, array('completed', 'archived', 'cancelled')); });
                    $inactive_visible_tasks = array_filter($visible_tasks, function($t) { return in_array($t->status, array('completed', 'archived', 'cancelled')); });
                    ?>
                    <div class="fs-portal-card">
                        <div class="fs-portal-card-header fs-portal-tabs-header">
                            <div class="fs-portal-tabs">
                                <button type="button" class="fs-portal-tab active" data-tab="project-tasks-active">
                                    <?php esc_html_e('Active', 'freelance-studio'); ?> 
                                    <?php if (!empty($active_visible_tasks)): ?>
                                    <span class="fs-count-badge"><?php echo count($active_visible_tasks); ?></span>
                                    <?php endif; ?>
                                </button>
                                <button type="button" class="fs-portal-tab" data-tab="project-tasks-inactive">
                                    <?php esc_html_e('Inactive', 'freelance-studio'); ?> 
                                    <?php if (!empty($inactive_visible_tasks)): ?>
                                    <span class="fs-count-badge"><?php echo count($inactive_visible_tasks); ?></span>
                                    <?php endif; ?>
                                </button>
                            </div>
                        </div>
                        
                        <!-- Active Tasks -->
                        <div class="fs-portal-card-body fs-portal-tab-content active" id="tab-project-tasks-active">
                            <?php if (!empty($active_visible_tasks)): ?>
                            <ul class="fs-portal-tasks-list fs-portal-tasks-full">
                                <?php foreach ($active_visible_tasks as $task): 
                                    $is_client_task = ($task->assigned_to ?? 'freelancer') === 'client';
                                    $is_overdue = $task->due_date && strtotime($task->due_date) < time();
                                ?>
                                <li class="fs-portal-task">
                                    <div class="fs-portal-task-status">
                                        <span class="fs-portal-task-pending"></span>
                                    </div>
                                    <div class="fs-portal-task-content">
                                        <div class="fs-portal-task-title"><?php echo esc_html($task->title); ?></div>
                                        <?php if (!empty($task->description)): ?>
                                        <div class="fs-portal-task-desc"><?php echo esc_html($task->description); ?></div>
                                        <?php endif; ?>
                                    </div>
                                    <div class="fs-portal-task-badges">
                                        <?php if ($is_client_task): ?>
                                        <span class="fs-portal-assignee-badge client"><?php esc_html_e('You', 'freelance-studio'); ?></span>
                                        <?php else: ?>
                                        <span class="fs-portal-assignee-badge designer"><?php echo esc_html($business_name); ?></span>
                                        <?php endif; ?>
                                    </div>
                                    <?php if ($task->due_date): ?>
                                    <div class="fs-portal-task-due <?php echo $is_overdue ? 'overdue' : ''; ?>">
                                        <?php echo  esc_html( date_i18n('M j', strtotime($task->due_date)) ); ?>
                                    </div>
                                    <?php endif; ?>
                                </li>
                                <?php endforeach; ?>
                            </ul>
                            <?php else: ?>
                            <div class="fs-portal-empty">
                                <p><?php esc_html_e('No active tasks.', 'freelance-studio'); ?></p>
                            </div>
                            <?php endif; ?>
                        </div>
                        
                        <!-- Inactive Tasks -->
                        <div class="fs-portal-card-body fs-portal-tab-content" id="tab-project-tasks-inactive">
                            <?php if (!empty($inactive_visible_tasks)): ?>
                            <ul class="fs-portal-tasks-list fs-portal-tasks-full">
                                <?php foreach ($inactive_visible_tasks as $task): 
                                    $is_client_task = ($task->assigned_to ?? 'freelancer') === 'client';
                                    $is_completed = $task->status === 'completed';
                                    $inactive_status_labels = array(
                                        'completed' => __('Completed', 'freelance-studio'),
                                        'archived' => __('Archived', 'freelance-studio'),
                                        'cancelled' => __('Cancelled', 'freelance-studio'),
                                    );
                                    $inactive_label = $inactive_status_labels[$task->status] ?? ucfirst($task->status);
                                ?>
                                <li class="fs-portal-task completed">
                                    <div class="fs-portal-task-status">
                                        <?php if ($is_completed): ?>
                                        <span class="fs-portal-task-done">
                                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                                <polyline points="20 6 9 17 4 12"/>
                                            </svg>
                                        </span>
                                        <?php else: ?>
                                        <span class="fs-portal-task-done" style="opacity: 0.4;">
                                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                                <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
                                            </svg>
                                        </span>
                                        <?php endif; ?>
                                    </div>
                                    <div class="fs-portal-task-content">
                                        <div class="fs-portal-task-title"><?php echo esc_html($task->title); ?></div>
                                        <?php if (!empty($task->description)): ?>
                                        <div class="fs-portal-task-desc"><?php echo esc_html($task->description); ?></div>
                                        <?php endif; ?>
                                    </div>
                                    <div class="fs-portal-task-badges">
                                        <?php if ($is_client_task): ?>
                                        <span class="fs-portal-assignee-badge client"><?php esc_html_e('You', 'freelance-studio'); ?></span>
                                        <?php else: ?>
                                        <span class="fs-portal-assignee-badge designer"><?php echo esc_html($business_name); ?></span>
                                        <?php endif; ?>
                                    </div>
                                    <div class="fs-portal-task-due">
                                        <?php echo esc_html($inactive_label); ?>
                                    </div>
                                </li>
                                <?php endforeach; ?>
                            </ul>
                            <?php else: ?>
                            <div class="fs-portal-empty">
                                <p><?php esc_html_e('No inactive tasks.', 'freelance-studio'); ?></p>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                
                <?php elseif ($current_tab === 'files'): ?>
                <!-- Files Tab -->
                <div class="fs-portal-files-tab">
                    <!-- Shared Files Section -->
                    <div class="fs-portal-card">
                        <div class="fs-portal-card-header">
                            <h2><?php esc_html_e('Project Files', 'freelance-studio'); ?> <span class="fs-count-badge"><?php echo count($files); ?></span></h2>
                        </div>
                        <div class="fs-portal-card-body">
                            <?php if (!empty($files)): ?>
                            <div class="fs-portal-files-grid">
                                <?php foreach ($files as $file): 
                                    $has_url = !empty($file->url);
                                    $tag = $has_url ? 'a' : 'div';
                                    $href = $has_url ? ' href="' . esc_url($file->url) . '" target="_blank"' : '';
                                    $disabled_class = $has_url ? '' : ' fs-portal-file-card-disabled';
                                ?>
                                <<?php echo  esc_html( $tag . $href ); ?> class="fs-portal-file-card<?php echo  esc_html( $disabled_class ); ?>">
                                    <div class="fs-portal-file-card-icon">
                                        <?php if ($file->type === 'link'): ?>
                                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                            <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/>
                                            <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>
                                        </svg>
                                        <?php else: ?>
                                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                            <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
                                            <polyline points="14 2 14 8 20 8"/>
                                        </svg>
                                        <?php endif; ?>
                                    </div>
                                    <div class="fs-portal-file-card-content">
                                        <div class="fs-portal-file-card-name"><?php echo esc_html($file->name); ?></div>
                                        <div class="fs-portal-file-card-meta">
                                            <?php if (!empty($file->size)): ?>
                                                <?php echo esc_html($file->size); ?> • 
                                            <?php endif; ?>
                                            <?php if ($file->created_at): ?>
                                                <?php echo  esc_html( date_i18n('M j, Y', strtotime($file->created_at)) ); ?>
                                            <?php endif; ?>
                                            <?php if (!empty($file->category) && $file->category !== 'general'): ?>
                                                • <span class="fs-portal-file-category"><?php echo esc_html(ucfirst(str_replace('_', ' ', $file->category))); ?></span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    <?php if ($has_url): ?>
                                    <div class="fs-portal-file-card-action">
                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                                            <polyline points="7 10 12 15 17 10"/>
                                            <line x1="12" y1="15" x2="12" y2="3"/>
                                        </svg>
                                    </div>
                                    <?php endif; ?>
                                </<?php echo  esc_html( $tag ); ?>>
                                <?php endforeach; ?>
                            </div>
                            <?php else: ?>
                            <div class="fs-portal-empty">
                                <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" style="margin-bottom: 16px; opacity: 0.5;">
                                    <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
                                    <polyline points="14 2 14 8 20 8"/>
                                </svg>
                                <p><?php esc_html_e('No files have been shared yet.', 'freelance-studio'); ?></p>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <!-- Client Upload Section -->
                    <div class="fs-portal-card">
                        <div class="fs-portal-card-header">
                            <h2><?php esc_html_e('Upload Files', 'freelance-studio'); ?></h2>
                        </div>
                        <div class="fs-portal-card-body">
                            <p class="fs-portal-upload-description"><?php esc_html_e('Share files with your designer by uploading them here. All uploaded files will be visible in the project.', 'freelance-studio'); ?></p>
                            
                            <div class="fs-portal-dropzone fs-portal-dropzone-large" id="fs-client-dropzone">
                                <svg class="fs-portal-dropzone-icon" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                                    <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                                    <polyline points="17 8 12 3 7 8"/>
                                    <line x1="12" y1="3" x2="12" y2="15"/>
                                </svg>
                                <p class="fs-portal-dropzone-text"><?php esc_html_e('Drag & drop files here', 'freelance-studio'); ?></p>
                                <p class="fs-portal-dropzone-hint"><?php esc_html_e('or click to select files', 'freelance-studio'); ?></p>
                            </div>
                            <input type="file" id="fs-client-file-input" multiple style="display: none;">
                            <div class="fs-portal-upload-queue" id="fs-client-upload-queue"></div>
                        </div>
                    </div>
                </div>
                
                <?php elseif ($current_tab === 'billing'): ?>
                <!-- Billing Tab -->
                <div class="fs-portal-card">
                    <div class="fs-portal-card-header">
                        <h2><?php esc_html_e('Invoices', 'freelance-studio'); ?></h2>
                    </div>
                    <div class="fs-portal-card-body">
                        <?php if (!empty($invoices)): ?>
                        <table class="fs-portal-table">
                            <thead>
                                <tr>
                                    <th><?php esc_html_e('Invoice', 'freelance-studio'); ?></th>
                                    <th><?php esc_html_e('Date', 'freelance-studio'); ?></th>
                                    <th><?php esc_html_e('Due', 'freelance-studio'); ?></th>
                                    <th><?php esc_html_e('Amount', 'freelance-studio'); ?></th>
                                    <th><?php esc_html_e('Status', 'freelance-studio'); ?></th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($invoices as $invoice): ?>
                                <tr>
                                    <td><strong>#<?php echo esc_html($invoice->invoice_number); ?></strong></td>
                                    <td><?php echo  esc_html( date_i18n('M j, Y', strtotime($invoice->invoice_date)) ); ?></td>
                                    <td class="<?php echo strtotime($invoice->due_date) < time() && !in_array($invoice->status, array('paid')) ? 'fs-text-danger' : ''; ?>">
                                        <?php echo  esc_html( date_i18n('M j, Y', strtotime($invoice->due_date)) ); ?>
                                    </td>
                                    <td><?php echo  esc_html( FS_View_Context::format_currency($invoice->total) ); ?></td>
                                    <td>
                                        <span class="fs-portal-invoice-status fs-status-<?php echo esc_attr($invoice->status); ?>">
                                            <?php echo esc_html(ucfirst($invoice->status)); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php if (!empty($invoice->view_token)): ?>
                                        <a href="<?php echo esc_url(home_url('?fs_invoice=' . $invoice->view_token)); ?>" class="fs-portal-btn fs-portal-btn-small">
                                            <?php esc_html_e('View', 'freelance-studio'); ?>
                                        </a>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                        <?php else: ?>
                        <div class="fs-portal-empty">
                            <p><?php esc_html_e('No invoices for this project yet.', 'freelance-studio'); ?></p>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </main>
        
        <!-- Footer -->
        <footer class="fs-portal-footer">
            <?php /* translators: 1. powered by value */ ?>
            <p><?php echo wp_kses_post( sprintf( __('Powered by %s', 'freelance-studio'), esc_html($business_name))); ?></p>
        </footer>
    </div>
    
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // In-card tab switching (Active/Completed tabs)
        var tabButtons = document.querySelectorAll('.fs-portal-tab[data-tab]');
        tabButtons.forEach(function(tab) {
            tab.addEventListener('click', function() {
                var tabName = this.getAttribute('data-tab');
                var parent = this.closest('.fs-portal-card');
                
                parent.querySelectorAll('.fs-portal-tab[data-tab]').forEach(function(t) {
                    t.classList.remove('active');
                });
                parent.querySelectorAll('.fs-portal-tab-content').forEach(function(c) {
                    c.classList.remove('active');
                });
                
                this.classList.add('active');
                var content = document.getElementById('tab-' + tabName);
                if (content) {
                    content.classList.add('active');
                }
            });
        });
        
        // Client task completion toggle
        var taskToggles = document.querySelectorAll('.fs-portal-task-toggle');
        taskToggles.forEach(function(toggle) {
            toggle.addEventListener('change', function() {
                var taskId = this.dataset.taskId;
                var isChecked = this.checked;
                var taskCard = this.closest('.fs-portal-task-card');
                
                // Optimistic UI update
                if (isChecked) {
                    taskCard.classList.add('completed');
                    taskCard.querySelector('.fs-portal-task-title').classList.add('completed');
                } else {
                    taskCard.classList.remove('completed');
                    taskCard.querySelector('.fs-portal-task-title').classList.remove('completed');
                }
                
                // Send AJAX request
                var formData = new FormData();
                formData.append('action', 'fs_client_toggle_task');
                formData.append('task_id', taskId);
                formData.append('portal_token', '<?php echo esc_js($portal_token); ?>');
                
                fetch('<?php echo  esc_url( admin_url('admin-ajax.php') ); ?>', {
                    method: 'POST',
                    body: formData,
                    credentials: 'same-origin'
                })
                .then(function(response) { return response.json(); })
                .then(function(data) {
                    if (!data.success) {
                        // Revert on error
                        toggle.checked = !isChecked;
                        if (!isChecked) {
                            taskCard.classList.add('completed');
                            taskCard.querySelector('.fs-portal-task-title').classList.add('completed');
                        } else {
                            taskCard.classList.remove('completed');
                            taskCard.querySelector('.fs-portal-task-title').classList.remove('completed');
                        }
                        alert(data.data || 'Error updating task');
                    }
                })
                .catch(function() {
                    // Revert on error
                    toggle.checked = !isChecked;
                    alert('Error updating task');
                });
            });
        });
        
        // Client file upload handling
        var dropzone = document.getElementById('fs-client-dropzone');
        var fileInput = document.getElementById('fs-client-file-input');
        var uploadQueue = document.getElementById('fs-client-upload-queue');
        var projectId = <?php echo intval($project->id); ?>;
        var portalToken = '<?php echo esc_js($portal_token); ?>';
        
        if (dropzone && fileInput) {
            dropzone.addEventListener('click', function() {
                fileInput.click();
            });
            
            dropzone.addEventListener('dragover', function(e) {
                e.preventDefault();
                e.stopPropagation();
                this.classList.add('active');
            });
            
            dropzone.addEventListener('dragleave', function(e) {
                e.preventDefault();
                e.stopPropagation();
                this.classList.remove('active');
            });
            
            dropzone.addEventListener('drop', function(e) {
                e.preventDefault();
                e.stopPropagation();
                this.classList.remove('active');
                handleClientFiles(e.dataTransfer.files);
            });
            
            fileInput.addEventListener('change', function() {
                handleClientFiles(this.files);
                this.value = '';
            });
        }
        
        function handleClientFiles(files) {
            Array.from(files).forEach(function(file) {
                uploadClientFile(file);
            });
        }
        
        function uploadClientFile(file) {
            var item = document.createElement('div');
            item.className = 'fs-portal-upload-item';
            item.innerHTML = '<span class="fs-portal-upload-item-name">' + escapeHtml(file.name) + '</span>' +
                '<span class="fs-portal-upload-item-size">' + formatFileSize(file.size) + '</span>' +
                '<span class="fs-portal-upload-spinner"></span>';
            uploadQueue.appendChild(item);
            
            var formData = new FormData();
            formData.append('action', 'fs_portal_upload_file');
            formData.append('project_id', projectId);
            formData.append('portal_token', portalToken);
            formData.append('file', file);
            
            fetch('<?php echo  esc_url( admin_url('admin-ajax.php') ); ?>', {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            })
            .then(function(response) { return response.json(); })
            .then(function(data) {
                var statusEl = item.querySelector('.fs-portal-upload-spinner');
                if (data.success) {
                    statusEl.outerHTML = '<span class="fs-portal-upload-success">✓</span>';
                    setTimeout(function() { location.reload(); }, 1500);
                } else {
                    statusEl.outerHTML = '<span class="fs-portal-upload-error">✗</span>';
                    item.title = data.data.message || 'Upload failed';
                }
            })
            .catch(function() {
                var statusEl = item.querySelector('.fs-portal-upload-spinner');
                statusEl.outerHTML = '<span class="fs-portal-upload-error">✗</span>';
            });
        }
        
        function escapeHtml(text) {
            var div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
        
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            var k = 1024;
            var sizes = ['Bytes', 'KB', 'MB', 'GB'];
            var i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
    });
    </script>
    
    <!-- Task Request Modal (Project) -->
    <div class="fs-portal-modal-overlay" id="fs-project-task-request-modal" style="display:none;">
        <div class="fs-portal-modal">
            <div class="fs-portal-modal-header">
                <h3><?php esc_html_e('Request a Task', 'freelance-studio'); ?></h3>
                <button type="button" class="fs-portal-modal-close">&times;</button>
            </div>
            <form id="fs-project-task-request-form">
                <input type="hidden" name="project_id" value="<?php echo esc_attr($project->id); ?>">
                <div class="fs-portal-modal-body">
                    <div class="fs-portal-form-group">
                        <label for="fs-proj-task-title"><?php esc_html_e('What do you need?', 'freelance-studio'); ?> <span class="required">*</span></label>
                        <input type="text" id="fs-proj-task-title" name="title" required placeholder="<?php esc_attr_e('e.g., Update homepage banner image', 'freelance-studio'); ?>">
                    </div>
                    <div class="fs-portal-form-group">
                        <label for="fs-proj-task-description"><?php esc_html_e('Details', 'freelance-studio'); ?></label>
                        <textarea id="fs-proj-task-description" name="description" rows="3" placeholder="<?php esc_attr_e('Describe what you need in more detail...', 'freelance-studio'); ?>"></textarea>
                    </div>
                    <div class="fs-portal-form-row">
                        <div class="fs-portal-form-group">
                            <label for="fs-proj-task-priority"><?php esc_html_e('Priority', 'freelance-studio'); ?></label>
                            <select id="fs-proj-task-priority" name="priority">
                                <option value="low"><?php esc_html_e('Low', 'freelance-studio'); ?></option>
                                <option value="medium" selected><?php esc_html_e('Medium', 'freelance-studio'); ?></option>
                                <option value="high"><?php esc_html_e('High', 'freelance-studio'); ?></option>
                                <option value="urgent"><?php esc_html_e('Urgent', 'freelance-studio'); ?></option>
                            </select>
                        </div>
                        <div class="fs-portal-form-group">
                            <label for="fs-proj-task-due-date"><?php esc_html_e('Requested Due Date', 'freelance-studio'); ?></label>
                            <input type="date" id="fs-proj-task-due-date" name="due_date">
                        </div>
                    </div>
                </div>
                <div class="fs-portal-modal-footer">
                    <button type="button" class="fs-portal-btn fs-portal-btn-secondary fs-portal-modal-cancel"><?php esc_html_e('Cancel', 'freelance-studio'); ?></button>
                    <button type="submit" class="fs-portal-btn fs-portal-btn-primary" id="fs-proj-task-submit-btn"><?php esc_html_e('Submit Request', 'freelance-studio'); ?></button>
                </div>
            </form>
        </div>
    </div>
    
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Project Task Request Modal
        var modal = document.getElementById('fs-project-task-request-modal');
        var openBtn = document.getElementById('fs-project-request-task-btn');
        
        if (!modal || !openBtn) return;
        
        var closeEls = modal.querySelectorAll('.fs-portal-modal-close, .fs-portal-modal-cancel');
        
        function openModal() {
            modal.style.display = 'flex';
            document.body.style.overflow = 'hidden';
        }
        
        function closeModal() {
            modal.style.display = 'none';
            document.body.style.overflow = '';
            document.getElementById('fs-project-task-request-form').reset();
        }
        
        openBtn.addEventListener('click', openModal);
        closeEls.forEach(function(el) { el.addEventListener('click', closeModal); });
        modal.addEventListener('click', function(e) { if (e.target === modal) closeModal(); });
        
        // Submit
        var form = document.getElementById('fs-project-task-request-form');
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            
            var submitBtn = document.getElementById('fs-proj-task-submit-btn');
            var origText = submitBtn.textContent;
            submitBtn.disabled = true;
            submitBtn.textContent = '<?php echo esc_js(__('Submitting...', 'freelance-studio')); ?>';
            
            var formData = new FormData(form);
            formData.append('action', 'fs_client_add_task');
            formData.append('portal_token', '<?php echo esc_js($portal_token); ?>');
            
            fetch('<?php echo  esc_url( admin_url('admin-ajax.php') ); ?>', {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            })
            .then(function(response) { return response.json(); })
            .then(function(data) {
                if (data.success) {
                    closeModal();
                    var successMsg = document.createElement('div');
                    successMsg.className = 'fs-portal-success-toast';
                    successMsg.textContent = data.data.message || '<?php echo esc_js(__('Request submitted!', 'freelance-studio')); ?>';
                    document.body.appendChild(successMsg);
                    setTimeout(function() { 
                        successMsg.remove();
                        location.reload();
                    }, 2000);
                } else {
                    alert(data.data || '<?php echo esc_js(__('Error submitting request', 'freelance-studio')); ?>');
                    submitBtn.disabled = false;
                    submitBtn.textContent = origText;
                }
            })
            .catch(function() {
                alert('<?php echo esc_js(__('Error submitting request', 'freelance-studio')); ?>');
                submitBtn.disabled = false;
                submitBtn.textContent = origText;
            });
        });
    });
    </script>
</body>
</html>
