<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 #ece8f5; 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: #2c3e50; }
.fg input.filter-active { border-color: #2c3e50; background: #f0f3f6; }

.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: #2c3e50; color: #2c3e50; }
.btn.primary { background: #2c3e50; color: #fff; border-color: #2c3e50; }
.btn.primary:hover { background: #1a252f; }

.table-wrap { border-radius: 10px; overflow: hidden; border: 1px solid #e0e6ed; box-shadow: 0 2px 12px rgba(44,62,80,.07); }
table { width: 100%; border-collapse: collapse; background: #fff; }
thead th {
    background: #2c3e50; padding: 11px 14px; text-align: left;
    font-size: 12px; color: #fff; font-weight: 600; letter-spacing: .4px; text-transform: uppercase;
}
thead th.r { text-align: right; }
tbody td { padding: 10px 14px; border-top: 1px solid #f0f3f6; font-size: 13px; color: #333; vertical-align: middle; }
tbody td.r { text-align: right; font-variant-numeric: tabular-nums; }
tbody tr:hover        { background: #f5f7fa; }
tbody tr.stripe       { background: #fafbfc; }
tbody tr.stripe:hover { background: #eef1f5; }
tfoot td { padding: 11px 14px; background: #ecf0f1; font-weight: 700; font-size: 13px; border-top: 2px solid #bdc3c7; }
tfoot td.r { text-align: right; font-variant-numeric: tabular-nums; }

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

.c-mfg   { color: #8e44ad; font-weight: 600; }
.c-buy   { color: #2980b9; font-weight: 600; }
.c-qty   { color: #27ae60; font-weight: 600; }
.c-unit  { color: #e67e22; font-weight: 600; }
.c-ext   { color: #1a1a2e; font-weight: 700; }

.type-tag { border-radius: 4px; font-size: 11px; padding: 2px 8px; font-weight: 600; white-space: nowrap; }
.type-mfg { background: #f5eef8; color: #8e44ad; }
.type-buy { background: #eaf4fb; color: #2980b9; }
.type-oth { background: #f0f3f6; color: #555; }

.pag-wrap { display: flex; justify-content: space-between; align-items: center; padding: 14px 0; flex-wrap: wrap; gap: 10px; }
.pag { display: flex; gap: 5px; flex-wrap: wrap; }
.pag a, .pag span {
    padding: 6px 11px; border: 1px solid #dee2e6; border-radius: 5px;
    font-size: 13px; cursor: pointer; background: #fff; color: #495057; text-decoration: none; transition: all .15s;
}
.pag a:hover   { background: #2c3e50; color: #fff; border-color: #2c3e50; }
.pag .active   { background: #2c3e50; color: #fff; border-color: #2c3e50; font-weight: 600; }
.pag .disabled { opacity: .4; pointer-events: none; }
</style>

<h2>📦 Stock Valuation Report</h2>

<!-- Stats -->
<div class="stats">
    <div class="stat"><div class="stat-label">Total Parts</div><div class="stat-value" id="sv-stat-total">—</div></div>
    <div class="stat"><div class="stat-label">Showing</div><div class="stat-value" id="sv-stat-range" style="font-size:15px;padding-top:5px">—</div></div>
    <div class="stat"><div class="stat-label">Total Stock Value</div><div class="stat-value" id="sv-stat-grand" style="font-size:17px;padding-top:4px;color:#27ae60">—</div></div>
    <div class="stat"><div class="stat-label">Avg Unit Value</div><div class="stat-value" id="sv-stat-unit" style="font-size:17px;padding-top:4px;color:#e67e22">—</div></div>
</div>

<!-- Toolbar -->
<div class="toolbar-row">
    <div class="fg">
        <label>Part Number</label>
        <input type="text" id="sv-f-part" placeholder="Search part…" oninput="svDebounce()">
    </div>
    <div class="fg">
        <label>Type</label>
        <select id="sv-f-type" onchange="svLoad()">
            <option value="all">All Types</option>
            <option value="Manufactured">Manufactured</option>
            <option value="Bought In">Bought In</option>
        </select>
    </div>
    <div class="fg">
        <label>Min Extended Value</label>
        <input type="number" id="sv-f-min" placeholder="e.g. 100" oninput="svDebounce()" style="width:140px">
    </div>
    <div class="fg">
        <label>Max Extended Value</label>
        <input type="number" id="sv-f-max" placeholder="e.g. 5000" oninput="svDebounce()" style="width:140px">
    </div>
    <div class="fg">
        <label>Per page</label>
        <select id="sv-per-page" onchange="svLoad()">
            <option value="25" selected>25</option>
            <option value="50">50</option>
            <option value="100">100</option>
        </select>
    </div>
    <button class="btn" onclick="svReset()">↺ Reset</button>
    <button class="btn primary" onclick="svLoad()">Search</button>
</div>

<!-- Table -->
<div class="table-wrap">
<table>
    <thead>
        <tr>
            <th>#</th>
            <th>Part Number</th>
            <th>Type</th>
            <th>Batch Ref</th>
            <th>Latest Used Date</th>
            <th class="r">Stock Qty</th>
            <th class="r">Unit Value</th>
            <th class="r">Extended Value</th>
        </tr>
    </thead>
    <tbody id="sv-tbody">
        <tr><td colspan="8" class="no-data">Loading…</td></tr>
    </tbody>
    <tfoot id="sv-tfoot" style="display:none">
        <tr>
            <td colspan="7" class="r">Total Stock Value</td>
            <td class="r" id="sv-foot-total">—</td>
        </tr>
    </tfoot>
</table>
</div>

<!-- Pagination -->
<div class="pag-wrap" id="sv-pag-wrap" style="display:none">
    <div style="font-size:13px;color:#666">Page <strong id="sv-pag-info">1 of 1</strong></div>
    <div class="pag" id="sv-pag-controls"></div>
</div>

<script>
(function () {

var FILTER_KEY  = 'sv_report_filters';
var currentPage = 1;
var debTimer    = null;

function saveFilters() {
    var s = {
        part    : document.getElementById('sv-f-part').value,
        type    : document.getElementById('sv-f-type').value,
        min     : document.getElementById('sv-f-min').value,
        max     : document.getElementById('sv-f-max').value,
        perPage : document.getElementById('sv-per-page').value,
        page    : currentPage
    };
    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.part    !== undefined) document.getElementById('sv-f-part').value    = s.part;
        if (s.type    !== undefined) document.getElementById('sv-f-type').value    = s.type;
        if (s.min     !== undefined) document.getElementById('sv-f-min').value     = s.min;
        if (s.max     !== undefined) document.getElementById('sv-f-max').value     = s.max;
        if (s.perPage !== undefined) document.getElementById('sv-per-page').value  = s.perPage;
        if (s.page    !== undefined) currentPage = parseInt(s.page) || 1;
        highlightFilters();
    } catch(e) {}
}

function highlightFilters() {
    ['sv-f-part','sv-f-min','sv-f-max'].forEach(function(id) {
        var el = document.getElementById(id);
        if (el) el.classList.toggle('filter-active', el.value !== '');
    });
}

function getParams() {
    return {
        current_page : currentPage,
        per_page     : document.getElementById('sv-per-page').value,
        part         : document.getElementById('sv-f-part').value.trim(),
        item_type    : document.getElementById('sv-f-type').value,
        min_val      : document.getElementById('sv-f-min').value.trim(),
        max_val      : document.getElementById('sv-f-max').value.trim()
    };
}

window.svDebounce = function () {
    saveFilters();
    clearTimeout(debTimer);
    debTimer = setTimeout(function () { currentPage = 1; svLoad(false); }, 400);
};

window.svLoad = function (resetPage) {
    if (resetPage !== false) currentPage = 1;
    saveFilters();

    document.getElementById('sv-tbody').innerHTML =
        '<tr><td colspan="8" class="no-data">Loading…</td></tr>';
    document.getElementById('sv-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_stock_valuation&' + qs,
        type     : 'GET',
        dataType : 'json',
        success  : function (res) {
            if (!res.success) {
                document.getElementById('sv-tbody').innerHTML =
                    '<tr><td colspan="8" class="no-data" style="color:red">' +
                    esc(res.message || 'Error loading data.') + '</td></tr>';
                return;
            }
            renderRows(res.data || [], res.pagination);
            updateStats(res.pagination, res.summary);
            renderPagination(res.pagination);
        },
        error    : function (xhr) {
            var raw = xhr.responseText || '';
            try {
                var res = JSON.parse(raw);
                document.getElementById('sv-tbody').innerHTML =
                    '<tr><td colspan="8" class="no-data" style="color:red">' +
                    esc(res.message || 'Error loading data.') + '</td></tr>';
            } catch(e) {
                document.getElementById('sv-tbody').innerHTML =
                    '<tr><td colspan="8" 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, pag) {
    var tbody = document.getElementById('sv-tbody');
    if (!rows.length) {
        tbody.innerHTML = '<tr><td colspan="8" class="no-data">No items found.</td></tr>';
        document.getElementById('sv-tfoot').style.display = 'none';
        return;
    }

    var perPage = parseInt(document.getElementById('sv-per-page').value);
    var offset  = ((pag ? pag.current_page : currentPage) - 1) * perPage;
    var html    = '';
    var pageTotal = 0;

    rows.forEach(function (r, i) {
        var stripe   = (i % 2 === 1) ? ' stripe' : '';
        var extVal   = parseFloat(r.extended_value || 0);
        pageTotal   += extVal;

        var typeClass = r.item_type === 'Manufactured' ? 'type-mfg'
                      : r.item_type === 'Bought In'    ? 'type-buy' : 'type-oth';

        var dateStr = r.latest_used_date
            ? (function(d){ var p=d.split(/[- :T]/); return p[2]+'-'+p[1]+'-'+p[0]; })(r.latest_used_date.substring(0,10))
            : '—';

        html +=
            '<tr class="' + stripe + '">' +
            '<td style="color:#ccc;font-size:11px">'     + (offset + i + 1) + '</td>' +
            '<td style="font-weight:700;color:#1a1a2e">' + esc(r.part_number) + '</td>' +
            '<td><span class="type-tag ' + typeClass + '">' + esc(r.item_type) + '</span></td>' +
            '<td style="color:#555">'  + esc(r.batch_ref || '—') + '</td>' +
            '<td style="color:#777">'  + dateStr + '</td>' +
            '<td class="r c-qty">'     + fmt(r.stock_quantity) + '</td>' +
            '<td class="r c-unit">£'  + fmt(r.unit_value)     + '</td>' +
            '<td class="r c-ext">£'   + fmt(extVal)           + '</td>' +
            '</tr>';
    });

    tbody.innerHTML = html;

    // Footer total (page slice total)
    document.getElementById('sv-foot-total').textContent = '£' + fmt(pageTotal);
    document.getElementById('sv-tfoot').style.display = '';
}

function updateStats(pag, summary) {
    if (pag) {
        document.getElementById('sv-stat-total').textContent = pag.total_records;
        document.getElementById('sv-stat-range').textContent = pag.showing_from + ' – ' + pag.showing_to;
    }
    if (summary) {
        document.getElementById('sv-stat-grand').textContent = '£' + fmt(summary.grand_total || 0);
        document.getElementById('sv-stat-unit').textContent  = '£' + fmt(summary.avg_unit    || 0);
    }
}

function renderPagination(pag) {
    var wrap = document.getElementById('sv-pag-wrap');
    if (!pag || pag.total_pages <= 1) { wrap.style.display = 'none'; return; }
    wrap.style.display = 'flex';
    document.getElementById('sv-pag-info').textContent = pag.current_page + ' of ' + pag.total_pages;

    var cp = pag.current_page, tp = pag.total_pages, html = '';
    html += cp > 1
        ? '<a onclick="svGoTo(1)">«</a><a onclick="svGoTo(' + (cp-1) + ')">‹</a>'
        : '<span class="disabled">«</span><span class="disabled">‹</span>';

    var s = Math.max(1, cp-2), e = Math.min(tp, cp+2);
    if (s > 1) html += '<span>…</span>';
    for (var i = s; i <= e; i++) {
        html += i === cp
            ? '<span class="active">' + i + '</span>'
            : '<a onclick="svGoTo(' + i + ')">' + i + '</a>';
    }
    if (e < tp) html += '<span>…</span>';
    html += cp < tp
        ? '<a onclick="svGoTo(' + (cp+1) + ')">›</a><a onclick="svGoTo(' + tp + ')">»</a>'
        : '<span class="disabled">›</span><span class="disabled">»</span>';

    document.getElementById('sv-pag-controls').innerHTML = html;
}

window.svGoTo = function (p) { currentPage = p; saveFilters(); svLoad(false); };

window.svReset = function () {
    ['sv-f-part','sv-f-min','sv-f-max'].forEach(function (id) { document.getElementById(id).value = ''; });
    document.getElementById('sv-f-type').value    = 'all';
    document.getElementById('sv-per-page').value  = '25';
    currentPage = 1;
    try { sessionStorage.removeItem(FILTER_KEY); } catch(e) {}
    highlightFilters();
    svLoad(false);
};

function fmt(v) { return parseFloat(v).toFixed(2).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();
svLoad(false);

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

})();
</script>