<?php
// ── Toast session message ──
if (isset($_SESSION['info_message'])) { ?>
    <script>
        $(document).ready(function () {
            Toastify({
                text: "<?php echo $_SESSION['info_message']; ?>",
                duration: 2000, close: true, gravity: "top", position: 'right',
                backgroundColor: "#28a745",
                style: { borderBottom: "3px solid white" }
            }).showToast();
            <?php unset($_SESSION['info_message']); ?>
        });
    </script>
<?php } ?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastify-js/1.12.0/toastify.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastify-js/1.12.0/toastify.min.js"></script>

<style>
/* ── Page layout ── */
.scrap-page          { padding: 10px; }
.section-card        { background: #fff; border: 1px solid #dee2e6; border-radius: 6px; padding: 1rem; margin-bottom: 1rem; }
.section-head        { font-size: 12px; font-weight: 700; text-transform: uppercase;
                       letter-spacing: .06em; color: #fff; background: #9C4893;
                       display: inline-block; padding: 3px 10px; border-radius: 3px;
                       margin-bottom: .75rem; }

/* ── Stat cards ── */
.stat-row            { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px,1fr));
                       gap: .6rem; margin-bottom: 1rem; }
.stat-box            { background: #f8f9fa; border-left: 4px solid #c00000;
                       border-radius: 5px; padding: .75rem 1rem; }
