<?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';

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

/*-----------------------------------------
  TABLES
-----------------------------------------*/
$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
");

$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
");

/*-----------------------------------------
  AJAX: +NEW PRESETS (NO REFRESH)
-----------------------------------------*/
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;
    }

    $action = 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 ($action === 'add_grower') {
        $mysqli->query("INSERT IGNORE INTO growers_list(name) VALUES('$nameEsc')");
        echo json_encode(['ok' => true, 'name' => $name]);
        exit;
    }

    if ($action === '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;
}

/*-----------------------------------------
  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;
        }

        $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'];

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

        $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;
    }

    /*------------------------------
      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())
            ");

            $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) {
            $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 TOTALS
-----------------------------------------*/
$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 (LOAD ALL)
-----------------------------------------*/
$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);

/*-----------------------------------------
  LIST
-----------------------------------------*/
$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; }

.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; }

.dash-body{ }
</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 -->
    <div class="row mb-4">
        <!-- Totals -->
        <div class="col-md-6">
            <div class="card h-100 shadow-sm dashboard-card" data-cardkey="eb_totals">
                <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 dash-toggle">−</button>
                </div>
                <div class="card-body dash-body">
                    <?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 dashboard-card" data-cardkey="eb_log" id="logCard">
                <div class="card-header fw-semibold d-flex flex-wrap gap-2 justify-content-between align-items-center">
                    <span>Empty Bins Movements (Log)</span>

                    <div class="d-flex gap-2 align-items-center flex-wrap">
                        <select id="logGrowerFilter" class="form-select form-select-sm" style="width:140px">
                            <option value="">All Growers</option>
                            <?php foreach ($growers as $g): ?>
                                <option value="<?= htmlspecialchars($g['name']) ?>"><?= htmlspecialchars($g['name']) ?></option>
                            <?php endforeach; ?>
                        </select>

                        <select id="logTypeFilter" class="form-select form-select-sm" style="width:130px">
                            <option value="">All Types</option>
                            <?php foreach ($types as $t): ?>
                                <option value="<?= htmlspecialchars($t['name']) ?>"><?= htmlspecialchars($t['name']) ?></option>
                            <?php endforeach; ?>
                        </select>

                        <select id="logDatePreset" class="form-select form-select-sm" style="width:130px">
                            <option value="all">All dates</option>
                            <option value="today">Today</option>
                            <option value="7">Last 7 days</option>
                            <option value="30">Last 30 days</option>
                            <option value="custom">Custom</option>
                        </select>

                        <input type="date" id="logDateFrom" class="form-control form-control-sm d-none" style="width:140px">
                        <input type="date" id="logDateTo"   class="form-control form-control-sm d-none" style="width:140px">

                        <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 id="exportLogCsv" class="btn btn-outline-secondary btn-sm" type="button">
                            Export CSV
                        </button>

                        <button type="button" class="btn btn-sm btn-outline-secondary dash-toggle">−</button>
                    </div>
                </div>

                <div class="card-body dash-body">
                    <?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 id="logTbody">
                                    <?php foreach ($log_rows as $i => $lr): ?>
                                        <tr data-log-index="<?= $i ?>"
                                            data-grower="<?= htmlspecialchars($lr['grower']) ?>"
                                            data-type="<?= htmlspecialchars($lr['type']) ?>"
                                            data-date="<?= htmlspecialchars(substr($lr['created_at'], 0, 10)) ?>">
                                            <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 style="width:200px;">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>

<!-- MINI MODAL: ADD GROWER -->
<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>

<!-- MINI MODAL: ADD TYPE -->
<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>
/* -------------------------
   Mini-modal controls
------------------------- */
function openMiniModal(id){
  const m = document.getElementById(id);
  if(!m) return;
  m.classList.add('show');

  // autofocus
  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) return;
  m.classList.remove('show');
}
document.addEventListener('click', (e) => {
  const modal = e.target.classList?.contains('mini-modal') ? e.target : null;
  if (modal) modal.classList.remove('show');
});
document.addEventListener('keydown', (e) => {
  if (e.key === 'Escape') {
    document.querySelectorAll('.mini-modal.show').forEach(m => m.classList.remove('show'));
  }
});

