<?php
require_once __DIR__ . '/../config/user_functions.php';

session_start();
if (!isset($_SESSION['user'])) { header('Location: /smproduce/auth/login.php'); exit; }
$role = $_SESSION['user']['role'] ?? 'viewer';
if (!in_array($role, ['admin','warehouse'])) { http_response_code(403); die('Forbidden'); }

require_once __DIR__ . '/../config/db_remote.php';


/*-----------------------------------------
  AJAX: ADD PRESET (GROWER / TYPE) - JSON
-----------------------------------------*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_action'])) {
    header('Content-Type: application/json; charset=utf-8');

    if ($role !== 'admin') {
        echo json_encode(['ok' => false, 'error' => 'Forbidden']);
        exit;
    }

    $ajax = trim($_POST['ajax_action'] ?? '');
    $name = trim($_POST['name'] ?? '');

    if ($name === '') {
        echo json_encode(['ok' => false, 'error' => 'Missing name']);
        exit;
    }

    $nameEsc = $mysqli->real_escape_string($name);

    if ($ajax === 'add_grower') {
        $mysqli->query("INSERT IGNORE INTO growers_list(name) VALUES('$nameEsc')");
        echo json_encode(['ok' => true, 'name' => $name]);
        exit;
    }

    if ($ajax === 'add_type') {
        $mysqli->query("INSERT IGNORE INTO bin_types_list(name) VALUES('$nameEsc')");
        echo json_encode(['ok' => true, 'name' => $name]);
        exit;
    }

    echo json_encode(['ok' => false, 'error' => 'Unknown action']);
    exit;
}

$messages = [];
$errors   = [];

/*-----------------------------------------
  PRESET TABLES (ID-BASED) - sicurezza
-----------------------------------------*/
$mysqli->query("
CREATE TABLE IF NOT EXISTS growers_list (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) UNIQUE NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
");

$mysqli->query("
CREATE TABLE IF NOT EXISTS bin_types_list (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) UNIQUE NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
");

/*-----------------------------------------
  EMPTY BINS LOG (se non esiste)
-----------------------------------------*/
$mysqli->query("
CREATE TABLE IF NOT EXISTS empty_bins_log (
    id INT AUTO_INCREMENT PRIMARY KEY,
    grower     VARCHAR(100) NOT NULL,
    type       VARCHAR(100) NOT NULL,
    qty_change INT NOT NULL,
    reason     VARCHAR(255) DEFAULT NULL,
    created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
");

/*-----------------------------------------
  LOAD PRESETS
-----------------------------------------*/
$growers = [];
$types   = [];

$res = $mysqli->query("SELECT id, name FROM growers_list ORDER BY name ASC");
if ($res) $growers = $res->fetch_all(MYSQLI_ASSOC);

$res = $mysqli->query("SELECT id, name FROM bin_types_list ORDER BY name ASC");
if ($res) $types = $res->fetch_all(MYSQLI_ASSOC);

/*-----------------------------------------
  POST ACTIONS
-----------------------------------------*/
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    /*------------------------------
      INLINE EDIT (AJAX)
    ------------------------------*/
    if (isset($_POST['inline_edit'])) {
        $id     = (int)($_POST['id'] ?? 0);
        $grower = $mysqli->real_escape_string(trim($_POST['grower'] ?? ''));
        $type   = $mysqli->real_escape_string(trim($_POST['type'] ?? ''));
        $date   = $mysqli->real_escape_string(trim($_POST['date'] ?? ''));
        $qty    = (int)($_POST['quantity'] ?? 0);

        if ($id <= 0 || $grower === '' || $type === '' || $date === '' || $qty <= 0) {
            echo "ERR";
            exit;
        }

        // prendo il record attuale per calcolare il delta
        $resOld = $mysqli->query("SELECT grower, type, quantity FROM empty_bins WHERE id = $id");
        if (!$resOld || !$resOldRow = $resOld->fetch_assoc()) {
            echo "ERR";
            exit;
        }
        $oldQty = (int)$resOldRow['quantity'];

        // aggiorno la riga
        $mysqli->query("
            UPDATE empty_bins
            SET grower = '$grower',
                type   = '$type',
                date   = '$date',
                quantity = $qty
            WHERE id = $id
        ");

        // loggo il movimento se cambia la quantità
        $diff = $qty - $oldQty;
        if ($diff !== 0) {
            $reason = $mysqli->real_escape_string('Inline edit via empty_bins_receiving');
            $mysqli->query("
                INSERT INTO empty_bins_log(grower, type, qty_change, reason)
                VALUES('$grower', '$type', $diff, '$reason')
            ");
        }

        echo "OK";
        exit;
    }

    /*------------------------------
      ADD NEW GROWER (preset)
    ------------------------------*/
    if (isset($_POST['add_grower']) && $role === 'admin') {
        $name = trim($_POST['new_grower'] ?? '');
        if ($name !== '') {
            $nameEsc = $mysqli->real_escape_string($name);
            $mysqli->query("INSERT IGNORE INTO growers_list(name) VALUES('$nameEsc')");
            $messages[] = "Grower added.";
        }
    }

    /*------------------------------
      SAVE EMPTY BINS (ADD)
    ------------------------------*/
    if (isset($_POST['save_empty'])) {
        $grower = trim($_POST['grower'] ?? '');
        $type   = trim($_POST['type'] ?? '');
        $date   = trim($_POST['date'] ?? '');
        $qty    = (int)($_POST['quantity'] ?? 0);

        if ($grower === '' || $type === '' || $date === '' || $qty <= 0) {
            $errors[] = "Grower, type, date and quantity are required.";
        } else {
            $g = $mysqli->real_escape_string($grower);
            $t = $mysqli->real_escape_string($type);
            $d = $mysqli->real_escape_string($date);

            $mysqli->query("
                INSERT INTO empty_bins(grower, type, date, quantity, created_at)
                VALUES('$g', '$t', '$d', $qty, NOW())
            ");

            // log movimento +
            $reason = $mysqli->real_escape_string('Manual add via empty_bins_receiving');
            $mysqli->query("
                INSERT INTO empty_bins_log(grower, type, qty_change, reason)
                VALUES('$g', '$t', $qty, '$reason')
            ");

            $messages[] = "Empty bins added.";
        }
    }

    /*------------------------------
      DELETE ROW
    ------------------------------*/
    if (isset($_POST['delete_row']) && $role === 'admin') {
        $id = (int)($_POST['delete_id'] ?? 0);
        if ($id > 0) {
            // leggo quantità prima di cancellare per log
            $resDel = $mysqli->query("SELECT grower, type, quantity FROM empty_bins WHERE id = $id");
            if ($resDel && $rowDel = $resDel->fetch_assoc()) {
                $g = $mysqli->real_escape_string($rowDel['grower']);
                $t = $mysqli->real_escape_string($rowDel['type']);
                $q = (int)$rowDel['quantity'];

                if ($q > 0) {
                    $reason = $mysqli->real_escape_string('Row deleted via empty_bins_receiving');
                    $mysqli->query("
                        INSERT INTO empty_bins_log(grower, type, qty_change, reason)
                        VALUES('$g', '$t', ".(-$q).", '$reason')
                    ");
                }
            }

            $mysqli->query("DELETE FROM empty_bins WHERE id = $id");
            $messages[] = "Record deleted.";
        }
    }
}

/*-----------------------------------------
  DASHBOARD QUANTITÀ PER GROWER + TYPE
-----------------------------------------*/
$totals = [];
$resTotals = $mysqli->query("
    SELECT grower, type, SUM(quantity) AS total_qty
    FROM empty_bins
    GROUP BY grower, type
    ORDER BY grower ASC, type ASC
");
if ($resTotals) {
    $totals = $resTotals->fetch_all(MYSQLI_ASSOC);
}

/*-----------------------------------------
  LOG MOVIMENTI (ultimi 50)
-----------------------------------------*/
$log_rows = [];
$resLog = $mysqli->query("
    SELECT grower, type, qty_change, reason, created_at
    FROM empty_bins_log
    ORDER BY created_at DESC
");
if ($resLog) {
    $log_rows = $resLog->fetch_all(MYSQLI_ASSOC);
}

/*-----------------------------------------
  LOAD TABLE EMPTY_BINS
-----------------------------------------*/
$rows = [];
$resRows = $mysqli->query("
    SELECT id, grower, type, date, quantity
    FROM empty_bins
    ORDER BY date DESC, id DESC
");
if ($resRows) {
    $rows = $resRows->fetch_all(MYSQLI_ASSOC);
}

include('../includes/header.php');
include('../includes/sidebar.php');
?>

<style>
.inline-edit-input {
    max-width: 140px;
}

/* DASHBOARD COMPACT (solo per le 2 card in alto) */
.compact-card-body {
    max-height: 260px;
    overflow-y: auto;
}

/* Sticky header nelle tabelle del dashboard */
.compact-card-body table thead th {
    position: sticky;
    top: 0;
    background: #fff;
    z-index: 2;
}
</style>

<div class="container-fluid">

    <h3 class="mb-3">Empty Bins Receiving</h3>

    <?php foreach ($messages as $m): ?>
        <div class="alert alert-success"><?= htmlspecialchars($m) ?></div>
    <?php endforeach; ?>

    <?php foreach ($errors as $m): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($m) ?></div>
    <?php endforeach; ?>

    <!-- =========================================
         DASHBOARD (IN ALTO)
    ========================================== -->
    <div class="row mb-4">
        <!-- Totals per Grower & Type -->
        <div class="col-md-6">
            <div class="card h-100 shadow-sm">
                <!-- MOD: header con toggle -->
                <div class="card-header fw-semibold d-flex justify-content-between align-items-center">
                    <span>Empty Bins by Grower &amp; Type (Current Balance)</span>
                    <button type="button"
                            class="btn btn-sm btn-outline-secondary js-toggle"
                            data-target="balance">−</button>
                </div>

                <!-- MOD: body con data-section + compatto -->
                <div class="card-body compact-card-body" data-section="balance">
                    <?php if (!empty($totals)): ?>
                        <div class="table-responsive">
                            <table class="table table-sm table-striped mb-0 align-middle">
                                <thead class="table-light">
                                    <tr>
                                        <th>Grower</th>
                                        <th>Type</th>
                                        <th class="text-end">Qty</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($totals as $t): ?>
                                        <tr>
                                            <td><?= htmlspecialchars($t['grower']) ?></td>
                                            <td><?= htmlspecialchars($t['type']) ?></td>
                                            <td class="text-end"><?= (int)$t['total_qty'] ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <span class="text-muted">No empty bins recorded.</span>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Movements Log -->
        <div class="col-md-6 mt-3 mt-md-0">
            <div class="card h-100 shadow-sm">
                <!-- MOD: header con toggle -->
                <div class="card-header fw-semibold d-flex justify-content-between align-items-center">
                    <span>Empty Bins Movements (Log)</span>
                    <div class="d-flex gap-2 align-items-center">
                        <select id="logLimitSelect" class="form-select form-select-sm" style="width:120px">
                            <option value="20">Last 20</option>
                            <option value="50">Last 50</option>
                            <option value="all">All</option>
                        </select>
                        <button type="button"
                            class="btn btn-sm btn-outline-secondary js-toggle"
                            data-target="log">−</button>
                    </div>
                </div>

                <!-- MOD: body con data-section + compatto -->
                <div class="card-body compact-card-body" data-section="log">
                    <?php if (!empty($log_rows)): ?>
                        <div class="table-responsive">
                            <table class="table table-sm mb-0 align-middle">
                                <thead class="table-light">
                                    <tr>
                                        <th>Date/Time</th>
                                        <th>Grower</th>
                                        <th>Type</th>
                                        <th class="text-end">Δ Qty</th>
                                        <th>Reason</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($log_rows as $lr): ?>
                                        <tr>
                                            <td><?= htmlspecialchars($lr['created_at']) ?></td>
                                            <td><?= htmlspecialchars($lr['grower']) ?></td>
                                            <td><?= htmlspecialchars($lr['type']) ?></td>
                                            <td class="text-end">
                                                <?php
                                                    $delta = (int)$lr['qty_change'];
                                                    $class = $delta >= 0 ? 'text-success' : 'text-danger';
                                                ?>
                                                <span class="<?= $class ?>"><?= $delta ?></span>
                                            </td>
                                            <td><?= htmlspecialchars($lr['reason'] ?? '') ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <span class="text-muted">No movements logged yet.</span>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div><!-- /row dashboard -->

    <!-- =========================================
         ADD EMPTY BINS
    ========================================== -->
    <div class="card shadow-sm mb-4">
        <div class="card-header fw-semibold">Add Empty Bins</div>
        <div class="card-body">
            <form method="post" class="row g-3">

                <!-- Grower -->
                <div class="col-md-4">
                    <label class="form-label fw-semibold">Grower</label>
                    <div class="input-group">
                        <select name="grower" id="growerSelect" class="form-select" required>
                            <option value="">Select...</option>
                            <?php foreach ($growers as $g): ?>
                                <option value="<?= htmlspecialchars($g['name']) ?>">
                                    <?= htmlspecialchars($g['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <?php if ($role === 'admin'): ?>
                        <button type="button"
                                class="btn btn-outline-primary btn-sm"
                                onclick="openMiniModal('modalGrower')">
                            + New
                        </button>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Type -->
                <div class="col-md-3">
                    <label class="form-label fw-semibold">Type</label>
                    <div class="input-group">
                        <select name="type" id="typeSelect" class="form-select" required>
                        <option value="">Select...</option>
                        <?php foreach ($types as $t): ?>
                            <option value="<?= htmlspecialchars($t['name']) ?>">
                                <?= htmlspecialchars($t['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                        <?php if ($role === 'admin'): ?>
                        <button type="button" class="btn btn-outline-primary btn-sm" onclick="openMiniModal('modalType')">+ New</button>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Date -->
                <div class="col-md-3">
                    <label class="form-label fw-semibold">Date</label>
                    <input type="date"
                           name="date"
                           class="form-control"
                           value="<?= date('Y-m-d') ?>"
                           required>
                </div>

                <!-- Quantity -->
                <div class="col-md-2">
                    <label class="form-label fw-semibold">Qty</label>
                    <input type="number"
                           name="quantity"
                           class="form-control"
                           value="1"
                           min="1"
                           required>
                </div>

                <div class="col-12">
                    <button class="btn btn-success" name="save_empty" value="1">
                        Save
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- =========================================
         EMPTY BINS LIST + FILTERS
    ========================================== -->
    <div class="card shadow-sm">
        <div class="card-header fw-semibold">Empty Bins List</div>
        <div class="card-body">

            <!-- FILTERS -->
            <div class="row g-3 mb-3">
                <div class="col-md-3">
                    <input id="filterSearch"
                           class="form-control"
                           placeholder="🔍 Search (grower / type)">
                </div>

                <div class="col-md-3">
                    <select id="filterGrower" class="form-select">
                        <option value="">All Growers</option>
                        <?php foreach ($growers as $g): ?>
                            <option value="<?= htmlspecialchars($g['name']) ?>">
                                <?= htmlspecialchars($g['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-3">
                    <select id="filterType" class="form-select">
                        <option value="">All Types</option>
                        <?php foreach ($types as $t): ?>
                            <option value="<?= htmlspecialchars($t['name']) ?>">
                                <?= htmlspecialchars($t['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-3">
                    <input id="filterDate"
                           type="date"
                           class="form-control">
                </div>
            </div>

            <!-- TABLE -->
            <div class="table-responsive">
                <table class="table table-striped align-middle">
                    <thead class="table-light">
                        <tr>
                            <th>ID</th>
                            <th>Grower</th>
                            <th>Type</th>
                            <th>Date</th>
                            <th>Qty</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="emptyBinsTable">
                        <?php foreach ($rows as $r): ?>
                            <tr data-id="<?= (int)$r['id'] ?>"
                                data-grower="<?= htmlspecialchars($r['grower']) ?>"
                                data-type="<?= htmlspecialchars($r['type']) ?>"
                                data-date="<?= htmlspecialchars($r['date']) ?>">

                                <td><?= (int)$r['id'] ?></td>
                                <td class="cell-grower"><?= htmlspecialchars($r['grower']) ?></td>
                                <td class="cell-type"><?= htmlspecialchars($r['type']) ?></td>
                                <td class="cell-date"><?= htmlspecialchars($r['date']) ?></td>
                                <td class="cell-qty"><?= (int)$r['quantity'] ?></td>

                                <td class="cell-actions">
                                    <button type="button"
                                            class="btn btn-sm btn-warning"
                                            onclick="editRow(<?= (int)$r['id'] ?>)">
                                        Edit
                                    </button>

                                    <?php if ($role === 'admin'): ?>
                                    <form method="post"
                                          class="d-inline"
                                          onsubmit="return confirm('Delete this row?');">
                                        <input type="hidden" name="delete_row" value="1">
                                        <input type="hidden" name="delete_id" value="<?= (int)$r['id'] ?>">
                                        <button class="btn btn-sm btn-danger">Delete</button>
                                    </form>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>

                        <?php if (empty($rows)): ?>
                            <tr>
                                <td colspan="6" class="text-center text-muted py-3">
                                    No empty bins recorded.
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

        </div>
    </div>

</div>

<!-- MODAL ADD GROWER -->
<div class="modal fade" id="addGrowerModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <form class="modal-content" method="post">
      <input type="hidden" name="add_grower" value="1">
      <div class="modal-header">
        <h5 class="modal-title">Add Grower</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <label class="form-label">Grower Name</label>
        <input type="text" class="form-control" name="new_grower" required>
      </div>
      <div class="modal-footer">
        <button class="btn btn-success">Save</button>
      </div>
    </form>
  </div>
</div>


<!-- MINI MODALS (+ New) -->
<style>
.mini-modal{display:none;position:fixed;inset:0;background:rgba(0,0,0,.55);z-index:9999;align-items:center;justify-content:center;padding:20px;}
.mini-modal.show{display:flex;}
.mini-box{background:#fff;width:100%;max-width:420px;border-radius:10px;overflow:hidden;box-shadow:0 12px 40px rgba(0,0,0,.25);}
.mini-head{padding:12px 16px;font-weight:600;border-bottom:1px solid #e7e7e7;display:flex;justify-content:space-between;align-items:center;}
.mini-body{padding:16px;}
.mini-close{border:0;background:transparent;font-size:22px;cursor:pointer;line-height:1;}
</style>

<div class="mini-modal" id="modalGrower" aria-hidden="true">
  <div class="mini-box">
    <div class="mini-head">
      <span>Add Grower</span>
      <button class="mini-close" type="button" onclick="closeMiniModal('modalGrower')">&times;</button>
    </div>
    <div class="mini-body">
      <label class="form-label">Grower Name</label>
      <input type="text" class="form-control mb-3" id="newGrowerInput" placeholder="e.g. ABC Farms">
      <div class="d-flex gap-2 justify-content-end">
        <button class="btn btn-success" type="button" onclick="ajaxAddPreset('add_grower')">Save</button>
        <button class="btn btn-secondary" type="button" onclick="closeMiniModal('modalGrower')">Cancel</button>
      </div>
    </div>
  </div>
</div>

<div class="mini-modal" id="modalType" aria-hidden="true">
  <div class="mini-box">
    <div class="mini-head">
      <span>Add Bin Type</span>
      <button class="mini-close" type="button" onclick="closeMiniModal('modalType')">&times;</button>
    </div>
    <div class="mini-body">
      <label class="form-label">Type Name</label>
      <input type="text" class="form-control mb-3" id="newTypeInput" placeholder="e.g. 48L / Macro / ...">
      <div class="d-flex gap-2 justify-content-end">
        <button class="btn btn-success" type="button" onclick="ajaxAddPreset('add_type')">Save</button>
        <button class="btn btn-secondary" type="button" onclick="closeMiniModal('modalType')">Cancel</button>
      </div>
    </div>
  </div>
</div>

<?php include('../includes/footer.php'); ?>

<script>
/* ================= DASHBOARD TOGGLE (JS puro) ================= */
document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('.js-toggle').forEach(btn => {
        const section = btn.dataset.target;
        const key = 'collapse_' + section;
        const body = document.querySelector('.card-body[data-section="' + section + '"]');

        if (!body) return;

        // restore state
        if (localStorage.getItem(key) === 'closed') {
            body.style.display = 'none';
            btn.textContent = '+';
        }

        const logSel=document.getElementById('logLimitSelect');
        if(logSel){ logSel.value = localStorage.getItem('log_limit') || '50'; logSel.addEventListener('change', applyLogLimit); applyLogLimit(); }

        btn.addEventListener('click', () => {
            const isOpen = body.style.display !== 'none';
            body.style.display = isOpen ? 'none' : '';
            btn.textContent = isOpen ? '+' : '−';
            localStorage.setItem(key, isOpen ? 'closed' : 'open');
        });
    });
});

// dblclick on card-header to toggle (balance/log)
function toggleSectionByKey(section){
    const btn = document.querySelector('.js-toggle[data-target="'+section+'"]');
    if (btn) btn.click();
}
document.addEventListener('dblclick', (e) => {
    const header = e.target.closest('.card-header');
    if (!header) return;
    const btn = header.querySelector('.js-toggle');
    if (!btn) return;
    toggleSectionByKey(btn.dataset.target);
});

// Log limit handling (client-side)
function applyLogLimit(){
    const sel=document.getElementById('logLimitSelect');
    const tbody = sel ? sel.closest('.card')?.querySelector('tbody') : null;
    if (!sel || !tbody) return;
    localStorage.setItem('log_limit', sel.value);
    const limit = sel.value === 'all' ? Infinity : parseInt(sel.value,10);
    let i=0;
    tbody.querySelectorAll('tr').forEach(tr=>{
        tr.style.display = (i < limit) ? '' : 'none';
        i++;
    });
}

// Mini modal helpers
function openMiniModal(id){
    const m=document.getElementById(id); if(!m) return;
    m.classList.add('show');
    setTimeout(()=>{
        if(id==='modalGrower') document.getElementById('newGrowerInput')?.focus();
        if(id==='modalType') document.getElementById('newTypeInput')?.focus();
    }, 50);
}
function closeMiniModal(id){ const m=document.getElementById(id); if(m) m.classList.remove('show'); }
document.addEventListener('click', (e)=>{ if(e.target.classList?.contains('mini-modal')) e.target.classList.remove('show'); });
document.addEventListener('keydown', (e)=>{ if(e.key==='Escape') document.querySelectorAll('.mini-modal.show').forEach(m=>m.classList.remove('show')); });

function sortSelectOptions(selectEl){
    if(!selectEl) return;
    const opts=Array.from(selectEl.options);
    const first=opts.shift();
    opts.sort((a,b)=> (a.text||'').localeCompare(b.text||'', undefined, {sensitivity:'base'}));
    selectEl.innerHTML='';
    if(first) selectEl.appendChild(first);
    opts.forEach(o=>selectEl.appendChild(o));
}
function ensureOption(selectEl, value, selectIt){
    if(!selectEl) return;
    const exists=Array.from(selectEl.options).some(o=>o.value===value);
    if(!exists){
        const opt=document.createElement('option');
        opt.value=value; opt.textContent=value;
        selectEl.appendChild(opt);
    }
    sortSelectOptions(selectEl);
    if(selectIt) selectEl.value=value;
}

async function ajaxAddPreset(kind){
    const val = (kind==='add_grower'
        ? (document.getElementById('newGrowerInput')?.value||'')
        : (document.getElementById('newTypeInput')?.value||'')
    ).trim();

    if(!val){ alert('Please enter a name'); return; }

    const fd=new FormData();
    fd.append('ajax_action', kind);
    fd.append('name', val);

    try{
        const r=await fetch('empty_bins_receiving.php',{method:'POST', body:fd});
        const data=await r.json();
        if(!data.ok){ alert(data.error||'Error'); return; }

        if(kind==='add_grower'){
            ensureOption(document.getElementById('growerSelect'), data.name, true);
            ensureOption(document.getElementById('filterGrower'), data.name, false);
            document.getElementById('newGrowerInput').value='';
            closeMiniModal('modalGrower');
        } else {
            ensureOption(document.getElementById('typeSelect'), data.name, true);
            ensureOption(document.getElementById('filterType'), data.name, false);
            document.getElementById('newTypeInput').value='';
            closeMiniModal('modalType');
        }
        if (typeof applyFilters === 'function') applyFilters();
    } catch(e){
        alert('Network/Server error');
    }
}

</script>

<script>
function editRow(id) {
    const row = document.querySelector(`tr[data-id='${id}']`);
    if (!row) return;

    const growerCell = row.querySelector('.cell-grower');
    const typeCell   = row.querySelector('.cell-type');
    const dateCell   = row.querySelector('.cell-date');
    const qtyCell    = row.querySelector('.cell-qty');
    const actionsCell= row.querySelector('.cell-actions');

    const grower = growerCell.innerText.trim();
    const type   = typeCell.innerText.trim();
    const date   = dateCell.innerText.trim();
    const qty    = qtyCell.innerText.trim();

    const esc = s => s.replace(/"/g, '&quot;');

    growerCell.innerHTML =
        `<input class="form-control form-control-sm inline-edit-input" id="edit_grower_${id}" value="${esc(grower)}">`;

    typeCell.innerHTML =
        `<input class="form-control form-control-sm inline-edit-input" id="edit_type_${id}" value="${esc(type)}">`;

    dateCell.innerHTML =
        `<input type="date" class="form-control form-control-sm" id="edit_date_${id}" value="${esc(date)}">`;

    qtyCell.innerHTML =
        `<input type="number" class="form-control form-control-sm inline-edit-input" id="edit_qty_${id}" min="1" value="${esc(qty)}">`;

    actionsCell.innerHTML = `
        <button class="btn btn-sm btn-success" onclick="saveRow(${id})">Save</button>
        <button class="btn btn-sm btn-secondary" onclick="location.reload()">Cancel</button>
    `;
}

function saveRow(id) {
    const growerEl = document.getElementById(`edit_grower_${id}`);
    const typeEl   = document.getElementById(`edit_type_${id}`);
    const dateEl   = document.getElementById(`edit_date_${id}`);
    const qtyEl    = document.getElementById(`edit_qty_${id}`);

    if (!growerEl || !typeEl || !dateEl || !qtyEl) {
        alert('Missing fields');
        return;
    }

    const fd = new FormData();
    fd.append('inline_edit', '1');
    fd.append('id', id);
    fd.append('grower',  growerEl.value);
    fd.append('type',    typeEl.value);
    fd.append('date',    dateEl.value);
    fd.append('quantity', qtyEl.value);

    // robust: invia al file corrente, qualunque sia il nome
    fetch('<?= basename(__FILE__) ?>', {
        method: 'POST',
        body: fd
    })
    .then(r => r.text())
    .then(txt => {
        if (txt.trim() === 'OK') {
            location.reload();
        } else {
            alert('Error saving row');
        }
    })
    .catch(() => alert('Error saving row'));
}

/*-----------------------------------------
  FILTERS
-----------------------------------------*/
function applyFilters() {
    const searchInput = document.getElementById('filterSearch');
    const growerSel   = document.getElementById('filterGrower');
    const typeSel     = document.getElementById('filterType');
    const dateInput   = document.getElementById('filterDate');

    const search = (searchInput?.value || '').toLowerCase();
    const fg     = (growerSel?.value   || '').toLowerCase();
    const ft     = (typeSel?.value     || '').toLowerCase();
    const fd     = (dateInput?.value   || '');

    document.querySelectorAll('#emptyBinsTable tr').forEach(row => {
        const grower = (row.dataset.grower || '').toLowerCase();
        const type   = (row.dataset.type   || '').toLowerCase();
        const date   = (row.dataset.date   || '');

        let match = true;

        if (search && !(grower.includes(search) || type.includes(search))) match = false;
        if (fg && grower !== fg) match = false;
        if (ft && type !== ft) match = false;
        if (fd && date !== fd) match = false;

        row.style.display = match ? '' : 'none';
    });
}

window.addEventListener('DOMContentLoaded', () => {
    const searchInput = document.getElementById('filterSearch');
    const growerSel   = document.getElementById('filterGrower');
    const typeSel     = document.getElementById('filterType');
    const dateInput   = document.getElementById('filterDate');

    if (searchInput) searchInput.addEventListener('input',  applyFilters);
    if (growerSel)   growerSel.addEventListener('change',   applyFilters);
    if (typeSel)     typeSel.addEventListener('change',     applyFilters);
    if (dateInput)   dateInput.addEventListener('change',   applyFilters);
});
</script>
