<?php
/**
 * Client Detail View - Dashboard + Tabbed Interface
 *
 * @package Freelance_Studio
 */

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

// Ensure stats has all expected keys with defaults
$stats = wp_parse_args($stats, array(
    'total_revenue' => 0,
    'total_invoiced' => 0,
    'total_paid' => 0,
    'outstanding' => 0,
    'total_projects' => 0,
    'active_projects' => 0
));

// Ensure time summary defaults
$time_summary = $time_summary ?: (object) array(
    'total_seconds' => 0,
    'billable_seconds' => 0,
    'total_billable_amount' => 0,
    'uninvoiced_amount' => 0,
    'rounded_billable_hours' => 0,
);

// Get current tab
$current_tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'overview';
$base_url = admin_url('admin.php?page=fs-clients&action=view&id=' . $client->id);

// Define tabs
$tabs = array(
    'overview' => __('Overview', 'freelance-studio'),
    'address' => __('Address & Contacts', 'freelance-studio'),
    'projects' => __('Projects', 'freelance-studio'),
    'tasks' => __('Tasks', 'freelance-studio'),
    'time' => __('Time Entries', 'freelance-studio'),
    'proposals' => __('Proposals', 'freelance-studio'),
    'invoices' => __('Invoices', 'freelance-studio'),
    'expenses' => __('Expenses', 'freelance-studio'),
    'notes' => __('Notes', 'freelance-studio'),
);

// Get tasks for this client — open tasks only
$task_sort = isset($_GET['task_sort']) ? sanitize_text_field($_GET['task_sort']) : 'due_date';
$task_order = isset($_GET['task_order']) ? strtoupper(sanitize_text_field($_GET['task_order'])) : 'ASC';
if (!in_array($task_order, array('ASC', 'DESC'))) $task_order = 'ASC';
$valid_sorts = array('title', 'priority', 'status', 'due_date', 'client_name');
if (!in_array($task_sort, $valid_sorts)) $task_sort = 'due_date';

$client_tasks = FS_Task::get_all(array(
    'client_id' => $client->id,
    'smart_recurring' => true,
    'exclude_archived' => true,
    'status' => array('pending', 'in_progress', 'needs_info', 'with_client', 'requested'),
    'orderby' => $task_sort,
    'order' => $task_order,
));
$task_counts = FS_Task::count_by_client($client->id);

// Get expenses for this client's projects
$client_expenses = array();
if (!empty($projects)) {
    foreach ($projects as $project) {
        $project_expenses = FS_Expense::get_all(array('project_id' => $project->id));
        $client_expenses = array_merge($client_expenses, $project_expenses);
    }
}

// Get proposals for this client
$client_proposals = isset($proposals) ? $proposals : FS_Proposal::get_by_client($client->id);

// Get display name and primary contact
$display_name = FS_Client::get_display_name($client);
$primary_contact = FS_Client::get_primary_contact($client);

// Prepare data for overview tab
$recent_projects = array_slice($projects, 0, 3);
$recent_invoices = array_slice($invoices, 0, 5);
$active_proposals = array_filter($client_proposals, function($p) {
    return in_array($p->status, array('draft', 'sent', 'viewed'));
});
$active_contracts = isset($contracts) ? array_filter($contracts, function($c) {
    return in_array($c->status, array('draft', 'sent', 'viewed'));
}) : array();

// Total hours
$total_hours = $time_summary->total_seconds ? round($time_summary->total_seconds / 3600, 1) : 0;
$billable_hours = $time_summary->rounded_billable_hours ? round($time_summary->rounded_billable_hours, 1) : 0;

// Build monthly earnings chart data (last 12 months)
$chart_labels = array();
$chart_data = array();
$monthly_map = array();
if (!empty($monthly_earnings)) {
    foreach ($monthly_earnings as $row) {
        $monthly_map[$row->month] = floatval($row->total);
    }
}
for ($i = 11; $i >= 0; $i--) {
    $month_key = date('Y-m', strtotime("-{$i} months"));
    $chart_labels[] = date('M \'y', strtotime("-{$i} months"));
    $chart_data[] = isset($monthly_map[$month_key]) ? $monthly_map[$month_key] : 0;
}
?>

