<?php
/**
 * Reporting View
 *
 * @package Freelance_Studio
 */

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

$months = array(
    1 => 'Jan', 2 => 'Feb', 3 => 'Mar', 4 => 'Apr',
    5 => 'May', 6 => 'Jun', 7 => 'Jul', 8 => 'Aug',
    9 => 'Sep', 10 => 'Oct', 11 => 'Nov', 12 => 'Dec'
);

$internal_tracking_enabled = get_option('fs_internal_tracking_enabled', '0') === '1';
$include_internal = isset($_GET['include_internal']) ? $_GET['include_internal'] === '1' : true;
?>

<?php if (empty($GLOBALS['fs_in_finances'])): ?>
<div class="wrap fs-wrap">
<?php endif; ?>
    <h1><?php esc_html_e('Reporting', 'freelance-studio'); ?></h1>
    
    <!-- Year Filter -->
    <div class="fs-year-filter">
        <form method="get">
            <input type="hidden" name="page" value="fs-finances">
            <input type="hidden" name="tab" value="reporting">
            <label for="year"><?php esc_html_e('Year:', 'freelance-studio'); ?></label>
            <select name="year" id="year" onchange="this.form.submit()">
                <?php foreach ($available_years as $year): ?>
                    <option value="<?php echo  esc_attr( $year ); ?>" <?php selected($selected_year, $year); ?>><?php echo  esc_attr( $year ); ?></option>
                <?php endforeach; ?>
            </select>
            <?php if ($internal_tracking_enabled): ?>
                &nbsp;&nbsp;
                <label>
                    <input type="checkbox" name="include_internal" value="1" <?php checked($include_internal); ?> onchange="this.form.submit()">
                    <?php esc_html_e('Include internal projects', 'freelance-studio'); ?>
                </label>
            <?php endif; ?>
        </form>
    </div>
    
    <!-- Summary Cards -->
    <div class="fs-report-summary">
        <div class="fs-report-card">
            <div class="label"><?php esc_html_e('Total Income', 'freelance-studio'); ?></div>
            <div class="value positive">$<?php echo number_format($total_income, 2); ?></div>
        </div>
        
        <div class="fs-report-card">
            <div class="label"><?php esc_html_e('Total Expenses', 'freelance-studio'); ?></div>
            <div class="value negative">$<?php echo number_format($total_expenses, 2); ?></div>
        </div>
        
        <div class="fs-report-card">
            <div class="label"><?php esc_html_e('Net Profit', 'freelance-studio'); ?></div>
            <div class="value <?php echo $net_profit >= 0 ? 'positive' : 'negative'; ?>">$<?php echo number_format($net_profit, 2); ?></div>
        </div>
        
        <?php if ( ! function_exists( 'fs_studio_is_free_plan' ) || ! fs_studio_is_free_plan() ): ?>
        <div class="fs-report-card">
            <div class="label"><?php esc_html_e('Estimated Tax', 'freelance-studio'); ?></div>
            <div class="value">$<?php echo number_format($tax_data['quarterly_total_estimated'], 2); ?></div>
        </div>
        <?php endif; ?>
    </div>
    
    <div class="fs-report-grid">

        <!-- ===== LEFT COLUMN: Charts + Tax ===== -->
        <div class="fs-report-main">

        <!-- Monthly Income/Expense -->
        <div class="fs-report-section fs-chart-section">
            <h2><?php esc_html_e('Monthly Income vs Expenses', 'freelance-studio'); ?></h2>
            <div class="fs-chart-container">
                <canvas id="fs-income-expense-chart"></canvas>
            </div>
        </div>

        <!-- Income by Client (line chart) -->
        <div class="fs-report-section fs-chart-section">
            <h2><?php esc_html_e('Income by Client', 'freelance-studio'); ?></h2>
            <?php if (empty($client_income_by_month)): ?>
                <p class="text-muted"><?php esc_html_e('No paid invoices for this period.', 'freelance-studio'); ?></p>
            <?php else: ?>
                <div class="fs-chart-container">
                    <canvas id="fs-client-income-chart"></canvas>
                </div>
            <?php endif; ?>
        </div>

        <!-- Tax Section (moved to Finances > Tax) -->
        <div class="fs-report-section">
            <h2><?php esc_html_e('Tax Summary', 'freelance-studio'); ?></h2>
            <p class="description"><?php esc_html_e('Tax estimates, deductions, and quarterly payment tracking have moved to their own dedicated page.', 'freelance-studio'); ?></p>
            <a href="<?php echo esc_url(admin_url('admin.php?page=fs-finances&tab=tax&year=' . $selected_year)); ?>" class="fs-btn fs-btn-primary fs-btn-small" style="margin-top:10px;">
                <?php esc_html_e('View Tax Planning', 'freelance-studio'); ?>
            </a>
        </div>

        </div><!-- /.fs-report-main (left column) -->

        <!-- ===== RIGHT COLUMN: Sidebar Stack ===== -->
        <div class="fs-report-sidebar-stack">

        <!-- Expense Categories -->
        <div class="fs-report-section">
            <h2><?php esc_html_e('Expenses by Category', 'freelance-studio'); ?></h2>
            <?php if (empty($expense_categories)): ?>
                <p class="text-muted"><?php esc_html_e('No expenses recorded for this period.', 'freelance-studio'); ?></p>
            <?php else: ?>
                <table class="fs-table fs-table-borderless">
                    <thead>
                        <tr>
                            <th class="fs-col-no-pad-left"><?php esc_html_e('Category', 'freelance-studio'); ?></th>
                            <th class="text-right"><?php esc_html_e('Amount', 'freelance-studio'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($expense_categories as $cat): ?>
                            <tr>
                                <td class="fs-col-no-pad-left"><?php echo esc_html($cat->category); ?></td>
                                <td class="text-right">$<?php echo number_format($cat->total, 2); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>

        <!-- Top Clients -->
        <div class="fs-report-section">
            <h2><?php esc_html_e('Top Clients', 'freelance-studio'); ?></h2>
            <?php if (empty($top_clients)): ?>
                <p class="text-muted"><?php esc_html_e('No paid invoices for this period.', 'freelance-studio'); ?></p>
            <?php else: ?>
                <table class="fs-table fs-table-borderless">
                    <thead>
                        <tr>
                            <th class="fs-col-no-pad-left"><?php esc_html_e('Client', 'freelance-studio'); ?></th>
                            <th class="text-right"><?php esc_html_e('Revenue', 'freelance-studio'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($top_clients as $client): ?>
                            <tr>
                                <td class="fs-col-no-pad-left">
                                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-clients&action=view&id=' . $client->id) ); ?>">
                                        <?php echo esc_html($client->company_name ?: $client->name); ?>
                                    </a>
                                </td>
                                <td class="text-right">$<?php echo number_format($client->total_revenue, 2); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>

        <!-- Export & Reports -->
        <div class="fs-report-section fs-export-sidebar">
            <h2><?php esc_html_e('Export & Reports', 'freelance-studio'); ?></h2>
            <?php if ( function_exists( 'fs_studio_is_free_plan' ) && fs_studio_is_free_plan() ): ?>
            <div class="fs-pro-overlay-wrapper fs-pro-overlay-compact">
                <div class="fs-pro-overlay">
                    <div class="fs-pro-overlay-content">
                        <span class="fs-upgrade-badge">PRO</span>
                        <p><?php esc_html_e( 'Report exports are available with Freelance Studio Pro.', 'freelance-studio' ); ?></p>
                        <a href="<?php echo function_exists( 'freelance_studio_fs' ) ? esc_url( freelance_studio_fs()->get_upgrade_url() ) : '#'; ?>" class="fs-btn fs-btn-primary fs-btn-small">
                            <?php esc_html_e( 'Upgrade to Pro', 'freelance-studio' ); ?>
                        </a>
                    </div>
                </div>
                <div class="fs-export-sidebar-group" aria-hidden="true">
                    <h4><?php esc_html_e('Data Exports (CSV)', 'freelance-studio'); ?></h4>
                    <span class="fs-btn fs-btn-secondary fs-btn-small" style="pointer-events:none;opacity:0.5;">
                        <span class="dashicons dashicons-media-spreadsheet"></span> <?php esc_html_e('Invoices', 'freelance-studio'); ?>
                    </span>
                    <span class="fs-btn fs-btn-secondary fs-btn-small" style="pointer-events:none;opacity:0.5;">
                        <span class="dashicons dashicons-media-spreadsheet"></span> <?php esc_html_e('Expenses', 'freelance-studio'); ?>
                    </span>
                </div>
                <div class="fs-export-sidebar-group" aria-hidden="true">
                    <h4><?php esc_html_e('Tax Reports (PDF)', 'freelance-studio'); ?></h4>
                    <span class="fs-btn fs-btn-secondary fs-btn-small" style="pointer-events:none;opacity:0.5;">
                        <span class="dashicons dashicons-pdf"></span> <?php esc_html_e('Annual Summary', 'freelance-studio'); ?>
                    </span>
                </div>
            </div>
            <?php else: ?>
            <div class="fs-export-sidebar-group">
                <h4><?php esc_html_e('Data Exports (CSV)', 'freelance-studio'); ?></h4>
                <button type="button" class="fs-btn fs-btn-secondary fs-btn-small fs-export-btn" data-type="invoices" data-year="<?php echo  esc_attr( $selected_year ); ?>">
                    <span class="dashicons dashicons-media-spreadsheet"></span> <?php esc_html_e('Invoices', 'freelance-studio'); ?>
                </button>
                <button type="button" class="fs-btn fs-btn-secondary fs-btn-small fs-export-btn" data-type="expenses" data-year="<?php echo  esc_attr( $selected_year ); ?>">
                    <span class="dashicons dashicons-media-spreadsheet"></span> <?php esc_html_e('Expenses', 'freelance-studio'); ?>
                </button>
                <button type="button" class="fs-btn fs-btn-secondary fs-btn-small fs-export-btn" data-type="time_entries" data-year="<?php echo  esc_attr( $selected_year ); ?>">
                    <span class="dashicons dashicons-media-spreadsheet"></span> <?php esc_html_e('Time Entries', 'freelance-studio'); ?>
                </button>
                <button type="button" class="fs-btn fs-btn-secondary fs-btn-small fs-export-btn" data-type="clients" data-year="<?php echo  esc_attr( $selected_year ); ?>">
                    <span class="dashicons dashicons-media-spreadsheet"></span> <?php esc_html_e('Clients', 'freelance-studio'); ?>
                </button>
            </div>
            <div class="fs-export-sidebar-group">
                <h4><?php esc_html_e('Tax Reports', 'freelance-studio'); ?></h4>
                <button type="button" class="fs-btn fs-btn-secondary fs-btn-small" id="fs-generate-1099-pdf" data-year="<?php echo  esc_attr( $selected_year ); ?>">
                    <span class="dashicons dashicons-pdf"></span> <?php esc_html_e('Income Summary (PDF)', 'freelance-studio'); ?>
                </button>
                <button type="button" class="fs-btn fs-btn-secondary fs-btn-small fs-export-btn" data-type="income_summary" data-year="<?php echo  esc_attr( $selected_year ); ?>">
                    <span class="dashicons dashicons-media-spreadsheet"></span> <?php esc_html_e('Income Summary (CSV)', 'freelance-studio'); ?>
                </button>
            </div>
            <p class="description">
                <?php /* translators: 1. count/number */ ?>
                <?php echo esc_html( sprintf( __( 'Income summary shows payments received from each client in %d for your tax records.', 'freelance-studio'), $selected_year) ); ?>
            </p>
            <?php endif; // end premium gate ?>
        </div>
        </div><!-- /.fs-report-sidebar-stack -->

    </div><!-- /.fs-report-grid -->
<?php if (empty($GLOBALS['fs_in_finances'])): ?>
</div>
<?php endif; ?>

<?php // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript, PluginCheck.CodeAnalysis.Offloading.OffloadedContent -- Chart.js loaded on reporting page only; no local alternative bundled. ?>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
<script>
jQuery(document).ready(function($) {
    // Freelance Studio color palette
    var fsColors = {
        primary: '#1FBBA6',
        primaryDark: '#2BA891',
        primaryLight: '#77D5C9',
        secondary: '#81A5DF',
        secondaryDark: '#5D4E80',
        accent: '#FFA26E',
        highlight: '#D2E768',
        pink: '#F2B6F6',
        danger: '#E85A5A',
        info: '#7B68A6'
    };
    
    // Chart color arrays using site colors
    var chartColors = [
        fsColors.primary,
        fsColors.accent,
        fsColors.secondary,
        fsColors.highlight,
        fsColors.pink,
        fsColors.primaryDark,
        fsColors.info,
        fsColors.primaryLight,
        fsColors.secondaryDark,
        fsColors.danger
    ];
    
    // Monthly Income vs Expenses - Bar Chart (split at 0)
    var incomeExpenseCtx = document.getElementById('fs-income-expense-chart');
    if (incomeExpenseCtx) {
        var incomeData = <?php echo json_encode(array_column($income_data, 'total')); ?>;
        var expenseData = <?php echo json_encode(array_column($expense_data, 'total')); ?>;
        // Make expenses negative for display below zero line
        var negativeExpenseData = expenseData.map(function(val) { return -val; });
        var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
        
        new Chart(incomeExpenseCtx, {
            type: 'bar',
            data: {
                labels: months,
                datasets: [
                    {
                        label: '<?php esc_html_e('Income', 'freelance-studio'); ?>',
                        data: incomeData,
                        backgroundColor: fsColors.primary,
                        borderRadius: 4
                    },
                    {
                        label: '<?php esc_html_e('Expenses', 'freelance-studio'); ?>',
                        data: negativeExpenseData,
                        backgroundColor: fsColors.accent,
                        borderRadius: 4
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'top',
                        labels: {
                            usePointStyle: true,
                            padding: 20
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                var value = Math.abs(context.raw);
                                return context.dataset.label + ': $' + value.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
                            }
                        }
                    }
                },
                scales: {
                    x: {
                        grid: {
                            display: false
                        }
                    },
                    y: {
                        ticks: {
                            callback: function(value) {
                                return '$' + Math.abs(value).toLocaleString();
                            }
                        },
                        grid: {
                            color: function(context) {
                                if (context.tick.value === 0) {
                                    return '#374151';
                                }
                                return 'rgba(0,0,0,0.1)';
                            },
                            lineWidth: function(context) {
                                if (context.tick.value === 0) {
                                    return 2;
                                }
                                return 1;
                            }
                        }
                    }
                }
            }
        });
    }
    
    // Annual Deductions by Category - Interactive Pie Chart
    var deductionsPieCtx = document.getElementById('fs-deductions-pie-chart');
    if (deductionsPieCtx) {
        <?php 
        $deduction_labels = array();
        $deduction_values = array();
        $deduction_counts = array();
        if (!empty($tax_data['annual_deduction_details'])) {
            foreach ($tax_data['annual_deduction_details'] as $cat) {
                $deduction_labels[] = $cat->category;
                $deduction_values[] = floatval($cat->total);
                $deduction_counts[] = intval($cat->count);
            }
        }
        ?>
        var deductionLabels = <?php echo json_encode($deduction_labels); ?>;
        var deductionValues = <?php echo json_encode($deduction_values); ?>;
        var deductionCounts = <?php echo json_encode($deduction_counts); ?>;
        var totalDeductions = deductionValues.reduce(function(a, b) { return a + b; }, 0);
        
        var pieChart = new Chart(deductionsPieCtx, {
            type: 'doughnut',
            data: {
                labels: deductionLabels,
                datasets: [{
                    data: deductionValues,
                    backgroundColor: chartColors.slice(0, deductionLabels.length),
                    borderWidth: 2,
                    borderColor: '#fff',
                    hoverOffset: 8
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                var value = context.raw;
                                var percentage = ((value / totalDeductions) * 100).toFixed(1);
                                var count = deductionCounts[context.dataIndex];
                                return context.label + ': $' + value.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2}) + ' (' + percentage + '%) - ' + count + ' items';
                            }
                        }
                    }
                },
                onClick: function(evt, elements) {
                    if (elements.length > 0) {
                        var index = elements[0].index;
                        var category = deductionLabels[index];
                        var amount = deductionValues[index];
                        var count = deductionCounts[index];
                        var percentage = ((amount / totalDeductions) * 100).toFixed(1);
                        
                        // Update legend to highlight selected
                        $('#fs-deductions-legend .fs-legend-item').removeClass('active');
                        $('#fs-deductions-legend .fs-legend-item').eq(index).addClass('active');
                    }
                }
            }
        });
        
        // Build custom interactive legend
        var legendHtml = '';
        deductionLabels.forEach(function(label, index) {
            var percentage = ((deductionValues[index] / totalDeductions) * 100).toFixed(1);
            legendHtml += '<div class="fs-legend-item" data-index="' + index + '">' +
                '<span class="fs-legend-color" style="background-color: ' + chartColors[index] + ';"></span>' +
                '<span class="fs-legend-label">' + label + '</span>' +
                '<span class="fs-legend-value">$' + deductionValues[index].toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2}) + '</span>' +
                '<span class="fs-legend-percent">(' + percentage + '%)</span>' +
                '</div>';
        });
        $('#fs-deductions-legend').html(legendHtml);
        
        // Legend item click to highlight chart segment
        $('#fs-deductions-legend').on('click', '.fs-legend-item', function() {
            var index = $(this).data('index');
            $('#fs-deductions-legend .fs-legend-item').removeClass('active');
            $(this).addClass('active');
            
            // Highlight the segment
            pieChart.setActiveElements([{datasetIndex: 0, index: index}]);
            pieChart.update();
        });
    }

    // Income by Client - Multi-line chart
    var clientIncomeCtx = document.getElementById('fs-client-income-chart');
    if (clientIncomeCtx) {
        <?php
        $client_names  = array_keys($client_income_by_month);
        $client_series = array();
        foreach ($client_income_by_month as $name => $monthly) {
            $client_series[] = array_values($monthly); // indices 0-11
        }
        ?>
        var clientNames  = <?php echo json_encode($client_names); ?>;
        var clientSeries = <?php echo json_encode($client_series); ?>;
        var lineMonths = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

        var lineColors = [
            fsColors.primary, fsColors.accent, fsColors.secondary,
            fsColors.highlight, fsColors.pink, fsColors.primaryDark,
            fsColors.info, fsColors.danger
        ];

        var clientDatasets = clientNames.map(function(name, i) {
            return {
                label: name,
                data: clientSeries[i],
                borderColor: lineColors[i % lineColors.length],
                backgroundColor: lineColors[i % lineColors.length] + '22',
                borderWidth: 2,
                pointRadius: 4,
                pointHoverRadius: 6,
                tension: 0.3,
                fill: false
            };
        });

        new Chart(clientIncomeCtx, {
            type: 'line',
            data: { labels: lineMonths, datasets: clientDatasets },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: { mode: 'index', intersect: false },
                plugins: {
                    legend: { position: 'top', labels: { usePointStyle: true, padding: 16 } },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return context.dataset.label + ': $' +
                                    context.raw.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
                            }
                        }
                    }
                },
                scales: {
                    x: { grid: { display: false } },
                    y: {
                        beginAtZero: true,
                        ticks: { callback: function(v) { return '$' + v.toLocaleString(); } },
                        grid: { color: 'rgba(0,0,0,0.06)' }
                    }
                }
            }
        });
    }
});
</script>