/* -------------------------
   Utility: sort select options
------------------------- */
function sortSelectOptions(selectEl) {
  if (!selectEl) return;
  const opts = Array.from(selectEl.options);
  const first = opts.shift(); // keep first option (Select... / All ...)
  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));
}

/* -------------------------
   Utility: ensure option exists + select it
------------------------- */
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;
}

/* -------------------------
   AJAX +New Grower/Type
------------------------- */
async function ajaxAddPreset(action){
  const isGrower = action === 'add_grower';
  const inputId = isGrower ? 'newGrowerInput' : 'newTypeInput';
  const modalId = isGrower ? 'modalGrower' : 'modalType';
  const val = (document.getElementById(inputId)?.value || '').trim();

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

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

  try {
    const resp = await fetch('empty_bins_receiving.php', { method:'POST', body: fd });
    const data = await resp.json();

    if (!data.ok) {
      alert(data.error || 'Error');
      return;
    }

    if (isGrower) {
      // Add form select + filter selects + log filter
      ensureOption(document.getElementById('growerSelect'), data.name, true);
      ensureOption(document.getElementById('filterGrower'), data.name, false);
      ensureOption(document.getElementById('logGrowerFilter'), data.name, false);
      document.getElementById(inputId).value = '';
      closeMiniModal(modalId);
      applyFilters();
      applyLogFilters();
      return;
    }

    // Type
    ensureOption(document.getElementById('typeSelect'), data.name, true);
    ensureOption(document.getElementById('filterType'), data.name, false);
    ensureOption(document.getElementById('logTypeFilter'), data.name, false);
    document.getElementById(inputId).value = '';
    closeMiniModal(modalId);
    applyFilters();
    applyLogFilters();
  } catch (e) {
    alert('Network/Server error');
  }
}

/* -------------------------
   Dashboard collapse + localStorage
------------------------- */
function initDashCollapse(){
  document.querySelectorAll('.dashboard-card').forEach(card => {
    const key = card.getAttribute('data-cardkey') || '';
    const body = card.querySelector('.dash-body');
    const toggles = card.querySelectorAll('.dash-toggle');
    const header = card.querySelector('.card-header');

    if(!key || !body || !header || toggles.length === 0) return;

    const storageKey = 'dash_' + key;

    function applyState(isOpen){
      body.style.display = isOpen ? '' : 'none';
      toggles.forEach(b => b.textContent = isOpen ? '−' : '+');
    }

    const saved = localStorage.getItem(storageKey);
    applyState(saved !== 'closed');

    function toggle(){
      const isOpen = body.style.display !== 'none';
      const nextOpen = !isOpen;
      applyState(nextOpen);
      localStorage.setItem(storageKey, nextOpen ? 'open' : 'closed');
    }

    toggles.forEach(btn => btn.addEventListener('click', (e)=>{ e.preventDefault(); toggle(); }));
    header.addEventListener('dblclick', (e)=>{ e.preventDefault(); toggle(); });
  });
}

