<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: #16a085; }
.fg input.filter-active { border-color: #16a085; background: #f0faf8; }

.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: #16a085; color: #16a085; }
.btn.primary { background: #16a085; color: #fff; border-color: #16a085; }
.btn.primary:hover { background: #0e6655; }

.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: #16a085; 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: #f0faf8; }
tbody tr.stripe       { background: #fafbfc; }
tbody tr.stripe:hover { background: #e8f8f5; }
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-qty   { color: #16a085; font-weight: 600; }
.c-price { color: #e67e22; font-weight: 600; }
.c-total { color: #1a1a2e; font-weight: 700; }

.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: #16a085; color: #fff; border-color: #16a085; }
.pag .active   { background: #16a085; color: #fff; border-color: #16a085; font-weight: 600; }
.pag .disabled { opacity: .4; pointer-events: none; }
</style>

<h2>🚚 Delivery Report</h2>

<!-- Stats -->
<div class="stats">
    <div class="stat"><div class="stat-label">Total Records</div><div class="stat-value" id="dr-stat-total">—</div></div>
    <div class="stat"><div class="stat-label">Showing</div><div class="stat-value" id="dr-stat-range" style="font-size:15px;padding-top:5px">—</div></div>
    <div class="stat"><div class="stat-label">Total Qty Delivered</div><div class="stat-value" id="dr-stat-qty" style="font-size:17px;padding-top:4px;color:#16a085">—</div></div>
    <div class="stat"><div class="stat-label">Total Value</div><div class="stat-value" id="dr-stat-value" style="font-size:17px;padding-top:4px;color:#e67e22">—</div></div>
</div>

<!-- Toolbar -->
<div class="toolbar-row">
    <div class="fg">
        <label>From Date</label>
        <input type="date" id="dr-f-from" oninput="drDebounce()">
    </div>
    <div class="fg">
        <label>To Date</label>
        <input type="date" id="dr-f-to" oninput="drDebounce()">
    </div>
    <div class="fg">
        <label>Part Number</label>
        <input type="text" id="dr-f-part" placeholder="Search part…" oninput="drDebounce()">
    </div>
    <div class="fg">
        <label>Order No</label>
        <input type="text" id="dr-f-order" placeholder="Customer order…" oninput="drDebounce()">
    </div>
    <div class="fg">
        <label>Invoice No</label>
        <input type="text" id="dr-f-invoice" placeholder="Invoice…" oninput="drDebounce()">
    </div>
    <div class="fg">
        <label>Per page</label>
        <select id="dr-per-page" onchange="drLoad()">
            <option value="25" selected>25</option>
            <option value="50">50</option>
            <option value="100">100</option>
        </select>
    </div>
    <button class="btn" onclick="drReset()">↺ Reset</button>
    <button class="btn primary" onclick="drLoad()">Search</button>
</div>

<!-- Table -->
<div class="table-wrap">
<table>
    <thead>
        <tr>
            <th>#</th>
            <th>Customer Code</th>
            <th>Customer Name</th>
            <th>Part Number</th>
            <th>Description</th>
            <th class="r">Qty</th>
            <th class="r">Unit Price</th>
            <th class="r">Total</th>
            <th>Delivery Date</th>
            <th>Delivery Note</th>
            <th>Date Required</th>
            <th>Invoice No</th>
            <th>Order No</th>
        </tr>
    </thead>
    <tbody id="dr-tbody">
        <tr><td colspan="13" class="no-data">Loading…</td></tr>
    </tbody>
    <tfoot id="dr-tfoot" style="display:none">
        <tr>
            <td colspan="5" class="r">Page Totals</td>
            <td class="r" id="dr-foot-qty">—</td>
            <td></td>
            <td class="r" id="dr-foot-total">—</td>
            <td colspan="5"></td>
        </tr>
    </tfoot>
</table>
</div>

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

<script>
(function () {

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

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

function highlightFilters() {
    ['dr-f-from','dr-f-to','dr-f-part','dr-f-order','dr-f-invoice'].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('dr-per-page').value,
        from_date      : document.getElementById('dr-f-from').value,
        to_date        : document.getElementById('dr-f-to').value,
        part_number    : document.getElementById('dr-f-part').value.trim(),
        customer_order : document.getElementById('dr-f-order').value.trim(),
        invoice_number : document.getElementById('dr-f-invoice').value.trim()
    };
}

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

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

    document.getElementById('dr-tbody').innerHTML =
        '<tr><td colspan="13" class="no-data">Loading…</td></tr>';
    document.getElementById('dr-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_delivery_report&' + qs,
        type     : 'GET',
        dataType : 'json',
        success  : function (res) {
            if (!res.success) {
                document.getElementById('dr-tbody').innerHTML =
                    '<tr><td colspan="13" 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('dr-tbody').innerHTML =
                    '<tr><td colspan="13" class="no-data" style="color:red">' +
                    esc(res.message || 'Error loading data.') + '</td></tr>';
            } catch(e) {
                document.getElementById('dr-tbody').innerHTML =
                    '<tr><td colspan="13" 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 fmtDate(d) {
    if (!d) return '—';
    var p = d.substring(0, 10).split('-');
    return p[2] + '-' + p[1] + '-' + p[0];
}

function renderRows(rows, pag) {
    var tbody = document.getElementById('dr-tbody');
    if (!rows.length) {
        tbody.innerHTML = '<tr><td colspan="13" class="no-data">No delivery records found.</td></tr>';
        document.getElementById('dr-tfoot').style.display = 'none';
        return;
    }

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

    rows.forEach(function (r, i) {
        var stripe = (i % 2 === 1) ? ' stripe' : '';
        var qty    = parseFloat(r.quantity_delivered || 0);
        var price  = parseFloat(r.unit_price         || 0);
        var total  = parseFloat(r.total              || 0);
        pageQty   += qty;
        pageVal   += total;

        html +=
            '<tr class="' + stripe + '">' +
            '<td style="color:#ccc;font-size:11px">'     + (offset + i + 1)          + '</td>' +
            '<td style="font-weight:600;color:#1a1a2e">' + esc(r.customer_code)       + '</td>' +
            '<td>'                                        + esc(r.customer_name)       + '</td>' +
            '<td style="font-weight:700;color:#16a085">' + esc(r.part_number)         + '</td>' +
            '<td style="color:#555">'                    + esc(r.part_description)    + '</td>' +
            '<td class="r c-qty">'                       + fmt(qty)                   + '</td>' +
            '<td class="r c-price">£'                    + fmt(price)                 + '</td>' +
            '<td class="r c-total">£'                    + fmt(total)                 + '</td>' +
            '<td style="color:#555">'                    + fmtDate(r.date_delivered)  + '</td>' +
            '<td style="color:#555">'                    + esc(r.delivery_note || '—')+ '</td>' +
            '<td style="color:#555">'                    + fmtDate(r.date_required)   + '</td>' +
            '<td style="color:#888;font-size:12px">'     + esc(r.invoice_number)      + '</td>' +
            '<td style="color:#888;font-size:12px">'     + esc(r.order_number || '—') + '</td>' +
            '</tr>';
    });

    tbody.innerHTML = html;

    document.getElementById('dr-foot-qty').textContent   = fmt(pageQty);
    document.getElementById('dr-foot-total').textContent = '£' + fmt(pageVal);
    document.getElementById('dr-tfoot').style.display    = '';
}

function updateStats(pag, summary) {
    if (pag) {
        document.getElementById('dr-stat-total').textContent = pag.total_records;
        document.getElementById('dr-stat-range').textContent = pag.showing_from + ' – ' + pag.showing_to;
    }
    if (summary) {
        document.getElementById('dr-stat-qty').textContent   = fmt(summary.total_qty   || 0);
        document.getElementById('dr-stat-value').textContent = '£' + fmt(summary.total_value || 0);
    }
}

function renderPagination(pag) {
    var wrap = document.getElementById('dr-pag-wrap');
    if (!pag || pag.total_pages <= 1) { wrap.style.display = 'none'; return; }
    wrap.style.display = 'flex';
    document.getElementById('dr-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="drGoTo(1)">«</a><a onclick="drGoTo(' + (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="drGoTo(' + i + ')">' + i + '</a>';
    }
    if (e < tp) html += '<span>…</span>';
    html += cp < tp
        ? '<a onclick="drGoTo(' + (cp+1) + ')">›</a><a onclick="drGoTo(' + tp + ')">»</a>'
        : '<span class="disabled">›</span><span class="disabled">»</span>';

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

window.drGoTo = function (p) { currentPage = p; saveFilters(); drLoad(false); };

window.drReset = function () {
    ['dr-f-from','dr-f-to','dr-f-part','dr-f-order','dr-f-invoice'].forEach(function(id) {
        document.getElementById(id).value = '';
    });
    document.getElementById('dr-per-page').value = '25';
    currentPage = 1;
    try { sessionStorage.removeItem(FILTER_KEY); } catch(e) {}
    highlightFilters();
    drLoad(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();
drLoad(false);

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

})();
</script>