<?php
// includes/finance/finance_forecast.php

require_once(ROOT_URL . '/includes/finance/finance_functions.php');

$T    = $_GET['t'] ?? 'includes/finance';
$P    = $_GET['p'] ?? 'finance_forecast.php';
$SELF = 'index.php?t=' . rawurlencode($T) . '&p=' . rawurlencode($P);

$today         = strtotime('today');
$defaultEnd    = strtotime('+12 months', $today);
$defaultStart  = date('d-m-Y', $today);
$defaultEndStr = date('d-m-Y', $defaultEnd);

// Agent/Broker filter selects (using your existing helpers)
$agentSelectHtml  = listAgent(0, 'forecast_agent', 'select');
$brokerSelectHtml = listBrokers(0, 'forecast_broker', 'select');
?>
<div class="container-fluid">
    <div class="row">
        <div class="note note-light mb-3 col-12 col-md-9">
            <strong>Finance Forecast:</strong>
            This page provides a projection of expected renewal income from active clients.
            It uses each client’s contract rate and term to estimate renewal value within a
            chosen date range, and can be filtered by agent or broker. Incomplete records or
            overdue renewals are listed but excluded from the forecast totals.
        </div>

        <div class="col-12 col-md-3 text-md-end mb-3">
            <button id="btnForecastCsv" type="button" class="btn btn-secondary me-2 mb-2"
                    data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                    title="Export current forecast to CSV">
                <i class="fad fa-file-csv me-2"></i>CSV
            </button>
            <button id="btnForecastPdf" type="button" class="btn btn-secondary me-2 mb-2"
                    data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                    title="Generate PDF forecast report">
                <i class="fad fa-file-pdf me-2"></i>PDF
            </button>
            <button id="btnForecastPrint" type="button" class="btn btn-secondary mb-2"
                    data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                    title="Print current forecast">
                <i class="fad fa-print me-2"></i>Print
            </button>
        </div>
    </div>

    <div class="card mb-3">
        <div class="card-header">
            <i class="fad fa-filter me-2"></i>Filters
        </div>
        <div class="card-body">
            <div class="row g-3 align-items-end">
                <!-- Date from -->
                <div class="col-12 col-md-3">
                    <div class="w-100 date-picker" data-date-type="open" data-format="dd-mm-yyyy" data-mdb-toggle-button="false">
                        <h6 class="mb-1">From date</h6>
                        <input
                               type="text"
                               id="forecast_start"
                               name="forecast_start"
                               class="form-control form-control-sm"
                               placeholder="Start date"
                               value="<?= htmlspecialchars($defaultStart) ?>"
                               data-mdb-confirmDateOnSelect
                               data-mdb-toggle="datepicker" />
                    </div>
                </div>

                <!-- Date to -->
                <div class="col-12 col-md-3">
                    <div class="w-100 date-picker" data-date-type="open" data-format="dd-mm-yyyy" data-mdb-toggle-button="false">
                        <h6 class="mb-1">To date</h6>
                        <input
                               type="text"
                               id="forecast_end"
                               name="forecast_end"
                               class="form-control form-control-sm"
                               placeholder="End date"
                               value="<?= htmlspecialchars($defaultEndStr) ?>"
                               data-mdb-confirmDateOnSelect
                               data-mdb-toggle="datepicker" />
                    </div>
                </div>

                <!-- Scope -->
                <div class="col-12 col-md-3">
                    <label for="forecast_scope" class="form-label mb-1">Scope</label>
                    <select id="forecast_scope" name="forecast_scope" class="form-select form-select-sm">
                        <option value="all" selected>All clients</option>
                        <option value="agent">Specific agent</option>
                        <option value="broker">Specific broker</option>
                    </select>
                </div>

                <!-- Agent -->
                <div class="col-12 col-md-3" id="forecast_agent_container" style="display:none;">
                    <label for="forecast_agent" class="form-label mb-1">Agent</label>
                    <?= $agentSelectHtml ?>
                </div>

                <!-- Broker -->
                <div class="col-12 col-md-3" id="forecast_broker_container" style="display:none;">
                    <label for="forecast_broker" class="form-label mb-1">Broker</label>
                    <?= $brokerSelectHtml ?>
                </div>

                <div class="col-12 col-md-3">
                    <button id="btnForecastApply" type="button" class="btn btn-info btn-sm w-100"
                            data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                            title="Apply filters and refresh forecast">
                        <i class="fad fa-sync-alt me-2"></i>Apply filters
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Summary + by-month -->
    <div class="card mb-3" id="forecastSummaryCard" style="display:none;">
        <div class="card-header">
            <i class="fad fa-chart-line me-2"></i>Summary
        </div>
        <div class="card-body" id="forecastSummary">
            <!-- Filled by JS -->
        </div>
    </div>

    <!-- Detailed table -->
    <div class="card">
        <div class="card-header">
            <i class="fad fa-list-alt me-2"></i>Client details
        </div>
        <div class="card-body" id="forecastResults">
            <div class="text-center text-muted" id="forecastLoading">
                <i class="fad fa-spinner-third fa-spin me-2"></i>Loading forecast…
            </div>
            <div id="forecastTableContainer" style="display:none;">
                <!-- Table inserted by JS -->
            </div>
        </div>
    </div>