/* -------------------------
   Empty Bins List: Edit inline
------------------------- */
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);

    fetch('empty_bins_receiving.php', { 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'));
}

/* -------------------------
   Empty Bins List: 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';
    });
}

/* -------------------------
   LOG FILTERS + CSV EXPORT
------------------------- */
function toggleCustomDates() {
  const dateSel = document.getElementById('logDatePreset');
  const from = document.getElementById('logDateFrom');
  const to   = document.getElementById('logDateTo');
  const isCustom = (dateSel?.value === 'custom');
  from?.classList.toggle('d-none', !isCustom);
  to?.classList.toggle('d-none', !isCustom);
}

function inDateRange(rowDate) {
  const dateSel = document.getElementById('logDatePreset');
  const from = document.getElementById('logDateFrom');
  const to   = document.getElementById('logDateTo');
  const mode = dateSel?.value || 'all';

  if (!rowDate) return true;
  if (mode === 'all') return true;

  const today = new Date();
  const rd = new Date(rowDate + 'T00:00:00');

  if (mode === 'today') return rd.toDateString() === today.toDateString();

  if (mode === '7' || mode === '30') {
    const days = parseInt(mode, 10);
    const diff = (today - rd) / (1000 * 60 * 60 * 24);
    return diff <= days;
  }

  if (mode === 'custom') {
    if (from?.value && rowDate < from.value) return false;
    if (to?.value   && rowDate > to.value)   return false;
    return true;
  }

  return true;
}

function applyLogFilters() {
  const limitSel  = document.getElementById('logLimitSelect');
  const growerSel = document.getElementById('logGrowerFilter');
  const typeSel   = document.getElementById('logTypeFilter');
  const dateSel   = document.getElementById('logDatePreset');
  const from      = document.getElementById('logDateFrom');
  const to        = document.getElementById('logDateTo');
  const tbody     = document.getElementById('logTbody');

  if (!limitSel || !tbody) return;

  toggleCustomDates();

  // persist
  localStorage.setItem('log_limit', limitSel.value);
  localStorage.setItem('log_grower', growerSel?.value || '');
  localStorage.setItem('log_type', typeSel?.value || '');
  localStorage.setItem('log_date', dateSel?.value || 'all');
  localStorage.setItem('log_from', from?.value || '');
  localStorage.setItem('log_to', to?.value || '');

  const limit = limitSel.value;
  const gv = (growerSel?.value || '').toLowerCase();
  const tv = (typeSel?.value || '').toLowerCase();

  let shown = 0;

  Array.from(tbody.querySelectorAll('tr')).forEach(row => {
    const rg = (row.dataset.grower || '').toLowerCase();
    const rt = (row.dataset.type || '').toLowerCase();
    const rd = row.dataset.date || '';

    let match = true;
    if (gv && rg !== gv) match = false;
    if (tv && rt !== tv) match = false;
    if (!inDateRange(rd)) match = false;

    if (!match) {
      row.style.display = 'none';
      return;
    }

    if (limit !== 'all' && shown >= parseInt(limit, 10)) {
      row.style.display = 'none';
      return;
    }

    row.style.display = '';
    shown++;
  });
}

function initLogControls() {
  const limitSel  = document.getElementById('logLimitSelect');
  const growerSel = document.getElementById('logGrowerFilter');
  const typeSel   = document.getElementById('logTypeFilter');
  const dateSel   = document.getElementById('logDatePreset');
  const from      = document.getElementById('logDateFrom');
  const to        = document.getElementById('logDateTo');

  if (limitSel)  limitSel.value  = localStorage.getItem('log_limit')  || '20';
  if (growerSel) growerSel.value = localStorage.getItem('log_grower') || '';
  if (typeSel)   typeSel.value   = localStorage.getItem('log_type')   || '';
  if (dateSel)   dateSel.value   = localStorage.getItem('log_date')   || 'all';
  if (from)      from.value      = localStorage.getItem('log_from')   || '';
  if (to)        to.value        = localStorage.getItem('log_to')     || '';

  [limitSel, growerSel, typeSel, dateSel, from, to].forEach(el => {
    if (!el) return;
    el.addEventListener('change', applyLogFilters);
  });

  applyLogFilters();
}

function exportLogCsv() {
  const tbody = document.getElementById('logTbody');
  if (!tbody) return;

  const headers = ['Date/Time','Grower','Type','Delta Qty','Reason'];
  const lines = [];
  lines.push(headers.join(','));

  const rows = Array.from(tbody.querySelectorAll('tr')).filter(tr => tr.style.display !== 'none');
  if (rows.length === 0) { alert('No rows to export'); return; }

  rows.forEach(tr => {
    const tds = Array.from(tr.children).map(td => `"${(td.innerText || '').replace(/"/g,'""')}"`);
    lines.push(tds.join(','));
  });

  const csv = lines.join('\n');
  const blob = new Blob([csv], { type:'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);

  const a = document.createElement('a');
  const date = new Date().toISOString().slice(0,10);
  a.href = url;
  a.download = `empty_bins_log_${date}.csv`;
  a.click();
  URL.revokeObjectURL(url);
}

window.addEventListener('DOMContentLoaded', () => {
  initDashCollapse();
  initLogControls();

  const exportBtn = document.getElementById('exportLogCsv');
  if (exportBtn) exportBtn.addEventListener('click', exportLogCsv);

  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>
