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

// DEBUG (puoi disabilitarlo in produzione)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

$msg = null;
$err = null;

/* ----------------------------------------
   PRESET TABLES (ID-BASED)
---------------------------------------- */
$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 growers_list (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) UNIQUE NOT NULL
)");

$mysqli->query("
CREATE TABLE IF NOT EXISTS varieties_list (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) UNIQUE NOT NULL
)");

$growers   = $mysqli->query("SELECT id, name FROM growers_list ORDER BY name ASC")->fetch_all(MYSQLI_ASSOC);
$varieties = $mysqli->query("SELECT id, name FROM varieties_list ORDER BY name ASC")->fetch_all(MYSQLI_ASSOC);
$types     = $mysqli->query("SELECT id, name FROM bin_types_list ORDER BY name ASC")->fetch_all(MYSQLI_ASSOC);

/* ----------------------------------------
   ORDINAMENTO (AVAILABLE / DUMPED)
---------------------------------------- */
$allowedSort = ['grower','variety','lot','date','total_bins','group_id'];

// Available
$sort_av = $_GET['sort_av'] ?? 'date';
$dir_av  = strtolower($_GET['dir_av'] ?? 'desc');
if (!in_array($sort_av, $allowedSort)) $sort_av = 'date';
$dir_av = $dir_av === 'asc' ? 'asc' : 'desc';

// Dumped
$sort_dump = $_GET['sort_dump'] ?? 'date';
$dir_dump  = strtolower($_GET['dir_dump'] ?? 'desc');
if (!in_array($sort_dump, $allowedSort)) $sort_dump = 'date';
$dir_dump = $dir_dump === 'asc' ? 'asc' : 'desc';

$orderClauseAv   = "ORDER BY {$sort_av} {$dir_av}";
$orderClauseDump = "ORDER BY {$sort_dump} {$dir_dump}";