<div class="wrap fs-wrap">
    <!-- Client Profile Header -->
    <div class="fs-client-profile-header">
        <div class="fs-client-profile-info">
            <?php $client_logo = FS_Client::get_logo_url($client->id, 'medium'); ?>
            <?php if ($client_logo): ?>
                <img src="<?php echo esc_url($client_logo); ?>" alt="" class="fs-client-profile-logo">
            <?php else: ?>
                <div class="fs-client-profile-avatar">
                    <?php echo esc_html(strtoupper(substr($display_name, 0, 2))); ?>
                </div>
            <?php endif; ?>
            <div class="fs-client-profile-details">
                <h1 class="fs-client-profile-name"><?php echo esc_html($display_name); ?></h1>
                <div class="fs-client-profile-meta">
                    <?php if ($primary_contact && !empty($primary_contact->email)): ?>
                        <span class="fs-client-meta-item">
                            <span class="dashicons dashicons-email-alt"></span>
                            <a href="mailto:<?php echo esc_attr($primary_contact->email); ?>"><?php echo esc_html($primary_contact->email); ?></a>
                        </span>
                    <?php elseif (!empty($client->email)): ?>
                        <span class="fs-client-meta-item">
                            <span class="dashicons dashicons-email-alt"></span>
                            <a href="mailto:<?php echo esc_attr($client->email); ?>"><?php echo esc_html($client->email); ?></a>
                        </span>
                    <?php endif; ?>
                    <?php if (!empty($client->phone)): ?>
                        <span class="fs-client-meta-item">
                            <span class="dashicons dashicons-phone"></span>
                            <?php echo esc_html($client->phone); ?>
                        </span>
                    <?php endif; ?>
                    <?php if (!empty($client->website)): ?>
                        <span class="fs-client-meta-item">
                            <span class="dashicons dashicons-admin-site-alt3"></span>
                            <a href="<?php echo esc_url($client->website); ?>" target="_blank"><?php echo esc_html(preg_replace('#^https?://#', '', $client->website)); ?></a>
                        </span>
                    <?php endif; ?>
                    <?php
                    $address_parts = array_filter(array($client->city, $client->state, $client->country));
                    if (!empty($address_parts)):
                    ?>
                        <span class="fs-client-meta-item">
                            <span class="dashicons dashicons-location"></span>
                            <?php echo esc_html(implode(', ', $address_parts)); ?>
                        </span>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <div class="fs-client-profile-actions">
            <a href="<?php echo esc_url( admin_url('admin.php?page=fs-clients') ); ?>" class="fs-btn fs-btn-secondary">
                <span class="dashicons dashicons-arrow-left-alt2"></span> <?php esc_html_e('All Clients', 'freelance-studio'); ?>
            </a>
            <a href="<?php echo esc_url( admin_url('admin.php?page=fs-clients&action=edit&id=' . $client->id) ); ?>" class="fs-btn fs-btn-primary">
                <span class="dashicons dashicons-edit"></span> <?php esc_html_e('Edit Client', 'freelance-studio'); ?>
            </a>
        </div>
    </div>

    <!-- Tab Navigation -->
    <nav class="fs-tab-nav">
        <?php foreach ($tabs as $tab_id => $tab_label): ?>
            <a href="<?php echo esc_url(add_query_arg('tab', $tab_id, $base_url)); ?>" 
               class="fs-tab-link <?php echo $current_tab === $tab_id ? 'active' : ''; ?>">
                <?php echo esc_html($tab_label); ?>
            </a>
        <?php endforeach; ?>
    </nav>
    
    <!-- Tab Content -->
    <div class="fs-tab-content">
        
        <?php if ($current_tab === 'overview'): ?>

            <!-- Stats + Quick Actions Row -->
            <div class="fs-client-top-row">
                <div class="fs-client-stats-row">
                    <div class="fs-client-stat-card">
                        <div class="fs-client-stat-value"><?php echo FS_View_Context::format_currency($stats['total_paid']); ?></div>
                        <div class="fs-client-stat-label"><?php esc_html_e('Total Earned', 'freelance-studio'); ?></div>
                    </div>
                    <div class="fs-client-stat-card">
                        <div class="fs-client-stat-value"><?php echo FS_View_Context::format_currency($stats['outstanding']); ?></div>
                        <div class="fs-client-stat-label"><?php esc_html_e('Outstanding', 'freelance-studio'); ?></div>
                    </div>
                    <div class="fs-client-stat-card">
                        <div class="fs-client-stat-value"><?php echo number_format($billable_hours, 1); ?>h</div>
                        <div class="fs-client-stat-label"><?php esc_html_e('Billable Hours', 'freelance-studio'); ?></div>
                    </div>
                    <div class="fs-client-stat-card">
                        <div class="fs-client-stat-value"><?php echo intval($stats['total_projects']); ?></div>
                        <div class="fs-client-stat-label"><?php esc_html_e('Projects', 'freelance-studio'); ?></div>
                    </div>
                    <div class="fs-client-stat-card">
                        <div class="fs-client-stat-value"><?php echo intval($stats['active_projects']); ?></div>
                        <div class="fs-client-stat-label"><?php esc_html_e('Active', 'freelance-studio'); ?></div>
                    </div>
                </div>
                <div class="fs-dashboard-card fs-client-qa-card">
                    <div class="fs-quick-actions">
                        <a href="<?php echo esc_url( admin_url('admin.php?page=fs-projects&action=add&client_id=' . $client->id) ); ?>" class="fs-quick-action">
                            <span class="dashicons dashicons-portfolio"></span>
                            <span><?php esc_html_e('New Project', 'freelance-studio'); ?></span>
                        </a>
                        <a href="<?php echo esc_url( admin_url('admin.php?page=fs-finances&tab=invoices&action=add&client_id=' . $client->id) ); ?>" class="fs-quick-action">
                            <span class="dashicons dashicons-media-spreadsheet"></span>
                            <span><?php esc_html_e('New Invoice', 'freelance-studio'); ?></span>
                        </a>
                        <a href="<?php echo esc_url( admin_url('admin.php?page=fs-proposals&action=add&client_id=' . $client->id) ); ?>" class="fs-quick-action">
                            <span class="dashicons dashicons-media-document"></span>
                            <span><?php esc_html_e('New Proposal', 'freelance-studio'); ?></span>
                        </a>
                        <a href="<?php echo esc_url( admin_url('admin.php?page=fs-contracts&action=add&client_id=' . $client->id) ); ?>" class="fs-quick-action">
                            <span class="dashicons dashicons-clipboard"></span>
                            <span><?php esc_html_e('New Contract', 'freelance-studio'); ?></span>
                        </a>
                    </div>
                </div>
            </div>

            <!-- Dashboard Layout: 2/3 + 1/3 -->
            <div class="fs-dashboard-layout">
                <div class="fs-dashboard-main">

                    <!-- Open Tasks -->
                    <div class="fs-dashboard-card">
                        <div class="fs-card-header-row">
                            <h3><?php esc_html_e('Open Tasks', 'freelance-studio'); ?>
                                <?php if (!empty($client_tasks)): ?>
                                    <span class="fs-badge-count"><?php echo count($client_tasks); ?></span>
                                <?php endif; ?>
                            </h3>
                            <button type="button" class="fs-btn fs-btn-primary fs-btn-small" id="fs-client-overview-add-task">
                                <span class="dashicons dashicons-plus-alt2"></span> <?php esc_html_e('New Task', 'freelance-studio'); ?>
                            </button>
                        </div>
                        <ul class="fs-task-list" id="fs-client-dashboard-tasks">
                            <?php if (!empty($client_tasks)):
                                $display_tasks = array_slice($client_tasks, 0, 10);
                                foreach ($display_tasks as $task):
                                    $is_overdue = $task->due_date && strtotime($task->due_date) < strtotime('today');
                            ?>
                            <li class="fs-task-item" data-task-id="<?php echo $task->id; ?>">
                                <label class="fs-task-checkbox">
                                    <input type="checkbox" class="fs-toggle-task" data-id="<?php echo $task->id; ?>">
                                    <span class="fs-checkmark"></span>
                                </label>
                                <div class="fs-task-info">
                                    <span class="fs-task-title"><?php echo esc_html($task->title); ?></span>
                                </div>
                                <div class="fs-task-meta">
                                    <?php if ($task->due_date): ?><span class="fs-task-due <?php echo $is_overdue ? 'overdue' : ''; ?>"><?php echo date('M j', strtotime($task->due_date)); ?></span><?php endif; ?>
                                    <?php if ($is_overdue): ?><span class="fs-status-badge status-overdue"><?php esc_html_e('Overdue', 'freelance-studio'); ?></span><?php endif; ?>
                                    <?php if (!empty($task->project_name)): ?><span class="fs-task-project"><?php echo esc_html($task->project_name); ?></span><?php endif; ?>
                                </div>
                            </li>
                            <?php endforeach; else: ?>
                                <li class="fs-empty-message"><?php esc_html_e('No open tasks.', 'freelance-studio'); ?></li>
                            <?php endif; ?>
                        </ul>
                        <div class="fs-card-footer"><a href="<?php echo esc_url(add_query_arg('tab', 'tasks', $base_url)); ?>"><?php esc_html_e('View All', 'freelance-studio'); ?> →</a></div>
                    </div>

                    <!-- Recent Invoices -->
                    <div class="fs-dashboard-card">
                        <div class="fs-card-header-row">
                            <h3><?php esc_html_e('Recent Invoices', 'freelance-studio'); ?></h3>
                            <?php if (count($invoices) > 5): ?>
                            <a href="<?php echo esc_url(add_query_arg('tab', 'invoices', $base_url)); ?>" class="fs-card-link"><?php esc_html_e('View All', 'freelance-studio'); ?> →</a>
                            <?php endif; ?>
                        </div>
                        <?php if (!empty($recent_invoices)): ?>
                        <table class="fs-table fs-compact-table widefat">
                            <thead><tr>
                                <th><?php esc_html_e('Invoice', 'freelance-studio'); ?></th>
                                <th><?php esc_html_e('Status', 'freelance-studio'); ?></th>
                                <th class="text-right"><?php esc_html_e('Amount', 'freelance-studio'); ?></th>
                                <th class="text-right"><?php esc_html_e('Date', 'freelance-studio'); ?></th>
                            </tr></thead>
                            <tbody>
                            <?php foreach ($recent_invoices as $invoice): ?>
                                <tr>
                                    <td><a href="<?php echo esc_url( admin_url('admin.php?page=fs-finances&tab=invoices&action=edit&id=' . $invoice->id) ); ?>" class="fs-link-primary">#<?php echo esc_html($invoice->invoice_number); ?></a></td>
                                    <td><?php echo wp_kses_post( FS_View_Context::status_badge($invoice->status) ); ?></td>
                                    <td class="text-right"><?php echo FS_View_Context::format_currency($invoice->total); ?></td>
                                    <td class="text-right"><?php echo $invoice->invoice_date ? FS_View_Context::format_date($invoice->invoice_date) : '—'; ?></td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                        <?php else: ?>
                        <p class="fs-empty-card-message"><?php esc_html_e('No invoices yet.', 'freelance-studio'); ?></p>
                        <?php endif; ?>
                    </div>

                    <!-- Earnings Chart -->
                    <div class="fs-dashboard-card">
                        <div class="fs-card-header-row">
                            <h3><?php esc_html_e('Earnings (Last 12 Months)', 'freelance-studio'); ?></h3>
                        </div>
                        <?php if (array_sum($chart_data) > 0): ?>
                        <div class="fs-chart-container"><canvas id="fs-client-earnings-chart" height="260"></canvas></div>
                        <?php else: ?>
                        <p class="fs-empty-card-message"><?php esc_html_e('No payment data yet.', 'freelance-studio'); ?></p>
                        <?php endif; ?>
                    </div>

                </div>

                <!-- Sidebar -->
                <div class="fs-dashboard-sidebar">

                    <!-- Recent Projects (compact) -->
                    <div class="fs-dashboard-card">
                        <div class="fs-card-header-row">
                            <h3><?php esc_html_e('Recent Projects', 'freelance-studio'); ?></h3>
                            <?php if (count($projects) > 3): ?>
                            <a href="<?php echo esc_url(add_query_arg('tab', 'projects', $base_url)); ?>" class="fs-card-link"><?php esc_html_e('All', 'freelance-studio'); ?> →</a>
                            <?php endif; ?>
                        </div>
                        <?php if (!empty($recent_projects)): ?>
                        <ul class="fs-simple-list">
                            <?php foreach ($recent_projects as $project): ?>
                            <li>
                                <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>
                                <?php echo wp_kses_post( FS_View_Context::status_badge($project->status) ); ?>
                            </li>
                            <?php endforeach; ?>
                        </ul>
                        <?php else: ?>
                        <p class="fs-empty-card-message"><?php esc_html_e('No projects yet.', 'freelance-studio'); ?></p>
                        <?php endif; ?>
                    </div>

                    <!-- Pending Documents -->
                    <?php if (!empty($active_proposals) || !empty($active_contracts)): ?>
                    <div class="fs-dashboard-card">
                        <div class="fs-card-header-row">
                            <h3><?php esc_html_e('Pending Documents', 'freelance-studio'); ?></h3>
                        </div>
                        <ul class="fs-simple-list">
                            <?php foreach ($active_proposals as $proposal): ?>
                            <li>
                                <a href="<?php echo esc_url( admin_url('admin.php?page=fs-proposals&action=edit&id=' . $proposal->id) ); ?>">
                                    <span class="dashicons dashicons-format-aside"></span>
                                    <?php echo esc_html($proposal->title ?: __('Proposal', 'freelance-studio') . ' #' . $proposal->id); ?>
                                </a>
                                <?php echo wp_kses_post( FS_View_Context::status_badge($proposal->status) ); ?>
                            </li>
                            <?php endforeach; ?>
                            <?php foreach ($active_contracts as $contract): ?>
                            <li>
                                <a href="<?php echo esc_url( admin_url('admin.php?page=fs-contracts&action=edit&id=' . $contract->id) ); ?>">
                                    <span class="dashicons dashicons-media-document"></span>
                                    <?php echo esc_html($contract->title ?: __('Contract', 'freelance-studio') . ' #' . $contract->id); ?>
                                </a>
                                <?php echo wp_kses_post( FS_View_Context::status_badge($contract->status) ); ?>
                            </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                    <?php endif; ?>

                    <!-- Client Notes -->
                    <div class="fs-dashboard-card">
                        <div class="fs-card-header-row">
                            <h3><?php esc_html_e('Notes', 'freelance-studio'); ?></h3>
                            <a href="<?php echo esc_url(add_query_arg('tab', 'notes', $base_url)); ?>" class="fs-card-link"><?php esc_html_e('Edit', 'freelance-studio'); ?></a>
                        </div>
                        <?php if (!empty($client->notes)): ?>
                            <div class="fs-client-notes-preview"><?php echo wp_kses_post(wpautop($client->notes)); ?></div>
                        <?php else: ?>
                            <p class="fs-empty-card-message"><?php esc_html_e('No notes yet.', 'freelance-studio'); ?></p>
                        <?php endif; ?>
                    </div>

                    <!-- Client Portal -->
                    <?php
                    $portal_url = FS_Client::get_portal_url($client->id);
                    if ($client->portal_enabled && $portal_url):
                    ?>
                    <div class="fs-dashboard-card">
                        <div class="fs-card-header-row">
                            <h3><?php esc_html_e('Client Portal', 'freelance-studio'); ?></h3>
                        </div>
                        <div class="fs-link-copy-group fs-link-copy-compact">
                            <input type="text" readonly class="fs-copy-link" value="<?php echo esc_url($portal_url); ?>" id="fs-portal-link-overview">
                            <button type="button" class="fs-btn fs-btn-secondary fs-btn-small" onclick="navigator.clipboard.writeText(document.getElementById('fs-portal-link-overview').value); this.textContent='<?php esc_html_e('Copied!', 'freelance-studio'); ?>';">
                                <?php esc_html_e('Copy', 'freelance-studio'); ?>
                            </button>
                        </div>
                    </div>
                    <?php endif; ?>

                </div>
            </div>

            <!-- Earnings Chart Script -->
            <?php if (array_sum($chart_data) > 0): ?>
            <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
            <script>
            document.addEventListener('DOMContentLoaded', function() {
                var ctx = document.getElementById('fs-client-earnings-chart');
                if (!ctx) return;
                new Chart(ctx, {
                    type: 'bar',
                    data: {
                        labels: <?php echo json_encode($chart_labels); ?>,
                        datasets: [{
                            label: '<?php echo esc_js(__('Earnings', 'freelance-studio')); ?>',
                            data: <?php echo json_encode($chart_data); ?>,
                            backgroundColor: 'rgba(62, 207, 178, 0.3)',
                            borderColor: '#3ECFB2',
                            borderWidth: 2,
                            borderRadius: 6,
                            maxBarThickness: 40,
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: { display: false },
                            tooltip: {
                                callbacks: {
                                    label: function(context) {
                                        return '$' + context.parsed.y.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});
                                    }
                                }
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                grid: { color: '#f0f0f0' },
                                ticks: { callback: function(v) { return '$' + v.toLocaleString(); } }
                            },
                            x: {
                                grid: { display: false },
                                ticks: { maxRotation: 45, font: { size: 11 } }
                            }
                        }
                    }
                });
            });
            </script>
            <?php endif; ?>

            <script>
            jQuery(document).ready(function($) {
                var ajaxNonce = '<?php echo wp_create_nonce('fs_ajax_nonce'); ?>';
                $('#fs-client-dashboard-tasks').on('change', '.fs-toggle-task', function() {
                    var $cb = $(this), taskId = $cb.data('id');
                    var newStatus = $cb.is(':checked') ? 'completed' : 'pending';
                    $.post(ajaxurl, { action: 'fs_update_task_status', task_id: taskId, status: newStatus, nonce: ajaxNonce }, function(r) {
                        if (r.success && newStatus === 'completed') {
                            $cb.closest('.fs-task-item').fadeOut(300, function() { $(this).remove(); });
                        }
                    });
                });

                // New Task button on overview - opens task modal with client pre-selected
                $('#fs-client-overview-add-task').on('click', function() {
                    if (typeof openTaskModal === 'function') {
                        openTaskModal();
                        // Pre-select this client in the modal
                        setTimeout(function() {
                            var $clientField = $('#task-modal-client-id, #task-client-id');
                            if ($clientField.length) {
                                $clientField.val('<?php echo intval($client->id); ?>').trigger('change');
                            }
                        }, 100);
                    }
                });
            });
            </script>

<?php endif; // end overview tab ?>

<?php
// Include all other existing tab content (address, projects, tasks, time, proposals, invoices, expenses, notes)
include JEEB_FS_PLUGIN_DIR . 'includes/views/clients/view-tabs.php';
?>

    </div>
</div>