</div>

<script>
(function() {
    "use strict";

    const DATA_URL = ROOT_URL + '/includes/finance/forecast/finance_forecast_data.php';

    function getFilters() {
        const scopeEl = document.getElementById('forecast_scope');
        const agentEl = document.getElementById('forecast_agent');
        const brokerEl = document.getElementById('forecast_broker');
        const startEl = document.getElementById('forecast_start');
        const endEl = document.getElementById('forecast_end');

        return {
            scope: scopeEl ? scopeEl.value : 'all',
            agent: agentEl ? agentEl.value : '',
            broker: brokerEl ? brokerEl.value : '',
            start: startEl ? startEl.value.trim() : '',
            end: endEl ? endEl.value.trim() : ''
        };
    }

    function toggleScopeFields() {
        const scope = document.getElementById('forecast_scope').value;
        const agentWrap = document.getElementById('forecast_agent_container');
        const brokerWrap = document.getElementById('forecast_broker_container');

        if (agentWrap) agentWrap.style.display = (scope === 'agent') ? '' : 'none';
        if (brokerWrap) brokerWrap.style.display = (scope === 'broker') ? '' : 'none';
    }

    function formatGBP(value) {
        if (typeof value !== 'number' || isNaN(value)) return '£0.00';
        return '£' + value.toLocaleString('en-GB', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        });
    }

    function formatPct(value) {
        const n = Number(value) || 0;
        if (!n) return '';
        return n.toLocaleString('en-GB', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        }) + '%';
    }

    function renderSummary(data) {
        const summaryEl = document.getElementById('forecastSummary');
        const card = document.getElementById('forecastSummaryCard');
        if (!summaryEl || !card) return;

        const s = data.summary || {};
        const months = data.months || [];

        const periodStr = `${new Date(s.start_ts * 1000).toLocaleDateString('en-GB')} to ${new Date(s.end_ts * 1000).toLocaleDateString('en-GB')}`;

        let monthRows = '';
        months.forEach(m => {
            monthRows += `
                <tr>
                    <td>${m.label}</td>
                    <td>${m.count}</td>
                    <td class="text-end">${formatGBP(m.total)}</td>
                    <td class="text-end">${formatGBP(m.commission || 0)}</td>
                </tr>
            `;
        });
        if (!monthRows) {
            monthRows = `
                <tr>
                    <td colspan="4" class="text-center text-muted">No renewals within the selected period.</td>
                </tr>
            `;
        }

        summaryEl.innerHTML = `
            <div class="row mb-3">
                <div class="col-12 col-md-3">
                    <div class="border rounded p-2 h-100">
                        <div class="text-muted small">Total forecast income</div>
                        <div class="fw-bold fs-5">${formatGBP(s.total_forecast || 0)}</div>
                        <div class="text-muted small">Commission: <strong>${formatGBP(s.total_commission || 0)}</strong></div>
                        <div class="text-muted small">Net: <strong>${formatGBP(s.total_net_after_comm || 0)}</strong></div>
                    </div>
                </div>
                <div class="col-12 col-md-3">
                    <div class="border rounded p-2 h-100">
                        <div class="text-muted small">Clients included</div>
                        <div class="fw-bold fs-5">${s.included_count || 0}</div>
                        <div class="text-muted small">of ${s.client_count || 0} active clients</div>
                    </div>
                </div>
                <div class="col-12 col-md-3">
                    <div class="border rounded p-2 h-100">
                        <div class="text-muted small">Incomplete records</div>
                        <div class="fw-bold fs-5">${s.incomplete_count || 0}</div>
                        <div class="text-muted small">Missing rate/term or dates</div>
                    </div>
                </div>
                <div class="col-12 col-md-3">
                    <div class="border rounded p-2 h-100">
                        <div class="text-muted small">Overdue renewals</div>
                        <div class="fw-bold fs-5">${s.overdue_count || 0}</div>
                        <div class="text-muted small">In the past (not forecast)</div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-12 col-lg-6">
                    <p class="mb-1"><strong>Period:</strong> ${periodStr}</p>
                    <p class="mb-1 small text-muted">
                        Only future renewals within this period are included.
                        Overdue renewals and incomplete records are listed for attention but excluded from totals.
                    </p>
                </div>
                <div class="col-12 col-lg-6">
                    <div class="table-responsive">
                        <table class="table table-sm table-bordered mb-0">
                            <thead>
                                <tr>
                                    <th>Month</th>
                                    <th>Renewals</th>
                                    <th class="text-end">Forecast value</th>
                                    <th class="text-end">Commission</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${monthRows}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        `;

        card.style.display = '';
    }

    function renderTable(data) {
        const container = document.getElementById('forecastTableContainer');
        const loading = document.getElementById('forecastLoading');
        if (!container) return;

        const rows = data.rows || [];

        if (loading) loading.style.display = 'none';
        container.style.display = '';

        let bodyRows = '';
        rows.forEach(row => {
            const valueStr = row.included ? formatGBP(row.forecast_value) : '';
            const rateStr = row.rate_per_hour > 0 ? formatGBP(row.rate_per_hour).replace('£', '') : '';
            const rateDisp = row.rate_per_hour > 0 ? '£' + rateStr : '';
            const termStr = row.term_years > 0 ? row.term_years : '';

            const commRate = row.included ? (Number(row.commission_rate) || 0) : 0;
            const commVal = row.included ? (Number(row.commission_value) || 0) : 0;

            const commRateStr = row.included && commRate > 0 ? formatPct(commRate) : '';
            const commValStr = row.included && commVal > 0 ? formatGBP(commVal) : '';

            let statusBadgeClass = 'badge bg-secondary';
            if (row.status.indexOf('Incomplete') === 0) {
                statusBadgeClass = 'badge bg-warning text-dark';
            } else if (row.status.indexOf('Overdue') === 0) {
                statusBadgeClass = 'badge bg-danger';
            } else if (row.status.indexOf('Included') === 0) {
                statusBadgeClass = 'badge bg-success';
            }

            bodyRows += `
                <tr>
                    <td>${row.clientnumber}</td>
                    <td>${row.clientname}</td>
                    <td>${row.renewal_label}</td>
                    <td><span class="${statusBadgeClass}">${row.status}</span></td>
                    <td class="text-end">${rateDisp}</td>
                    <td class="text-center">${termStr}</td>
                    <td class="text-end">${valueStr}</td>
                    <td class="text-center">${commRateStr}</td>
                    <td class="text-end">${commValStr}</td>
                    <td>${row.agent_name || ''}</td>
                    <td>${row.broker_name || ''}</td>
                </tr>
            `;
        });

        if (!bodyRows) {
            bodyRows = `
                <tr>
                    <td colspan="11" class="text-center text-muted">No active clients found for the selected criteria.</td>
                </tr>
            `;
        }

        container.innerHTML = `
            <div class="table-responsive">
                <table class="table table-sm table-striped">
                    <thead>
                        <tr>
                            <th style="width:8%">Client #</th>
                            <th style="width:20%">Client</th>
                            <th style="width:10%">Renewal date</th>
                            <th style="width:14%">Status</th>
                            <th style="width:9%" class="text-end">Rate/hr</th>
                            <th style="width:7%" class="text-center">Term (yrs)</th>
                            <th style="width:9%" class="text-end">Forecast</th>
                            <th style="width:6%" class="text-center">Comm %</th>
                            <th style="width:9%" class="text-end">Commission</th>
                            <th style="width:9%">Agent</th>
                            <th style="width:10%">Broker</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${bodyRows}
                    </tbody>
                </table>
            </div>
        `;
    }

    function loadForecast() {
        const params = getFilters();
        const loading = document.getElementById('forecastLoading');
        const summaryCard = document.getElementById('forecastSummaryCard');
        const container = document.getElementById('forecastTableContainer');

        if (summaryCard) summaryCard.style.display = 'none';
        if (container) {
            container.style.display = 'none';
            container.innerHTML = '';
        }
        if (loading) {
            loading.style.display = '';
            loading.innerHTML = '<i class="fad fa-spinner-third fa-spin me-2"></i>Loading forecast…';
        }

        const formData = new URLSearchParams();
        formData.append('mode', 'data');
        formData.append('scope', params.scope);
        formData.append('agent', params.agent);
        formData.append('broker', params.broker);
        formData.append('start', params.start);
        formData.append('end', params.end);
        formData.append('tenant', TENANT_URL);

        fetch(DATA_URL, {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(text => {
                const loading = document.getElementById('forecastLoading');

                let data;
                try {
                    data = JSON.parse(text);
                } catch (e) {
                    console.error('finance_forecast_data.php raw response:', text);
                    if (loading) {
                        loading.innerHTML =
                            '<div class="text-danger small">Backend error in finance_forecast_data.php:<br><pre class="mt-2">' +
                            text.replace(/</g, '&lt;') +
                            '</pre></div>';
                    }
                    if (typeof showResponse === 'function') {
                        showResponse('danger', 'Finance forecast endpoint returned an invalid response. See details above.');
                    }
                    return;
                }

                if (data && data.error) {
                    if (loading) {
                        loading.innerHTML = '<span class="text-danger">' + data.error + '</span>';
                    }
                    if (typeof showResponse === 'function') {
                        showResponse('danger', data.error);
                    }
                    return;
                }

                renderSummary(data);
                renderTable(data);
            })
            .catch(err => {
                const loading = document.getElementById('forecastLoading');
                console.error('finance_forecast_data.php fetch error:', err);
                if (loading) {
                    loading.innerHTML = '<span class="text-danger">Failed to load forecast data.</span>';
                }
                if (typeof showResponse === 'function') {
                    showResponse('danger', 'Unable to load forecast data. Please try again.');
                }
            });

    }

    function buildExportUrl(mode) {
        const params = getFilters();
        const qs = new URLSearchParams();
        qs.append('mode', mode);
        qs.append('scope', params.scope);
        qs.append('agent', params.agent);
        qs.append('broker', params.broker);
        qs.append('start', params.start);
        qs.append('end', params.end);
        qs.append('tenant', TENANT_URL);
        return DATA_URL + '?' + qs.toString();
    }

    document.addEventListener('DOMContentLoaded', function() {
        const scopeEl = document.getElementById('forecast_scope');
        const applyBtn = document.getElementById('btnForecastApply');
        const csvBtn = document.getElementById('btnForecastCsv');
        const pdfBtn = document.getElementById('btnForecastPdf');
        const printBtn = document.getElementById('btnForecastPrint');

        if (scopeEl) {
            scopeEl.addEventListener('change', toggleScopeFields);
            toggleScopeFields();
        }

        if (applyBtn) {
            applyBtn.addEventListener('click', loadForecast);
        }

        if (csvBtn) {
            csvBtn.addEventListener('click', function() {
                window.location.href = buildExportUrl('csv');
            });
        }

        if (pdfBtn) {
            pdfBtn.addEventListener('click', function() {
                window.open(buildExportUrl('pdf'), '_blank');
            });
        }

        if (printBtn) {
            printBtn.addEventListener('click', function() {
                if (typeof printContainer === 'function') {
                    printContainer('forecastResults', {
                        styles: [
                            ROOT_URL + '/resources/mdb/css/mdb.min.css',
                            ROOT_URL + '/assets/css/style.css'
                        ]
                    });
                } else {
                    window.print();
                }
            });
        }

        // Initial load
        loadForecast();
    });
})();

document.getElementById('navBox').innerHTML =
    '<li class="breadcrumb-item ">Finance - Forecast</li> ';
</script>