/* ----------------------------------------
   AZIONI POST (incl. AJAX inline)
---------------------------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    /* ---------- INLINE EDIT GROUP (AJAX) ---------- */
    if ($action === 'edit_group_inline') {
        $gid     = intval($_POST['group_id'] ?? 0);
        $grower  = $mysqli->real_escape_string(trim($_POST['grower'] ?? ''));
        $variety = $mysqli->real_escape_string(trim($_POST['variety'] ?? ''));
        $type    = $mysqli->real_escape_string(trim($_POST['type'] ?? ''));
        $lot     = $mysqli->real_escape_string(trim($_POST['lot'] ?? ''));
        $date    = $mysqli->real_escape_string(trim($_POST['date'] ?? ''));

        $g = $mysqli->query("SELECT id FROM growers_list   WHERE name='$grower'")->fetch_assoc();
        $v = $mysqli->query("SELECT id FROM varieties_list WHERE name='$variety'")->fetch_assoc();
        $t = $mysqli->query("SELECT id FROM bin_types_list WHERE name='$type'")->fetch_assoc();

        $grower_id  = $g['id'] ?? 0;
        $variety_id = $v['id'] ?? 0;
        $type_id    = $t['id'] ?? 0;

        if ($gid > 0 && $grower_id > 0 && $variety_id > 0 && $date !== '') {
            $mysqli->query("
                UPDATE bins_ingresso
                SET 
                    grower_id  = $grower_id,
                    variety_id = $variety_id,
                    type_id    = $type_id,
                    lot        = '$lot',
                    date       = '$date'
                WHERE group_id = $gid
            ");
            echo "OK";
        } else {
            echo "ERROR";
        }
        exit;
    }

    /* ---------- INLINE EDIT BIN (AJAX) ---------- */
    if ($action === 'edit_bin_inline') {
        $id      = intval($_POST['id'] ?? 0);
        $grower  = $mysqli->real_escape_string(trim($_POST['grower'] ?? ''));
        $variety = $mysqli->real_escape_string(trim($_POST['variety'] ?? ''));
        $type    = $mysqli->real_escape_string(trim($_POST['type'] ?? ''));
        $lot     = $mysqli->real_escape_string(trim($_POST['lot'] ?? ''));
        $date    = $mysqli->real_escape_string(trim($_POST['date'] ?? ''));

        $g = $mysqli->query("SELECT id FROM growers_list   WHERE name='$grower'")->fetch_assoc();
        $v = $mysqli->query("SELECT id FROM varieties_list WHERE name='$variety'")->fetch_assoc();
        $t = $mysqli->query("SELECT id FROM bin_types_list WHERE name='$type'")->fetch_assoc();

        $grower_id  = $g['id'] ?? 0;
        $variety_id = $v['id'] ?? 0;
        $type_id    = $t['id'] ?? 0;

        if ($id > 0 && $grower_id > 0 && $variety_id > 0 && $date !== '') {
            $mysqli->query("
                UPDATE bins_ingresso
                SET
                    grower_id  = $grower_id,
                    variety_id = $variety_id,
                    type_id    = $type_id,
                    lot        = '$lot',
                    date       = '$date'
                WHERE id = $id
            ");
            echo "OK";
        } else {
            echo "ERROR";
        }
        exit;
    }

    /* ---------- ADD PRESETS ---------- */
    if ($action === 'add_grower' && $role === 'admin') {
        $n = trim($_POST['new_grower'] ?? '');
        if ($n !== '') {
            $n = $mysqli->real_escape_string($n);
            $mysqli->query("INSERT IGNORE INTO growers_list(name) VALUES('$n')");
            $msg = "Grower added.";
        }
    }

    if ($action === 'add_variety' && $role === 'admin') {
        $n = trim($_POST['new_variety'] ?? '');
        if ($n !== '') {
            $n = $mysqli->real_escape_string($n);
            $mysqli->query("INSERT IGNORE INTO varieties_list(name) VALUES('$n')");
            $msg = "Variety added.";
        }
    }

    if ($action === 'add_type' && $role === 'admin') {
        $n = trim($_POST['new_type'] ?? '');
        if ($n !== '') {
            $n = $mysqli->real_escape_string($n);
            $mysqli->query("INSERT IGNORE INTO bin_types_list(name) VALUES('$n')");
            $msg = "Type added.";
        }
    }

    /* ---------- DUMP / UNDO / DELETE ---------- */

    // DUMP GROUP: AVAILABLE -> DUMPED
    if ($action === 'dump_group') {
        $gid = intval($_POST['group_id'] ?? 0);
        if ($gid > 0) {
            $mysqli->query("
                UPDATE bins_ingresso
                SET status = 'DUMPED'
                WHERE group_id = {$gid}
                  AND status = 'AVAILABLE'
            ");
        }
    }

    // DUMP SINGLE
    if ($action === 'dump_single') {
        $id = intval($_POST['id'] ?? 0);
        if ($id > 0) {
            $mysqli->query("
                UPDATE bins_ingresso
                SET status = 'DUMPED'
                WHERE id = {$id}
                  AND status = 'AVAILABLE'
            ");
        }
    }

    // UNDO GROUP: DUMPED -> AVAILABLE
    if ($action === 'undo_group') {
        $gid = intval($_POST['group_id'] ?? 0);
        if ($gid > 0) {
            $mysqli->query("
                UPDATE bins_ingresso
                SET status = 'AVAILABLE'
                WHERE group_id = {$gid}
                  AND status = 'DUMPED'
            ");
        }
    }

    // UNDO SINGLE
    if ($action === 'undo_single') {
        $id = intval($_POST['id'] ?? 0);
        if ($id > 0) {
            $mysqli->query("
                UPDATE bins_ingresso
                SET status = 'AVAILABLE'
                WHERE id = {$id}
                  AND status = 'DUMPED'
            ");
        }
    }

    // Delete group
    if ($action === 'delete_group' && $role === 'admin') {
        $gid = intval($_POST['group_id'] ?? 0);
        if ($gid > 0) {
            $mysqli->query("DELETE FROM bins_ingresso WHERE group_id = {$gid}");
            $msg = "Group {$gid} deleted.";
        }
    }

    // Delete single bin
    if ($action === 'delete_single' && $role === 'admin') {
        $id = intval($_POST['id'] ?? 0);
        if ($id > 0) {
            $mysqli->query("DELETE FROM bins_ingresso WHERE id = {$id}");
            $msg = "Bin #{$id} deleted.";
        }
    }
}

/* ----------------------------------------
   TOTALI GROWER / VARIETY (AVAILABLE + DUMPED)
---------------------------------------- */
$totals_grower = [];
$res_tg = $mysqli->query("
    SELECT 
        COALESCE(gp.name, 'N/A') AS grower,
        COUNT(*) AS total_bins
    FROM bins_ingresso bi
    LEFT JOIN growers_list gp ON bi.grower_id = gp.id
    WHERE bi.status IN ('AVAILABLE','DUMPED')
    GROUP BY bi.grower_id
    ORDER BY grower ASC
");
if ($res_tg) $totals_grower = $res_tg->fetch_all(MYSQLI_ASSOC);

$totals_variety = [];
$res_tv = $mysqli->query("
    SELECT 
        COALESCE(vl.name, 'N/A') AS variety,
        COUNT(*) AS total_bins
    FROM bins_ingresso bi
    LEFT JOIN varieties_list vl ON bi.variety_id = vl.id
    WHERE bi.status IN ('AVAILABLE','DUMPED')
    GROUP BY bi.variety_id
    ORDER BY variety ASC
");
if ($res_tv) $totals_variety = $res_tv->fetch_all(MYSQLI_ASSOC);

/* ----------------------------------------
   GRUPPI AVAILABLE (status = AVAILABLE)
---------------------------------------- */
$sql_av = "
    SELECT 
        MIN(gp.name) AS grower,
        MIN(vl.name) AS variety,
        MIN(tl.name) AS type,
        MIN(bi.lot)  AS lot,
        DATE_FORMAT(MIN(bi.date),'%Y-%m-%d') AS date,
        COUNT(*) AS total_bins,
        bi.group_id
    FROM bins_ingresso bi
    LEFT JOIN growers_list   gp ON bi.grower_id  = gp.id
    LEFT JOIN varieties_list vl ON bi.variety_id = vl.id
    LEFT JOIN bin_types_list tl ON bi.type_id    = tl.id
    WHERE bi.status = 'AVAILABLE'
    GROUP BY bi.group_id
    {$orderClauseAv}
";
$res_groups_av = $mysqli->query($sql_av);
$groups_available = $res_groups_av ? $res_groups_av->fetch_all(MYSQLI_ASSOC) : [];

/* ----------------------------------------
   GRUPPI DUMPED (status = DUMPED)
---------------------------------------- */
$sql_dump = "
    SELECT 
        MIN(gp.name) AS grower,
        MIN(vl.name) AS variety,
        MIN(tl.name) AS type,
        MIN(bi.lot)  AS lot,
        DATE_FORMAT(MIN(bi.date),'%Y-%m-%d') AS date,
        COUNT(*) AS total_bins,
        bi.group_id
    FROM bins_ingresso bi
    LEFT JOIN growers_list   gp ON bi.grower_id  = gp.id
    LEFT JOIN varieties_list vl ON bi.variety_id = vl.id
    LEFT JOIN bin_types_list tl ON bi.type_id    = tl.id
    WHERE bi.status = 'DUMPED'
    GROUP BY bi.group_id
    {$orderClauseDump}
";
$res_groups_dump = $mysqli->query($sql_dump);
$groups_dumped = $res_groups_dump ? $res_groups_dump->fetch_all(MYSQLI_ASSOC) : [];

/* ----------------------------------------
   LISTE PER FILTRI (Grower / Variety / Lot)
---------------------------------------- */
$dump_filter_growers = $mysqli->query("
    SELECT DISTINCT gp.name AS name
    FROM bins_ingresso bi
    LEFT JOIN growers_list gp ON bi.grower_id = gp.id
    WHERE bi.status IN ('AVAILABLE','DUMPED')
      AND gp.name IS NOT NULL AND gp.name <> ''
    ORDER BY gp.name ASC
")->fetch_all(MYSQLI_ASSOC);

$dump_filter_varieties = $mysqli->query("
    SELECT DISTINCT vl.name AS name
    FROM bins_ingresso bi
    LEFT JOIN varieties_list vl ON bi.variety_id = vl.id
    WHERE bi.status IN ('AVAILABLE','DUMPED')
      AND vl.name IS NOT NULL AND vl.name <> ''
    ORDER BY vl.name ASC
")->fetch_all(MYSQLI_ASSOC);

$dump_filter_lots = $mysqli->query("
    SELECT DISTINCT bi.lot AS name
    FROM bins_ingresso bi
    WHERE bi.status IN ('AVAILABLE','DUMPED')
      AND bi.lot IS NOT NULL AND bi.lot <> ''
    ORDER BY bi.lot ASC
")->fetch_all(MYSQLI_ASSOC);

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

/* Helper per link di sort (se lo userai da UI in futuro) */
function sort_link($label, $col, $currentSort, $currentDir, $prefix) {
    $dir = 'asc';
    $arrow = '';
    if ($currentSort === $col) {
        if ($currentDir === 'asc') {
            $dir = 'desc';
            $arrow = ' ▲';
        } else {
            $dir = 'asc';
            $arrow = ' ▼';
        }
    }
    $qs = $_GET;
    $qs["sort_{$prefix}"] = $col;
    $qs["dir_{$prefix}"]  = $dir;
    $href = htmlspecialchars($_SERVER['PHP_SELF'] . '?' . http_build_query($qs));
    return '<a href="'.$href.'">'.$label.$arrow.'</a>';
}
?>

<h3 class="mb-3">Dumping Bins</h3>

<?php if ($msg): ?><div class="alert alert-success"><?= htmlspecialchars($msg) ?></div><?php endif; ?>
<?php if ($err): ?><div class="alert alert-danger"><?= htmlspecialchars($err) ?></div><?php endif; ?>

<!-- Totali matematici -->
<div class="row mb-4">
  <div class="col-md-6">
    <div class="card h-100">
      <div class="card-header fw-semibold">Totals by Grower (AVAILABLE + DUMPED)</div>
      <div class="card-body">
        <?php if (!empty($totals_grower)): ?>
          <table class="table table-sm mb-0">
            <thead>
              <tr>
                <th>Grower</th>
                <th class="text-end">Bins</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($totals_grower as $tg): ?>
              <tr>
                <td><?= htmlspecialchars($tg['grower']) ?></td>
                <td class="text-end"><?= (int)$tg['total_bins'] ?></td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        <?php else: ?>
          <span class="text-muted">No data.</span>
        <?php endif; ?>
      </div>
    </div>
  </div>

  <div class="col-md-6 mt-3 mt-md-0">
    <div class="card h-100">
      <div class="card-header fw-semibold">Totals by Variety (AVAILABLE + DUMPED)</div>
      <div class="card-body">
        <?php if (!empty($totals_variety)): ?>
          <table class="table table-sm mb-0">
            <thead>
              <tr>
                <th>Variety</th>
                <th class="text-end">Bins</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($totals_variety as $tv): ?>
              <tr>
                <td><?= htmlspecialchars($tv['variety']) ?></td>
                <td class="text-end"><?= (int)$tv['total_bins'] ?></td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        <?php else: ?>
          <span class="text-muted">No data.</span>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>

<form method="post">

  <!-- =========================
       FULL BINS AVAILABLE
  ========================== -->
  <div class="card shadow-sm mb-4">
    <div class="card-header d-flex justify-content-between align-items-center">
      <span class="fw-semibold">Full Bins Available</span>
      <div class="btn-group btn-group-sm">
        <button type="button" class="btn btn-outline-secondary" onclick="expandAllAvailable()">Expand All</button>
        <button type="button" class="btn btn-outline-secondary" onclick="collapseAllAvailable()">Collapse All</button>
      </div>
    </div>

    <div class="card-body">

      <!-- FILTRI -->
      <div class="row g-3 align-items-end mb-3">
        <div class="col-md-3">
          <label class="form-label mb-1">Search</label>
          <input id="dumpSearch" class="form-control" placeholder="🔍 Search (grower, variety, lot)">
        </div>

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

        <div class="col-md-3">
          <label class="form-label mb-1">Variety</label>
          <select id="dumpFilterVariety" class="form-select">
            <option value="">All Varieties</option>
            <?php foreach ($dump_filter_varieties as $v): ?>
              <option value="<?= htmlspecialchars($v['name']) ?>"><?= htmlspecialchars($v['name']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="col-md-3">
          <label class="form-label mb-1">Lot</label>
          <select id="dumpFilterLot" class="form-select">
            <option value="">All Lots</option>
            <?php foreach ($dump_filter_lots as $l): ?>
              <option value="<?= htmlspecialchars($l['name']) ?>"><?= htmlspecialchars($l['name']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>
      <!-- /FILTRI -->

      <div class="table-responsive">
        <table class="table table-hover mb-0 align-middle">
          <thead class="table-light">
            <tr>
              <th style="width:40px;"></th>
              <th>Grower</th>
              <th>Variety</th>
              <th>Type</th>
              <th>Lot</th>
              <th>Date</th>
              <th>Qty</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
          <?php if (!empty($groups_available)): ?>
            <?php foreach ($groups_available as $g): ?>
              <?php
                $gid    = (int)$g['group_id'];
                $grower = $g['grower'];
                $var    = $g['variety'];
                $type   = $g['type'];
                $lot    = $g['lot'];
                $date   = $g['date'];
                $qty    = (int)$g['total_bins'];

                $res_bins = $mysqli->query("
                    SELECT 
                        bi.*,
                        gp.name AS grower,
                        vl.name AS variety,
                        tl.name AS type
                    FROM bins_ingresso bi
                    LEFT JOIN growers_list   gp ON bi.grower_id  = gp.id
                    LEFT JOIN varieties_list vl ON bi.variety_id = vl.id
                    LEFT JOIN bin_types_list tl ON bi.type_id    = tl.id
                    WHERE bi.group_id = {$gid}
                      AND bi.status   = 'AVAILABLE'
                    ORDER BY bi.id ASC
                ");
                $bins = $res_bins ? $res_bins->fetch_all(MYSQLI_ASSOC) : [];
              ?>
              <!-- RIGA GRUPPO AVAILABLE -->
              <tr class="group-row-available"
                  onclick="toggleAvailable(<?= $gid ?>)"
                  data-grower="<?= htmlspecialchars($grower) ?>"
                  data-variety="<?= htmlspecialchars($var) ?>"
                  data-lot="<?= htmlspecialchars($lot) ?>">
                <td>
                  <span class="arrow" id="arrowA_<?= $gid ?>">➤</span>
                </td>
                <td id="gA_grower_<?= $gid ?>"><?= htmlspecialchars($grower) ?></td>
                <td id="gA_variety_<?= $gid ?>"><?= htmlspecialchars($var) ?></td>
                <td id="gA_type_<?= $gid ?>"><?= htmlspecialchars($type) ?></td>
                <td id="gA_lot_<?= $gid ?>"><?= htmlspecialchars($lot) ?></td>
                <td id="gA_date_<?= $gid ?>"><?= htmlspecialchars($date) ?></td>
                <td>
                  <span class="badge badge-size
                    <?php
                      if ($qty <= 2) echo ' bg-danger';
                      else if ($qty <= 5) echo ' bg-warning';
                      else echo ' bg-success';
                    ?>">
                    <?= $qty ?>
                  </span>
                </td>
                <td id="gA_actions_<?= $gid ?>">
                  <!-- INLINE EDIT GROUP -->
                  <button type="button"
                          class="btn btn-sm btn-warning"
                          onclick="event.stopPropagation(); editGroupInline('A', <?= $gid ?>);">
                    Edit
                  </button>

                  <!-- DUMP GROUP -->
                  <form method="post"
                        class="d-inline"
                        onclick="event.stopPropagation();"
                        onsubmit="return confirm('Dump all AVAILABLE bins in this group?');">
                    <input type="hidden" name="action" value="dump_group">
                    <input type="hidden" name="group_id" value="<?= $gid ?>">
                    <button class="btn btn-sm btn-primary">Dump Group</button>
                  </form>

                  <?php if ($role === 'admin'): ?>
                  <!-- DELETE GROUP -->
                  <form method="post"
                        class="d-inline"
                        onclick="event.stopPropagation();"
                        onsubmit="return confirm('Delete this group and all its bins?');">
                    <input type="hidden" name="action" value="delete_group">
                    <input type="hidden" name="group_id" value="<?= $gid ?>">
                    <button class="btn btn-sm btn-danger">Delete</button>
                  </form>
                  <?php endif; ?>
                </td>
              </tr>

              <!-- DETTAGLIO GRUPPO AVAILABLE -->
              <tr id="groupA_<?= $gid ?>" class="group-details-available" style="display:none;">
                <td colspan="8">
                  <?php if (!empty($bins)): ?>
                  <table class="table table-sm table-bordered group-details-table ms-4 mb-0">
                    <thead class="table-secondary">
                      <tr>
                        <th>ID</th>
                        <th>Grower</th>
                        <th>Variety</th>
                        <th>Type</th>
                        <th>Lot</th>
                        <th>Date</th>
                        <th>Barcode</th>
                        <th>Label</th>
                        <th>Actions</th>
                        <th>Delete</th>
                      </tr>
                    </thead>
                    <tbody>
                      <?php foreach ($bins as $b): ?>
                        <?php
                          $bid     = (int)$b['id'];
                          $bdate   = $b['date'];
                          $bgrower = $b['grower'];
                          $bvar    = $b['variety'];
                          $btype   = $b['type'];
                          $blot    = $b['lot'];
                          $barcode = "FBIN-" . str_pad($bid, 6, "0", STR_PAD_LEFT);
                        ?>
                        <tr id="bin_row_<?= $bid ?>">
                          <td><?= $bid ?></td>
                          <td id="b_grower_<?= $bid ?>"><?= htmlspecialchars($bgrower) ?></td>
                          <td id="b_variety_<?= $bid ?>"><?= htmlspecialchars($bvar) ?></td>
                          <td id="b_type_<?= $bid ?>"><?= htmlspecialchars($btype) ?></td>
                          <td id="b_lot_<?= $bid ?>"><?= htmlspecialchars($blot) ?></td>
                          <td id="b_date_<?= $bid ?>"><?= htmlspecialchars($bdate) ?></td>
                          <td><?= htmlspecialchars($barcode) ?></td>
                          <td>
                            <a href="print_bin_label.php?id=<?= $bid ?>"
                               target="_blank"
                               class="btn btn-sm btn-outline-secondary">
                              Print
                            </a>
                          </td>
                          <td id="b_actions_<?= $bid ?>">
                            <!-- INLINE EDIT BIN -->
                            <button type="button"
                                    class="btn btn-sm btn-warning"
                                    onclick="event.stopPropagation(); editBinInline(<?= $bid ?>);">
                              Edit
                            </button>

                            <!-- DUMP SINGLE -->
                            <form method="post"
                                  class="d-inline"
                                  onclick="event.stopPropagation();"
                                  onsubmit="return confirm('Dump this bin?');">
                              <input type="hidden" name="action" value="dump_single">
                              <input type="hidden" name="id" value="<?= $bid ?>">
                              <button class="btn btn-sm btn-primary">Dump</button>
                            </form>
                          </td>
                          <td>
                            <?php if ($role === 'admin'): ?>
                            <form method="post"
                                  onsubmit="return confirm('Delete this bin?');"
                                  onclick="event.stopPropagation();">
                              <input type="hidden" name="action" value="delete_single">
                              <input type="hidden" name="id" value="<?= $bid ?>">
                              <button class="btn btn-sm btn-danger">Del</button>
                            </form>
                            <?php endif; ?>
                          </td>
                        </tr>
                      <?php endforeach; ?>
                    </tbody>
                  </table>
                  <?php else: ?>
                    <div class="text-muted ms-4">No AVAILABLE bins in this group.</div>
                  <?php endif; ?>
                </td>
              </tr>
            <?php endforeach; ?>
          <?php else: ?>
            <tr>
              <td colspan="8" class="text-center text-muted py-4">
                No AVAILABLE groups found.
              </td>
            </tr>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <!-- =========================
       DUMPED BINS (status = DUMPED)
  ========================== -->
  <div class="card shadow-sm mb-4">
    <div class="card-header d-flex justify-content-between align-items-center">
      <span class="fw-semibold">Dumped Bins (DUMPED) - Grouped</span>
      <div class="btn-group btn-group-sm">
        <button type="button" class="btn btn-outline-secondary" onclick="expandAllDumped()">Expand All</button>
        <button type="button" class="btn btn-outline-secondary" onclick="collapseAllDumped()">Collapse All</button>
      </div>
    </div>

    <div class="card-body">
      <div class="table-responsive">
        <table class="table table-hover mb-0 align-middle">
          <thead class="table-light">
            <tr>
              <th style="width:40px;"></th>
              <th>Grower</th>
              <th>Variety</th>
              <th>Type</th>
              <th>Lot</th>
              <th>Date</th>
              <th>Qty</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
          <?php if (!empty($groups_dumped)): ?>
            <?php foreach ($groups_dumped as $g): ?>
              <?php
                $gid    = (int)$g['group_id'];
                $grower = $g['grower'];
                $var    = $g['variety'];
                $type   = $g['type'];
                $lot    = $g['lot'];
                $date   = $g['date'];
                $qty    = (int)$g['total_bins'];

                $res_bins = $mysqli->query("
                    SELECT 
                        bi.*,
                        gp.name AS grower,
                        vl.name AS variety,
                        tl.name AS type
                    FROM bins_ingresso bi
                    LEFT JOIN growers_list   gp ON bi.grower_id  = gp.id
                    LEFT JOIN varieties_list vl ON bi.variety_id = vl.id
                    LEFT JOIN bin_types_list tl ON bi.type_id    = tl.id
                    WHERE bi.group_id = {$gid}
                      AND bi.status   = 'DUMPED'
                    ORDER BY bi.id ASC
                ");
                $bins = $res_bins ? $res_bins->fetch_all(MYSQLI_ASSOC) : [];
              ?>
              <!-- RIGA GRUPPO DUMPED -->
              <tr class="group-row-dumped"
                  onclick="toggleDumped(<?= $gid ?>)"
                  data-grower="<?= htmlspecialchars($grower) ?>"
                  data-variety="<?= htmlspecialchars($var) ?>"
                  data-lot="<?= htmlspecialchars($lot) ?>">
                <td>
                  <span class="arrow" id="arrowD_<?= $gid ?>">➤</span>
                </td>
                <td id="gD_grower_<?= $gid ?>"><?= htmlspecialchars($grower) ?></td>
                <td id="gD_variety_<?= $gid ?>"><?= htmlspecialchars($var) ?></td>
                <td id="gD_type_<?= $gid ?>"><?= htmlspecialchars($type) ?></td>
                <td id="gD_lot_<?= $gid ?>"><?= htmlspecialchars($lot) ?></td>
                <td id="gD_date_<?= $gid ?>"><?= htmlspecialchars($date) ?></td>
                <td>
                  <span class="badge badge-size
                    <?php
                      if ($qty <= 2) echo ' bg-danger';
                      else if ($qty <= 5) echo ' bg-warning';
                      else echo ' bg-success';
                    ?>">
                    <?= $qty ?>
                  </span>
                </td>
                <td id="gD_actions_<?= $gid ?>">
                  <!-- INLINE EDIT GROUP -->
                  <button type="button"
                          class="btn btn-sm btn-warning"
                          onclick="event.stopPropagation(); editGroupInline('D', <?= $gid ?>);">
                    Edit
                  </button>

                  <!-- UNDO GROUP -->
                  <form method="post"
                        class="d-inline"
                        onclick="event.stopPropagation();"
                        onsubmit="return confirm('Undo dump for all DUMPED bins in this group?');">
                    <input type="hidden" name="action" value="undo_group">
                    <input type="hidden" name="group_id" value="<?= $gid ?>">
                    <button class="btn btn-sm btn-warning">Undo Group</button>
                  </form>

                  <?php if ($role === 'admin'): ?>
                  <!-- DELETE GROUP -->
                  <form method="post"
                        class="d-inline"
                        onclick="event.stopPropagation();"
                        onsubmit="return confirm('Delete this group and all its bins?');">
                    <input type="hidden" name="action" value="delete_group">
                    <input type="hidden" name="group_id" value="<?= $gid ?>">
                    <button class="btn btn-sm btn-danger">Delete</button>
                  </form>
                  <?php endif; ?>
                </td>
              </tr>

              <!-- DETTAGLIO GRUPPO DUMPED -->
              <tr id="groupD_<?= $gid ?>" class="group-details-dumped" style="display:none;">
                <td colspan="8">
                  <?php if (!empty($bins)): ?>
                  <table class="table table-sm table-bordered group-details-table ms-4 mb-0">
                    <thead class="table-secondary">
                      <tr>
                        <th>ID</th>
                        <th>Grower</th>
                        <th>Variety</th>
                        <th>Type</th>
                        <th>Lot</th>
                        <th>Date</th>
                        <th>Barcode</th>
                        <th>Label</th>
                        <th>Actions</th>
                        <th>Delete</th>
                      </tr>
                    </thead>
                    <tbody>
                      <?php foreach ($bins as $b): ?>
                        <?php
                          $bid     = (int)$b['id'];
                          $bdate   = $b['date'];
                          $bgrower = $b['grower'];
                          $bvar    = $b['variety'];
                          $btype   = $b['type'];
                          $blot    = $b['lot'];
                          $barcode = "FBIN-" . str_pad($bid, 6, "0", STR_PAD_LEFT);
                        ?>
                        <tr id="bin_row_<?= $bid ?>">
                          <td><?= $bid ?></td>
                          <td id="b_grower_<?= $bid ?>"><?= htmlspecialchars($bgrower) ?></td>
                          <td id="b_variety_<?= $bid ?>"><?= htmlspecialchars($bvar) ?></td>
                          <td id="b_type_<?= $bid ?>"><?= htmlspecialchars($btype) ?></td>
                          <td id="b_lot_<?= $bid ?>"><?= htmlspecialchars($blot) ?></td>
                          <td id="b_date_<?= $bid ?>"><?= htmlspecialchars($bdate) ?></td>
                          <td><?= htmlspecialchars($barcode) ?></td>
                          <td>
                            <a href="print_bin_label.php?id=<?= $bid ?>"
                               target="_blank"
                               class="btn btn-sm btn-outline-secondary">
                              Print
                            </a>
                          </td>
                          <td id="b_actions_<?= $bid ?>">
                            <!-- INLINE EDIT BIN -->
                            <button type="button"
                                    class="btn btn-sm btn-warning"
                                    onclick="event.stopPropagation(); editBinInline(<?= $bid ?>);">
                              Edit
                            </button>

                            <!-- UNDO SINGLE -->
                            <form method="post"
                                  class="d-inline"
                                  onclick="event.stopPropagation();"
                                  onsubmit="return confirm('Undo dump for this bin?');">
                              <input type="hidden" name="action" value="undo_single">
                              <input type="hidden" name="id" value="<?= $bid ?>">
                              <button class="btn btn-sm btn-warning">Undo</button>
                            </form>
                          </td>
                          <td>
                            <?php if ($role === 'admin'): ?>
                            <form method="post"
                                  onsubmit="return confirm('Delete this bin?');"
                                  onclick="event.stopPropagation();">
                              <input type="hidden" name="action" value="delete_single">
                              <input type="hidden" name="id" value="<?= $bid ?>">
                              <button class="btn btn-sm btn-danger">Del</button>
                            </form>
                            <?php endif; ?>
                          </td>
                        </tr>
                      <?php endforeach; ?>
                    </tbody>
                  </table>
                  <?php else: ?>
                    <div class="text-muted ms-4">No DUMPED bins in this group.</div>
                  <?php endif; ?>
                </td>
              </tr>
            <?php endforeach; ?>
          <?php else: ?>
            <tr>
              <td colspan="8" class="text-center text-muted py-4">
                No DUMPED groups found.
              </td>
            </tr>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

</form>

<style>
.arrow {
    transition: transform 0.25s ease;
    cursor: pointer;
    font-size: 18px;
}
.badge-size {
    font-size: 0.75rem;
    padding: 6px 10px;
}
.group-details-table td {
    padding: 6px 10px !important;
}
</style>

<script>
/* ----------------------------------------
   TOGGLE GROUP (Available / Dumped)
---------------------------------------- */
function toggleAvailable(id) {
  const row   = document.getElementById('groupA_' + id);
  const icon  = document.getElementById('arrowA_' + id);
  if (!row) return;
  const visible = row.style.display === 'table-row';
  row.style.display = visible ? 'none' : 'table-row';
  if (icon) icon.textContent = visible ? '➤' : '▼';
}

function toggleDumped(id) {
  const row   = document.getElementById('groupD_' + id);
  const icon  = document.getElementById('arrowD_' + id);
  if (!row) return;
  const visible = row.style.display === 'table-row';
  row.style.display = visible ? 'none' : 'table-row';
  if (icon) icon.textContent = visible ? '➤' : '▼';
}

function expandAllAvailable() {
  document.querySelectorAll('.group-details-available').forEach(r => {
    r.style.display = 'table-row';
  });
  document.querySelectorAll('span[id^="arrowA_"]').forEach(a => a.textContent = '▼');
}

function collapseAllAvailable() {
  document.querySelectorAll('.group-details-available').forEach(r => {
    r.style.display = 'none';
  });
  document.querySelectorAll('span[id^="arrowA_"]').forEach(a => a.textContent = '➤');
}

function expandAllDumped() {
  document.querySelectorAll('.group-details-dumped').forEach(r => {
    r.style.display = 'table-row';
  });
  document.querySelectorAll('span[id^="arrowD_"]').forEach(a => a.textContent = '▼');
}

function collapseAllDumped() {
  document.querySelectorAll('.group-details-dumped').forEach(r => {
    r.style.display = 'none';
  });
  document.querySelectorAll('span[id^="arrowD_"]').forEach(a => a.textContent = '➤');
}

/* ----------------------------------------
   INLINE EDIT GROUP
   prefix: 'A' (available) oppure 'D' (dumped)
---------------------------------------- */
function editGroupInline(prefix, gid) {
    const pre = (prefix === 'A') ? 'gA_' : 'gD_';

    let g = document.getElementById(pre + 'grower_' + gid).innerText.trim();
    let v = document.getElementById(pre + 'variety_' + gid).innerText.trim();
    let t = document.getElementById(pre + 'type_' + gid).innerText.trim();
    let l = document.getElementById(pre + 'lot_' + gid).innerText.trim();
    let d = document.getElementById(pre + 'date_' + gid).innerText.trim();

    document.getElementById(pre + 'grower_' + gid).innerHTML =
        `<input class="form-control form-control-sm" id="edit_grower_${gid}" value="${g}">`;

    document.getElementById(pre + 'variety_' + gid).innerHTML =
        `<input class="form-control form-control-sm" id="edit_variety_${gid}" value="${v}">`;

    document.getElementById(pre + 'type_' + gid).innerHTML =
        `<input class="form-control form-control-sm" id="edit_type_${gid}" value="${t}">`;

    document.getElementById(pre + 'lot_' + gid).innerHTML =
        `<input class="form-control form-control-sm" id="edit_lot_${gid}" value="${l}">`;

    document.getElementById(pre + 'date_' + gid).innerHTML =
        `<input type="date" class="form-control form-control-sm" id="edit_date_${gid}" value="${d}">`;

    document.getElementById(pre + 'actions_' + gid).innerHTML = `
        <button class="btn btn-sm btn-success" onclick="saveGroupInline(${gid}); event.stopPropagation();">Save</button>
        <button class="btn btn-sm btn-secondary" onclick="location.reload(); event.stopPropagation();">Cancel</button>
    `;
}

function saveGroupInline(gid) {
    let fd = new FormData();
    fd.append("action","edit_group_inline");
    fd.append("group_id",gid);
    fd.append("grower", document.getElementById('edit_grower_'+gid).value);
    fd.append("variety",document.getElementById('edit_variety_'+gid).value);
    fd.append("type",   document.getElementById('edit_type_'+gid).value);
    fd.append("lot",    document.getElementById('edit_lot_'+gid).value);
    fd.append("date",   document.getElementById('edit_date_'+gid).value);

    fetch("dumping_bins.php", {
        method:"POST",
        body: fd
    }).then(()=>location.reload());
}

/* ----------------------------------------
   INLINE EDIT BIN
---------------------------------------- */
function editBinInline(bid) {
    let g = document.getElementById('b_grower_'+bid).innerText.trim();
    let v = document.getElementById('b_variety_'+bid).innerText.trim();
    let t = document.getElementById('b_type_'+bid).innerText.trim();
    let l = document.getElementById('b_lot_'+bid).innerText.trim();
    let d = document.getElementById('b_date_'+bid).innerText.trim();

    document.getElementById('b_grower_'+bid).innerHTML =
        `<input class="form-control form-control-sm" id="editb_grower_${bid}" value="${g}">`;

    document.getElementById('b_variety_'+bid).innerHTML =
        `<input class="form-control form-control-sm" id="editb_variety_${bid}" value="${v}">`;

    document.getElementById('b_type_'+bid).innerHTML =
        `<input class="form-control form-control-sm" id="editb_type_${bid}" value="${t}">`;

    document.getElementById('b_lot_'+bid).innerHTML =
        `<input class="form-control form-control-sm" id="editb_lot_${bid}" value="${l}">`;

    document.getElementById('b_date_'+bid).innerHTML =
        `<input type="date" class="form-control form-control-sm" id="editb_date_${bid}" value="${d}">`;

    document.getElementById('b_actions_'+bid).innerHTML = `
        <button class="btn btn-sm btn-success" onclick="saveBinInline(${bid}); event.stopPropagation();">Save</button>
        <button class="btn btn-sm btn-secondary" onclick="location.reload(); event.stopPropagation();">Cancel</button>
    `;
}

function saveBinInline(bid) {
    let fd = new FormData();
    fd.append("action","edit_bin_inline");
    fd.append("id",bid);
    fd.append("grower",  document.getElementById('editb_grower_'+bid).value);
    fd.append("variety", document.getElementById('editb_variety_'+bid).value);
    fd.append("type",    document.getElementById('editb_type_'+bid).value);
    fd.append("lot",     document.getElementById('editb_lot_'+bid).value);
    fd.append("date",    document.getElementById('editb_date_'+bid).value);

    fetch("dumping_bins.php", {
        method:"POST",
        body: fd
    }).then(()=>location.reload());
}

/* ----------------------------------------
   FILTRI (Search + Grower/Variety/Lot)
---------------------------------------- */
function applyDumpingFilters() {
  const searchInput   = document.getElementById('dumpSearch');
  const growerSelect  = document.getElementById('dumpFilterGrower');
  const varietySelect = document.getElementById('dumpFilterVariety');
  const lotSelect     = document.getElementById('dumpFilterLot');

  const search    = searchInput  ? searchInput.value.toLowerCase().trim() : '';
  const growerVal = growerSelect ? growerSelect.value.toLowerCase()       : '';
  const varietyVal= varietySelect? varietySelect.value.toLowerCase()      : '';
  const lotVal    = lotSelect    ? lotSelect.value.toLowerCase()          : '';

  const rows = document.querySelectorAll('.group-row-available, .group-row-dumped');

  rows.forEach(row => {
    const g = (row.dataset.grower  || '').toLowerCase();
    const v = (row.dataset.variety || '').toLowerCase();
    const l = (row.dataset.lot     || '').toLowerCase();

    let match = true;

    if (search) {
      const textBlob = g + ' ' + v + ' ' + l;
      if (!textBlob.includes(search)) match = false;
    }
    if (growerVal && g !== growerVal)  match = false;
    if (varietyVal && v !== varietyVal)match = false;
    if (lotVal && l !== lotVal)        match = false;

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

    // Nascondi / mostra anche la riga dettaglio associata
    const isAvailable = row.classList.contains('group-row-available');
    const prefixRow   = isAvailable ? 'groupA_' : 'groupD_';
    const arrowPrefix = isAvailable ? 'arrowA_' : 'arrowD_';
    const arrowSpan   = row.querySelector('.arrow');
    if (arrowSpan) {
      const arrowId = arrowSpan.id || '';
      const coreId  = arrowId.replace(arrowPrefix, '');
      const detailRow = document.getElementById(prefixRow + coreId);
      if (detailRow) {
        detailRow.style.display = match ? detailRow.style.display : 'none';
      }
    }
  });
}

function initDumpingFilters() {
  const searchInput   = document.getElementById('dumpSearch');
  const growerSelect  = document.getElementById('dumpFilterGrower');
  const varietySelect = document.getElementById('dumpFilterVariety');
  const lotSelect     = document.getElementById('dumpFilterLot');

  if (searchInput)   searchInput.addEventListener('input',  applyDumpingFilters);
  if (growerSelect)  growerSelect.addEventListener('change', applyDumpingFilters);
  if (varietySelect) varietySelect.addEventListener('change', applyDumpingFilters);
  if (lotSelect)     lotSelect.addEventListener('change',    applyDumpingFilters);

  applyDumpingFilters();
}

if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initDumpingFilters);
} else {
  initDumpingFilters();
}
</script>

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