.stat-box.blue       { border-left-color: #007bff; }
.stat-box.green      { border-left-color: #28a745; }
.stat-box.orange     { border-left-color: #fd7e14; }
.stat-box .s-label   { font-size: 11px; text-transform: uppercase; color: #888; }
.stat-box .s-val     { font-size: 22px; font-weight: 700; color: #222; margin-top: 2px; }

/* ── Tables ── */
.scrap-table         { font-size: 13px; }
.scrap-table th      { background: #f0f0f0; text-align: center;
                       vertical-align: middle !important; white-space: nowrap; }
.scrap-table td      { text-align: center; vertical-align: middle !important; }
.scrap-table .col-date { text-align: left; font-weight: 500; white-space: nowrap; }
.scrap-table .row-total { background: #e9ecef; font-weight: 700; }
.scrap-table .row-value { background: #d4edda; font-weight: 700; color: #155724; }
.scrap-table .red-cell  { color: #c00000; font-weight: 600; }

/* ── Price table ── */
.price-ref-table     { font-size: 13px; }
.price-ref-table th  { background: #c00000; color: #fff; }

/* ── Filter bar ── */
.filter-bar          { display: flex; flex-wrap: wrap; gap: .4rem;
                       align-items: flex-end; margin-bottom: .75rem; }
.filter-bar label    { font-size: 11px; color: #666; margin-bottom: 2px; display: block; }
.filter-bar .form-group { margin: 0; }

/* ── Nav tabs ── */
.nav-tabs .nav-link        { color: #666; font-size: 13px; }
.nav-tabs .nav-link.active { font-weight: 700; color: #c00000;
                             border-bottom-color: #c00000; }

/* ── Spinner ── */
#loadingOverlay { display: none; position: fixed; inset: 0;
                  background: rgba(0,0,0,.3); z-index: 9999;
                  align-items: center; justify-content: center; }
#loadingOverlay.show { display: flex; }

/* ── Modal header colour ── */
.modal-header.purple-head { background: #9C4893; color: #fff; }
.modal-header.purple-head .close { color: #fff; }

/* ── Weight inputs grid ── */
#weight-inputs .form-group label { font-size: 12px; font-weight: 600; }
</style>

<!-- ── Loading overlay ── -->
<div id="loadingOverlay">
    <div class="spinner-border text-light" role="status">
        <span class="sr-only">Loading...</span>
    </div>
</div>

<section class="content-header">
    <div class="container-fluid">
        <div class="row align-items-center">
            <div class="col-sm-6">
                <h1 style="margin:0;font-size:22px;">
                    <i class="fas fa-recycle text-danger mr-2"></i>
                    Scrap Sales
                </h1>
            </div>
            <div class="col-sm-6 text-right">
                <button class="btn btn-lg btn-primary" onclick="openAddModal()">
                    <i class="fas fa-plus mr-1"></i>Add Collection
                </button>
                <button class="btn btn-sm btn-outline-secondary ml-1" onclick="exportCSV()">
                    <i class="fas fa-file-csv mr-1"></i>Export CSV
                </button>
            </div>
        </div>
    </div>
</section>

<section class="content scrap-page">
<div class="container-fluid">

    <!-- Tabs -->
    <ul class="nav nav-tabs mb-3" id="scrapTabs">
        <li class="nav-item">
            <a class="nav-link active" data-toggle="tab" href="#tab-dashboard">
                <i class="fas fa-chart-bar mr-1"></i>Dashboard
            </a>
        </li>
        <li class="nav-item">
            <a class="nav-link" data-toggle="tab" href="#tab-prices">
                <i class="fas fa-pound-sign mr-1"></i>Scrap Prices
            </a>
        </li>
    </ul>

    <div class="tab-content">

        <!-- ══════════ DASHBOARD TAB ══════════ -->
        <div class="tab-pane fade show active" id="tab-dashboard">

            <!-- Stat cards -->
            <div class="stat-row">
                <div class="stat-box">
                    <div class="s-label">Collections</div>
                    <div class="s-val" id="stat-count">—</div>
                </div>
                <div class="stat-box blue">
                    <div class="s-label">Total Weight (kg)</div>
                    <div class="s-val" id="stat-weight">—</div>
                </div>
                <div class="stat-box green">
                    <div class="s-label">Total Value</div>
                    <div class="s-val" id="stat-value">—</div>
                </div>
                <div class="stat-box orange">
                    <div class="s-label">Avg £ / kg</div>
                    <div class="s-val" id="stat-avg">—</div>
                </div>
            </div>

            <!-- Filter bar -->
            <div class="filter-bar">
                <div class="form-group">
                    <label>From Date</label>
                    <input type="date" id="filter-from" class="form-control form-control-sm" style="width:145px">
                </div>
                <div class="form-group">
                    <label>To Date</label>
                    <input type="date" id="filter-to" class="form-control form-control-sm" style="width:145px">
                </div>
                <button class="btn btn-sm btn-primary" onclick="loadCollections()">
                    <i class="fas fa-filter mr-1"></i>Filter
                </button>
                <button class="btn btn-sm btn-outline-secondary" onclick="clearFilter()">
                    <i class="fas fa-times mr-1"></i>Clear
                </button>
            </div>

            <!-- Collections Table -->
            <div class="section-card">
                <div class="section-head">Collection Records</div>
                <div class="table-responsive">
                    <table class="table table-bordered table-sm scrap-table" id="collectionsTable">
                        <thead id="collections-head">
                            <tr>
                                <th style="text-align:left">Date</th>
                                <th>Total (kg)</th>
                                <th>Value (£)</th>
                                <th>Notes</th>
                                <th style="width:80px">Action</th>
                            </tr>
                        </thead>
                        <tbody id="collections-body">
                            <tr>
                                <td colspan="5" class="text-center text-muted py-3">
                                    <div class="spinner-border spinner-border-sm" role="status"></div>
                                    Loading...
                                </td>
                            </tr>
                        </tbody>
                        <tfoot id="collections-foot"></tfoot>
                    </table>
                </div>
            </div>

        </div><!-- /dashboard tab -->

        <!-- ══════════ PRICES TAB ══════════ -->
        <div class="tab-pane fade" id="tab-prices">
            <div class="row">

                <!-- Edit prices -->
                <div class="col-md-5">
                    <div class="section-card">
                        <div class="section-head">Update Scrap Values (£ / kg)</div>
                        <form id="prices-form">
                            <div id="prices-inputs">
                                <div class="text-center p-3">
                                    <div class="spinner-border spinner-border-sm" role="status"></div>
                                    Loading...
                                </div>
                            </div>
                            <button type="submit" class="btn btn-sm btn-primary mt-2">
                                <i class="fas fa-save mr-1"></i>Save Prices
                            </button>
                        </form>
                    </div>
                </div>

                <!-- Price reference table -->
                <div class="col-md-4">
                    <div class="section-card">
                        <div class="section-head">Current Price Reference</div>
                        <table class="table table-bordered table-sm price-ref-table">
                            <thead>
                                <tr>
                                    <th>Material</th>
                                    <th>£ / kg</th>
                                    <th>Last Updated</th>
                                </tr>
                            </thead>
                            <tbody id="price-ref-body">
                                <tr><td colspan="3" class="text-center text-muted">Loading...</td></tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Price change history -->
                <div class="col-md-12 mt-3">
                    <div class="section-card">
                        <div class="section-head">Price Change History</div>
                        <div class="table-responsive">
                            <table class="table table-bordered table-sm scrap-table" id="priceHistoryTable" style="font-size:12px;">
                                <thead id="price-history-head">
                                    <tr>
                                        <th>Date / Time</th>
                                        <th colspan="99">Loading materials...</th>
                                    </tr>
                                </thead>
                                <tbody id="price-history-body">
                                    <tr><td colspan="10" class="text-center text-muted">Loading...</td></tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

            </div>
        </div><!-- /prices tab -->

    </div><!-- /tab-content -->

</div>
</section>

<!-- ══════════ ADD / EDIT MODAL ══════════ -->
<div class="modal fade" id="collectionModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">

            <div class="modal-header purple-head">
                <h5 class="modal-title" id="collectionModalTitle">
                    <i class="fas fa-plus mr-2"></i>Add Collection
                </h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span style="color:#fff;">&times;</span>
                </button>
            </div>

            <div class="modal-body">
                <input type="hidden" id="edit-id">

                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label style="font-size:12px;font-weight:600;">
                                Collection Date <span class="text-primary">*</span>
                            </label>
                            <input type="date" class="form-control form-control-sm" id="inp-date" required>
                        </div>
                    </div>
                    <div class="col-md-8">
                        <div class="form-group">
                            <label style="font-size:12px;font-weight:600;">Notes (optional)</label>
                            <input type="text" class="form-control form-control-sm" id="inp-notes"
                                placeholder="Any remarks about this collection…">
                        </div>
                    </div>
                </div>

                <div class="section-head mt-1">Material Weights (kg)</div>

                <!-- Dynamically rendered weight inputs -->
                <div class="row mt-2" id="weight-inputs">
                    <div class="col-12 text-center text-muted py-2">
                        <div class="spinner-border spinner-border-sm" role="status"></div>
                        Loading materials...
                    </div>
                </div>

                <!-- Live value preview -->
                <div class="alert alert-success py-2 mt-2" style="font-size:13px;margin-bottom:0;">
                    <strong>Estimated Value:</strong>
                    <span id="preview-value">£0.00</span>
                    &nbsp;|&nbsp;
                    <strong>Total Weight:</strong>
                    <span id="preview-kg">0 kg</span>
                </div>
            </div>

            <div class="modal-footer py-2">
                <button type="button" class="btn btn-sm btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-sm btn-primary" onclick="saveCollection()">
                    <i class="fas fa-save mr-1"></i>Save Collection
                </button>
            </div>

        </div>
    </div>
</div>

<script>
// ── URL (same pattern as your other modules) ──────────────
var AJAX_URL = site_url + '/modules/report_management/index.php?page=ajax_scrap_sales';

// ── State ─────────────────────────────────────────────────
var SCRAP_ITEMS   = [];   // [{id, scrap_item, slug}, ...]  — populated from DB
var currentPrices = {};   // {slug: price}

// ── Slug helper (mirrors PHP slugKey) ────────────────────
function slugKey(name) {
    return name.toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_|_$/g, '');
}

// ── Format helpers ────────────────────────────────────────
function fmtNum(n) {
    return parseFloat(n || 0).toLocaleString('en-GB', {minimumFractionDigits: 0, maximumFractionDigits: 2});
}
function fmtGBP(n) {
    return '£' + parseFloat(n || 0).toFixed(2);
}
function fmtDate(iso) {
    if (!iso) return '';
    var p = iso.split('-');
    return p[2] + '.' + p[1] + '.' + p[0].slice(2);
}
function escapeHtml(text) {
    if (text === null || text === undefined) return '';
    var div = document.createElement('div');
    div.textContent = String(text);
    return div.innerHTML;
}

// ── Toast ─────────────────────────────────────────────────
function showToast(msg, ok) {
    ok = (ok === undefined) ? true : ok;
    Toastify({
        text: msg, duration: 2500, close: true,
        gravity: 'top', position: 'right',
        backgroundColor: ok ? '#28a745' : '#dc3545',
        style: { borderBottom: '3px solid rgba(0,0,0,.15)' }
    }).showToast();
}

function loading(show) {
    if (show) $('#loadingOverlay').addClass('show');
    else      $('#loadingOverlay').removeClass('show');
}

// ── Init materials from items array ──────────────────────
function initMaterials(items) {
    SCRAP_ITEMS = items.map(function(i) {
        return { id: i.id, label: i.scrap_item, slug: slugKey(i.scrap_item) };
    });
}

// ── Render weight inputs in modal ────────────────────────
function renderWeightInputs() {
    if (!SCRAP_ITEMS.length) {
        $('#weight-inputs').html('<div class="col-12 text-center text-danger">No materials found. Please add items in Admin.</div>');
        return;
    }
    var html = '';
    $.each(SCRAP_ITEMS, function(i, item) {
        html += '<div class="col-md-4">';
        html += '<div class="form-group">';
        html += '<label>' + escapeHtml(item.label) + ' (kg)</label>';
        html += '<input type="number" class="form-control form-control-sm weight-field"';
        html += ' id="inp-' + item.slug + '"';
        html += ' data-slug="' + item.slug + '"';
        html += ' min="0" step="0.01" placeholder="0"';
        html += ' oninput="updatePreview()">';
        html += '</div></div>';
    });
    $('#weight-inputs').html(html);
}

// ══════════════════════════════════════════════════════════
// LOAD COLLECTIONS
// ══════════════════════════════════════════════════════════
function loadCollections() {
    loading(true);

    var postData = { action: 'get_scrap_collections' };
    var from = $('#filter-from').val();
    var to   = $('#filter-to').val();
    if (from) postData.from = from;
    if (to)   postData.to   = to;

    $.ajax({
        url:      AJAX_URL + '&action=get_scrap_collections',
        method:   'POST',
        data:     postData,
        dataType: 'json',
        success: function(response) {
            if (response.status === 'success') {
                // Init materials if not yet set
                if (response.items && response.items.length && !SCRAP_ITEMS.length) {
                    initMaterials(response.items);
                    renderWeightInputs();
                }
                currentPrices = response.prices || {};
                renderStats(response.totals, response.count);
                renderCollectionsTable(response.data, response.totals);
            } else {
                showToast(response.message || 'Failed to load collections.', false);
            }
        },
        error: function(xhr, status, error) {
            console.error('AJAX Error:', error, xhr.responseText);
            showToast('Error loading collections.', false);
        },
        complete: function() {
            loading(false);
        }
    });
}

function renderStats(totals, count) {
    $('#stat-count').text(count);
    $('#stat-weight').text(fmtNum(totals.total_kg));
    $('#stat-value').text(fmtGBP(totals.total_value));
    var avg = totals.total_kg > 0 ? totals.total_value / totals.total_kg : 0;
    $('#stat-avg').text(fmtGBP(avg));
}

function renderCollectionsTable(rows, totals) {
    // ── Build dynamic header ──────────────────────────────
    var thHtml = '<tr>';
    thHtml += '<th style="text-align:left">Date</th>';
    $.each(SCRAP_ITEMS, function(i, item) {
        thHtml += '<th>' + escapeHtml(item.label) + ' (kg)</th>';
    });
    thHtml += '<th>Total (kg)</th>';
    thHtml += '<th>Value (£)</th>';
    thHtml += '<th>Notes</th>';
    thHtml += '<th style="width:80px">Action</th>';
    thHtml += '</tr>';
    $('#collections-head').html(thHtml);

    var tbody = $('#collections-body');
    var tfoot = $('#collections-foot');
    var colSpan = SCRAP_ITEMS.length + 5;   // date + materials + total + value + notes + action

    if (!rows || rows.length === 0) {
        tbody.html('<tr><td colspan="' + colSpan + '" class="text-center text-muted py-3">' +
                   'No collections found. Add one using the button above.</td></tr>');
        tfoot.html('');
        return;
    }

    var html = '';
    $.each(rows, function(i, r) {
        html += '<tr>';
        html += '<td class="col-date">' + fmtDate(r.collection_date) + '</td>';
        $.each(SCRAP_ITEMS, function(j, item) {
            var val = parseFloat(r['weight_' + item.slug] || 0);
            html += '<td>' + fmtNum(val) + '</td>';
        });
        html += '<td><strong>' + fmtNum(r.total_kg) + '</strong></td>';
        html += '<td><strong class="text-success">' + fmtGBP(r.total_value) + '</strong></td>';
        html += '<td style="font-size:11px;color:#888;max-width:120px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">';
        html += (r.notes ? escapeHtml(r.notes) : '') + '</td>';
        html += '<td>';
        html += '<button class="btn btn-xs btn-outline-primary mr-1" onclick="openEditModal(' + r.id + ')" title="Edit">';
        html += '<i class="fas fa-edit"></i></button>';
        html += '<button class="btn btn-xs btn-outline-danger" onclick="deleteCollection(' + r.id + ')" title="Delete">';
        html += '<i class="fas fa-trash"></i></button>';
        html += '</td>';
        html += '</tr>';
    });
    tbody.html(html);

    // ── Totals footer ─────────────────────────────────────
    var footHtml = '<tr class="row-total">';
    footHtml += '<td class="col-date">Total Weight</td>';
    $.each(SCRAP_ITEMS, function(i, item) {
        footHtml += '<td>' + fmtNum(totals['weight_' + item.slug] || 0) + '</td>';
    });
    footHtml += '<td><strong>' + fmtNum(totals.total_kg) + '</strong></td>';
    footHtml += '<td></td><td></td><td></td></tr>';

    // ── Value footer ──────────────────────────────────────
    footHtml += '<tr class="row-value">';
    footHtml += '<td class="col-date">Value (£)</td>';
    $.each(SCRAP_ITEMS, function(i, item) {
        var w = parseFloat(totals['weight_' + item.slug] || 0);
        var p = parseFloat(currentPrices[item.slug] || 0);
        footHtml += '<td>' + fmtGBP(w * p) + '</td>';
    });
    footHtml += '<td></td>';
    footHtml += '<td><strong>' + fmtGBP(totals.total_value) + '</strong></td>';
    footHtml += '<td></td><td></td></tr>';

    tfoot.html(footHtml);
}

function clearFilter() {
    $('#filter-from').val('');
    $('#filter-to').val('');
    loadCollections();
}

// ══════════════════════════════════════════════════════════
// LOAD PRICES
// ══════════════════════════════════════════════════════════
function loadPrices() {
    $.ajax({
        url:      AJAX_URL + '&action=get_scrap_prices',
        method:   'POST',
        data:     { action: 'get_scrap_prices' },
        dataType: 'json',
        success: function(response) {
            if (response.status !== 'success') return;

            // Init materials from prices response if not yet done
            if (response.items && response.items.length && !SCRAP_ITEMS.length) {
                initMaterials(response.items);
                renderWeightInputs();
            }

            // ── Build price edit form ─────────────────────
            var inputsHtml = '';
            var refHtml    = '';

            // Map latest prices by slug for easy lookup
            var latestBySlug = {};
            $.each(response.data, function(i, p) {
                latestBySlug[p.material_slug] = p;
                currentPrices[p.material_slug] = parseFloat(p.price_per_kg);
            });

            // Render in the order of SCRAP_ITEMS so label matches
            $.each(SCRAP_ITEMS, function(i, item) {
                var p = latestBySlug[item.slug] || {};
                var priceVal = p.price_per_kg ? parseFloat(p.price_per_kg).toFixed(4) : '0.0000';
                var updDate  = p.updated_at
                    ? new Date(p.updated_at).toLocaleString('en-GB')
                    : '—';

                // Edit form row
                inputsHtml += '<div class="form-group row align-items-center mb-2">';
                inputsHtml += '<label class="col-4 mb-0" style="font-size:12px;font-weight:600;">' +
                              escapeHtml(item.label) + '</label>';
                inputsHtml += '<div class="col-6"><div class="input-group input-group-sm">';
                inputsHtml += '<div class="input-group-prepend"><span class="input-group-text">£</span></div>';
                inputsHtml += '<input type="number" class="form-control form-control-sm"' +
                              ' name="price_' + item.slug + '"' +
                              ' step="0.001" min="0" value="' + priceVal + '">';
                inputsHtml += '</div></div></div>';

                // Reference table row
                refHtml += '<tr>';
                refHtml += '<td><strong>' + escapeHtml(item.label) + '</strong></td>';
                refHtml += '<td class="text-success font-weight-bold">' + fmtGBP(p.price_per_kg || 0) + '</td>';
                refHtml += '<td style="font-size:11px;color:#888;">' + updDate + '</td>';
                refHtml += '</tr>';
            });

            $('#prices-inputs').html(inputsHtml || '<p class="text-muted">No materials found.</p>');
            $('#price-ref-body').html(refHtml   || '<tr><td colspan="3" class="text-center text-muted">No prices set yet.</td></tr>');

            // ── Price history table ───────────────────────
            // Build header
            var histHead = '<tr><th>Date / Time</th>';
            $.each(SCRAP_ITEMS, function(i, item) {
                histHead += '<th>' + escapeHtml(item.label) + '</th>';
            });
            histHead += '</tr>';
            $('#price-history-head').html(histHead);

            // Group history rows by timestamp snapshot_id
            var grouped  = {};
            var tsOrder  = [];
            $.each(response.history || [], function(i, p) {
                var ts = p.snapshot_id || p.updated_at;
                if (!grouped[ts]) {
                    grouped[ts] = { ts: p.updated_at || ts };
                    tsOrder.push(ts);
                }
                grouped[ts][p.material_slug] = parseFloat(p.price_per_kg).toFixed(4);
            });

            var histHtml = '';
            $.each(tsOrder, function(i, ts) {
                var row = grouped[ts];
                var dt  = row.ts ? new Date(row.ts).toLocaleString('en-GB') : ts;
                histHtml += '<tr>';
                histHtml += '<td style="white-space:nowrap;color:#555;">' + dt + '</td>';
                $.each(SCRAP_ITEMS, function(j, item) {
                    histHtml += '<td>' + (row[item.slug] !== undefined ? '£' + row[item.slug] : '—') + '</td>';
                });
                histHtml += '</tr>';
            });

            var cols = SCRAP_ITEMS.length + 1;
            $('#price-history-body').html(
                histHtml || '<tr><td colspan="' + cols + '" class="text-center text-muted">No history yet.</td></tr>'
            );
        },
        error: function() {
            console.error('Load prices error');
        }
    });
}

// ── Save prices ───────────────────────────────────────────
$('#prices-form').on('submit', function(e) {
    e.preventDefault();

    var postData = { action: 'update_scrap_prices' };
    $.each(SCRAP_ITEMS, function(i, item) {
        var el = $('[name="price_' + item.slug + '"]');
        if (el.length) postData['slug_' + item.slug] = parseFloat(el.val()) || 0;
    });

    loading(true);

    $.ajax({
        url:      AJAX_URL + '&action=update_scrap_prices',
        method:   'POST',
        data:     postData,
        dataType: 'json',
        success: function(response) {
            if (response.status === 'success') {
                showToast(response.message || 'Prices updated.');
                loadPrices();
                loadCollections();
            } else {
                showToast(response.message || 'Update failed.', false);
            }
        },
        error: function(xhr, status, error) {
            console.error('Price save error:', error);
            showToast('Network error.', false);
        },
        complete: function() {
            loading(false);
        }
    });
});

// ══════════════════════════════════════════════════════════
// ADD / EDIT MODAL
// ══════════════════════════════════════════════════════════
function openAddModal() {
    $('#edit-id').val('');
    $('#inp-date').val(new Date().toISOString().slice(0, 10));
    $('#inp-notes').val('');
    $.each(SCRAP_ITEMS, function(i, item) {
        $('#inp-' + item.slug).val('');
    });
    $('#collectionModalTitle').html('<i class="fas fa-plus mr-2"></i>Add Collection');
    updatePreview();
    $('#collectionModal').modal('show');
}

function openEditModal(id) {
    loading(true);

    $.ajax({
        url:      AJAX_URL + '&action=get_single_collection',
        method:   'POST',
        data:     { action: 'get_single_collection', id: id },
        dataType: 'json',
        success: function(response) {
            if (response.status === 'success') {
                var r = response.data;
                $('#edit-id').val(r.id);
                $('#inp-date').val(r.collection_date);
                $('#inp-notes').val(r.notes || '');
                $.each(SCRAP_ITEMS, function(i, item) {
                    $('#inp-' + item.slug).val(parseFloat(r['weight_' + item.slug]) || '');
                });
                $('#collectionModalTitle').html('<i class="fas fa-edit mr-2"></i>Edit Collection');
                updatePreview();
                $('#collectionModal').modal('show');
            } else {
                showToast(response.message || 'Could not load record.', false);
            }
        },
        error: function(xhr, status, error) {
            console.error('Edit load error:', error);
            showToast('Error loading record.', false);
        },
        complete: function() {
            loading(false);
        }
    });
}

function updatePreview() {
    var totalKg = 0, totalVal = 0;
    $.each(SCRAP_ITEMS, function(i, item) {
        var v = parseFloat($('#inp-' + item.slug).val()) || 0;
        totalKg  += v;
        totalVal += v * (currentPrices[item.slug] || 0);
    });
    $('#preview-value').text(fmtGBP(totalVal));
    $('#preview-kg').text(fmtNum(totalKg) + ' kg');
}

function saveCollection() {
    var id   = $('#edit-id').val();
    var date = $('#inp-date').val();

    if (!date) {
        showToast('Please select a collection date.', false);
        return;
    }

    var postData = {
        action:          id ? 'update_scrap_collection' : 'save_scrap_collection',
        collection_date: date,
        notes:           $('#inp-notes').val()
    };
    if (id) postData.id = id;

    $.each(SCRAP_ITEMS, function(i, item) {
        postData['weight_' + item.slug] = parseFloat($('#inp-' + item.slug).val()) || 0;
    });

    loading(true);

    $.ajax({
        url:      AJAX_URL + '&action=' + postData.action,
        method:   'POST',
        data:     postData,
        dataType: 'json',
        success: function(response) {
            if (response.status === 'success') {
                showToast(response.message || 'Saved successfully.');
                $('#collectionModal').modal('hide');
                loadCollections();
            } else {
                showToast(response.message || 'Save failed.', false);
            }
        },
        error: function(xhr, status, error) {
            console.error('Save error:', error, xhr.responseText);
            showToast('Network error saving collection.', false);
        },
        complete: function() {
            loading(false);
        }
    });
}

function deleteCollection(id) {
    if (!confirm('Delete this collection entry? This cannot be undone.')) return;

    loading(true);

    $.ajax({
        url:      AJAX_URL + '&action=delete_scrap_collection',
        method:   'POST',
        data:     { action: 'delete_scrap_collection', id: id },
        dataType: 'json',
        success: function(response) {
            if (response.status === 'success') {
                showToast('Collection deleted.');
                loadCollections();
            } else {
                showToast(response.message || 'Delete failed.', false);
            }
        },
        error: function(xhr, status, error) {
            console.error('Delete error:', error);
            showToast('Error deleting collection.', false);
        },
        complete: function() {
            loading(false);
        }
    });
}

// ══════════════════════════════════════════════════════════
// EXPORT CSV
// ══════════════════════════════════════════════════════════
function exportCSV() {
    $.ajax({
        url:      AJAX_URL + '&action=get_scrap_collections',
        method:   'POST',
        data:     { action: 'get_scrap_collections' },
        dataType: 'json',
        success: function(response) {
            if (response.status !== 'success' || !response.data.length) {
                showToast('No data to export.', false);
                return;
            }

            var headers = ['Date'];
            $.each(SCRAP_ITEMS, function(i, item) { headers.push(item.label + ' (kg)'); });
            headers.push('Total KG', 'Value GBP', 'Notes');

            var lines = [headers.join(',')];

            $.each(response.data, function(i, r) {
                var row = [fmtDate(r.collection_date)];
                $.each(SCRAP_ITEMS, function(j, item) {
                    row.push(r['weight_' + item.slug] || 0);
                });
                row.push(r.total_kg, r.total_value);
                row.push('"' + (r.notes || '').replace(/"/g, '""') + '"');
                lines.push(row.join(','));
            });

            var t = response.totals;
            var totRow = ['TOTAL WEIGHT'];
            $.each(SCRAP_ITEMS, function(i, item) {
                totRow.push(t['weight_' + item.slug] || 0);
            });
            totRow.push(t.total_kg, '', '');
            lines.push(totRow.join(','));

            var valRow = ['VALUE'];
            $.each(SCRAP_ITEMS, function(i, item) {
                var w = parseFloat(t['weight_' + item.slug] || 0);
                var p = parseFloat(currentPrices[item.slug] || 0);
                valRow.push(fmtGBP(w * p));
            });
            valRow.push('', fmtGBP(t.total_value), '');
            lines.push(valRow.join(','));

            var blob = new Blob([lines.join('\n')], { type: 'text/csv' });
            var url  = URL.createObjectURL(blob);
            var a    = document.createElement('a');
            a.href     = url;
            a.download = 'scrap_sales_' + new Date().toISOString().slice(0, 10) + '.csv';
            a.click();
            URL.revokeObjectURL(url);
            showToast('CSV exported.');
        },
        error: function() {
            showToast('Error exporting CSV.', false);
        }
    });
}

// ══════════════════════════════════════════════════════════
// INIT
// ══════════════════════════════════════════════════════════
$(document).ready(function() {
    // Load prices first so materials are ready before collections render
    $.ajax({
        url:      AJAX_URL + '&action=get_scrap_prices',
        method:   'POST',
        data:     { action: 'get_scrap_prices' },
        dataType: 'json',
        success: function(response) {
            if (response.status === 'success' && response.items) {
                initMaterials(response.items);
                renderWeightInputs();

                // Set current prices
                $.each(response.data, function(i, p) {
                    currentPrices[p.material_slug] = parseFloat(p.price_per_kg);
                });

                // Now load collections with materials ready
                loadCollections();

                // Also fully render the prices tab
                loadPrices();
            }
        },
        error: function() {
            loadCollections();
            loadPrices();
        }
    });

    // Auto-refresh every 60 seconds
    setInterval(function() {
        loadCollections();
    }, 60000);
});
</script>