<style>
*, *::before, *::after { box-sizing: border-box; }

h2 { margin-bottom: .4rem; font-size: 1.4rem; color: #1a1a2e; letter-spacing: -.3px; }

.stats { display: flex; gap: 12px; margin-bottom: 1.4rem; flex-wrap: wrap; }
.stat  { background: #fff; border: 1px solid #e0e6ed; border-radius: 10px; padding: 12px 20px; box-shadow: 0 1px 4px rgba(44,62,80,.07); }
.stat-label { font-size: 11px; color: #999; text-transform: uppercase; letter-spacing: .5px; }
.stat-value { font-size: 22px; font-weight: 700; color: #1a1a2e; }

.toolbar-row { display: flex; align-items: flex-end; gap: 12px; margin-bottom: 1rem; flex-wrap: wrap; }
.fg { display: flex; flex-direction: column; gap: 4px; }
.fg label { font-size: 11px; font-weight: 600; color: #666; text-transform: uppercase; letter-spacing: .4px; }
.fg input, .fg select {
    padding: 8px 12px; border: 1px solid #ddd; border-radius: 7px;
    font-size: 13px; background: #fff; transition: border-color .15s;
}
.fg input:focus, .fg select:focus { outline: none; border-color: #1a5276; }
.fg input.filter-active { border-color: #1a5276; background: #eaf0f6; }

.btn { padding: 8px 16px; border: 1px solid #ddd; border-radius: 7px; cursor: pointer; background: #fff; font-size: 13px; height: 36px; align-self: flex-end; transition: all .15s; font-weight: 500; }
.btn:hover { border-color: #1a5276; color: #1a5276; }
.btn.primary { background: #1a5276; color: #fff; border-color: #1a5276; }
.btn.primary:hover { background: #154360; }

.table-wrap { border-radius: 10px; overflow: hidden; border: 1px solid #e0e6ed; box-shadow: 0 2px 12px rgba(44,62,80,.07); overflow-x: auto; }
table { width: 100%; border-collapse: collapse; background: #fff; min-width: 900px; }
thead th {
    background: #1a5276; padding: 10px 10px; text-align: right;
    font-size: 11px; color: #fff; font-weight: 600; letter-spacing: .4px; text-transform: uppercase;
    white-space: nowrap;
}
thead th.l { text-align: left; }
tbody td { padding: 8px 10px; border-top: 1px solid #f0f3f6; font-size: 12px; color: #333; text-align: right; white-space: nowrap; }
tbody td.l { text-align: left; }
tbody tr:hover        { background: #eaf0f6; }
tbody tr.stripe       { background: #fafbfc; }
tbody tr.stripe:hover { background: #d6e4f0; }

/* month cells — zero = muted, positive = normal */
td.zero  { color: #ddd; }
td.pos   { color: #1a5276; font-weight: 600; }
td.total-col { color: #1a1a2e; font-weight: 700; border-left: 2px solid #e0e6ed; }

/* totals footer */
tfoot td {
    padding: 9px 10px; background: #d6e4f0; font-weight: 700;
    font-size: 12px; border-top: 2px solid #1a5276;
    text-align: right; white-space: nowrap;
}
tfoot td.l { text-align: left; }
tfoot td.grand { background: #1a5276; color: #fff; }

.no-data { padding: 2.5rem; text-align: center; color: #bbb; font-size: 14px; }

.pag-wrap { display: none; } /* no pagination — pivot table loads all rows */
</style>

<h2>📊 Sales Forecast</h2>

<!-- Stats -->
<div class="stats">
    <div class="stat"><div class="stat-label">Year</div><div class="stat-value" id="sf-stat-year">—</div></div>
    <div class="stat"><div class="stat-label">Customers</div><div class="stat-value" id="sf-stat-customers">—</div></div>
    <div class="stat"><div class="stat-label">Grand Total</div><div class="stat-value" id="sf-stat-grand" style="font-size:17px;padding-top:4px;color:#1a5276">—</div></div>
</div>

<!-- Toolbar -->
<div class="toolbar-row">
    <div class="fg">
        <label>Year</label>
        <select id="sf-f-year" onchange="sfLoad()">
            <?php
            $currentYear = (int)date('Y');
            for ($y = $currentYear + 1; $y >= $currentYear - 4; $y--) {
                $sel = ($y === $currentYear) ? 'selected' : '';
                echo "<option value=\"$y\" $sel>$y</option>";
            }
            ?>
        </select>
    </div>
    <div class="fg">
        <label>Customer Code</label>
        <input type="text" id="sf-f-customer" placeholder="Search customer…" oninput="sfDebounce()">
    </div>
    <button class="btn" onclick="sfReset()">↺ Reset</button>
    <button class="btn primary" onclick="sfLoad()">Search</button>
</div>

<!-- Table -->
<div class="table-wrap">
<table>
    <thead>
        <tr>
            <th class="l" style="min-width:130px">Customer Code</th>
            <th>Jan</th><th>Feb</th><th>Mar</th><th>Apr</th>
            <th>May</th><th>Jun</th><th>Jul</th><th>Aug</th>
            <th>Sep</th><th>Oct</th><th>Nov</th><th>Dec</th>
            <th class="total-col">Total</th>
        </tr>
    </thead>
    <tbody id="sf-tbody">
        <tr><td colspan="14" class="no-data">Loading…</td></tr>
    </tbody>
    <tfoot id="sf-tfoot" style="display:none">
        <tr id="sf-foot-row">
            <td class="l">Totals</td>
            <td id="sf-ft-Jan">—</td><td id="sf-ft-Feb">—</td>
            <td id="sf-ft-Mar">—</td><td id="sf-ft-Apr">—</td>
            <td id="sf-ft-May">—</td><td id="sf-ft-Jun">—</td>
            <td id="sf-ft-Jul">—</td><td id="sf-ft-Aug">—</td>
            <td id="sf-ft-Sep">—</td><td id="sf-ft-Oct">—</td>
            <td id="sf-ft-Nov">—</td><td id="sf-ft-Dec">—</td>
            <td class="grand" id="sf-ft-grand">—</td>
        </tr>
    </tfoot>
</table>
</div>

<script>
(function () {

var MONTHS      = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var FILTER_KEY  = 'sf_report_filters';
var debTimer    = null;

function saveFilters() {
    var s = {
        year     : document.getElementById('sf-f-year').value,
        customer : document.getElementById('sf-f-customer').value
    };
    try { sessionStorage.setItem(FILTER_KEY, JSON.stringify(s)); } catch(e) {}
    highlightFilters();
}

function restoreFilters() {
    try {
        var raw = sessionStorage.getItem(FILTER_KEY);
        if (!raw) return;
        var s = JSON.parse(raw);
        if (s.year     !== undefined) document.getElementById('sf-f-year').value     = s.year;
        if (s.customer !== undefined) document.getElementById('sf-f-customer').value = s.customer;
        highlightFilters();
    } catch(e) {}
}

function highlightFilters() {
    var el = document.getElementById('sf-f-customer');
    if (el) el.classList.toggle('filter-active', el.value !== '');
}

function getParams() {
    return {
        year          : document.getElementById('sf-f-year').value,
        customer_code : document.getElementById('sf-f-customer').value.trim()
    };
}

window.sfDebounce = function () {
    saveFilters();
    clearTimeout(debTimer);
    debTimer = setTimeout(function () { sfLoad(false); }, 400);
};

window.sfLoad = function () {
    saveFilters();

    document.getElementById('sf-tbody').innerHTML =
        '<tr><td colspan="14" class="no-data">Loading…</td></tr>';
    document.getElementById('sf-tfoot').style.display = 'none';

    var params = getParams();
    var qs = Object.keys(params).map(function(k) {
        return encodeURIComponent(k) + '=' + encodeURIComponent(params[k]);
    }).join('&');

    $.ajax({
        url      : site_url + '/modules/report_management/index.php?page=ajax_actions&action=get_sales_forecast&' + qs,
        type     : 'GET',
        dataType : 'json',
        success  : function (res) {
            if (!res.success) {
                document.getElementById('sf-tbody').innerHTML =
                    '<tr><td colspan="14" class="no-data" style="color:red">' +
                    esc(res.message || 'Error loading data.') + '</td></tr>';
                return;
            }
            renderRows(res.data || [], res.totals, res.summary);
        },
        error    : function (xhr) {
            var raw = xhr.responseText || '';
            try {
                var res = JSON.parse(raw);
                document.getElementById('sf-tbody').innerHTML =
                    '<tr><td colspan="14" class="no-data" style="color:red">' +
                    esc(res.message || 'Error loading data.') + '</td></tr>';
            } catch(e) {
                document.getElementById('sf-tbody').innerHTML =
                    '<tr><td colspan="14" class="no-data" style="color:red">' +
                    '<strong>Server did not return valid JSON.</strong>' +
                    '<br><pre style="text-align:left;font-size:11px;color:#555;white-space:pre-wrap;margin-top:8px">' +
                    esc(raw.substring(0, 800)) + '</pre></td></tr>';
            }
        }
    });
};

function renderRows(rows, totals, summary) {
    var tbody = document.getElementById('sf-tbody');

    if (!rows.length) {
        tbody.innerHTML = '<tr><td colspan="14" class="no-data">No forecast data found.</td></tr>';
        document.getElementById('sf-tfoot').style.display = 'none';
        updateStats(summary);
        return;
    }

    var html = '';
    rows.forEach(function (r, i) {
        var stripe = (i % 2 === 1) ? ' stripe' : '';
        html += '<tr class="' + stripe + '">';
        html += '<td class="l" style="font-weight:600;color:#1a1a2e">' + esc(r.customer_code || '—') + '</td>';
        MONTHS.forEach(function (m) {
            var val = parseFloat(r[m] || 0);
            if (val > 0) {
                html += '<td class="pos">£' + fmt(val) + '</td>';
            } else {
                html += '<td class="zero">—</td>';
            }
        });
        var rowTotal = parseFloat(r.row_total || 0);
        html += '<td class="total-col">£' + fmt(rowTotal) + '</td>';
        html += '</tr>';
    });

    tbody.innerHTML = html;

    /* footer totals */
    var grandTotal = 0;
    MONTHS.forEach(function (m) {
        var val = parseFloat(totals[m] || 0);
        grandTotal += val;
        var el = document.getElementById('sf-ft-' + m);
        if (el) el.textContent = val > 0 ? '£' + fmt(val) : '—';
    });
    document.getElementById('sf-ft-grand').textContent = '£' + fmt(summary.grand_total || 0);
    document.getElementById('sf-tfoot').style.display  = '';

    updateStats(summary);
}

function updateStats(summary) {
    if (!summary) return;
    document.getElementById('sf-stat-year').textContent      = summary.year          || '—';
    document.getElementById('sf-stat-customers').textContent = summary.customer_count || 0;
    document.getElementById('sf-stat-grand').textContent     = '£' + fmt(summary.grand_total || 0);
}

window.sfReset = function () {
    document.getElementById('sf-f-year').value     = new Date().getFullYear();
    document.getElementById('sf-f-customer').value = '';
    try { sessionStorage.removeItem(FILTER_KEY); } catch(e) {}
    highlightFilters();
    sfLoad();
};

function fmt(v) { return parseFloat(v).toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g, ','); }
function esc(s) {
    return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}

restoreFilters();
sfLoad();

setInterval(function () { sfLoad(); }, 5 * 60 * 1000);

})();
</script>