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

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

/*-----------------------------------------
  EMPTY BINS LOG TABLE (for + / - movements)
-----------------------------------------*/
$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   = $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);

$msg = null;
$err = null;

/**
 * Consume empty bins when FULL bins are received.
 * Match by grower NAME + type NAME (no variety).
 * Decreases empty_bins.quantity, FIFO by date/id.
 * Writes a negative movement into empty_bins_log.
 */
function consume_empty_bins_out(mysqli $mysqli, string $growerName, string $typeName, int $qty, int $groupId): void
{
    if ($qty <= 0) return;

    $growerEsc = $mysqli->real_escape_string($growerName);
    $typeEsc   = $mysqli->real_escape_string($typeName);
    $remaining = $qty;

    // take older empty bins first
    $res = $mysqli->query("
        SELECT id, quantity
        FROM empty_bins
        WHERE grower = '$growerEsc'
          AND type   = '$typeEsc'
          AND quantity > 0
        ORDER BY date ASC, id ASC
    ");

    if (!$res) return;

    while ($row = $res->fetch_assoc()) {
        if ($remaining <= 0) break;

        $rowId   = (int)$row['id'];
        $rowQty  = (int)$row['quantity'];
        if ($rowQty <= 0) continue;

        $take = min($remaining, $rowQty);
        $remaining -= $take;
        $newQty = $rowQty - $take;

        if ($newQty > 0) {
            $mysqli->query("UPDATE empty_bins SET quantity = $newQty WHERE id = $rowId");
        } else {
            // remove row when quantity becomes 0
            $mysqli->query("DELETE FROM empty_bins WHERE id = $rowId");
        }

        // log negative movement
        $reason = $mysqli->real_escape_string("Full bins received group #$groupId");
        $mysqli->query("
            INSERT INTO empty_bins_log(grower, type, qty_change, reason)
            VALUES('$growerEsc', '$typeEsc', ".(-$take).", '$reason')
        ");
    }

    // if $remaining > 0 we simply leave it (more full bins than empties given out)
}

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

    $action = $_POST['action'] ?? '';

    // Add grower preset
    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.";
        }
    }

    // Add variety preset
    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.";
        }
    }

    // Add type preset
    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.";
        }
    }

    // Inline edit of group (AJAX) - NAME -> ID
    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'] ?? ''));

        // name → ID
        $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 SINGLE BIN (AJAX) - NAME -> ID
    if ($action === 'edit_single_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'] ?? ''));

        // name → ID
        $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 group (ID-based) + CONSUME EMPTY BINS OUT
    if ($action === 'add') {
        $grower  = trim($_POST['grower'] ?? '');
        $date    = $_POST['date'] ?? date('Y-m-d');
        $variety = trim($_POST['variety'] ?? '');
        $type    = trim($_POST['type'] ?? '');
        $lot     = trim($_POST['lot'] ?? '');
        $qty     = max(1, intval($_POST['quantity'] ?? 0));

        if ($grower && $variety) {
            // grower_id
            $growerEsc = $mysqli->real_escape_string($grower);
            $g = $mysqli->query("SELECT id FROM growers_list WHERE name='$growerEsc'")->fetch_assoc();
            $grower_id = $g['id'] ?? 0;

            // variety_id
            $varietyEsc = $mysqli->real_escape_string($variety);
            $v = $mysqli->query("SELECT id FROM varieties_list WHERE name='$varietyEsc'")->fetch_assoc();
            $variety_id = $v['id'] ?? 0;

            // type_id
            $typeEsc = $mysqli->real_escape_string($type);
            $t = $mysqli->query("SELECT id FROM bin_types_list WHERE name='$typeEsc'")->fetch_assoc();
            $type_id = $t['id'] ?? 0;

            $lotEsc  = $mysqli->real_escape_string($lot);
            $dateEsc = $mysqli->real_escape_string($date);

            $gid = time();

            for ($i = 0; $i < $qty; $i++) {
                $mysqli->query("
                    INSERT INTO bins_ingresso(
                        grower_id, variety_id, type_id,
                        lot, date, status, group_id
                    ) VALUES (
                        $grower_id, $variety_id, $type_id,
                        '$lotEsc', '$dateEsc',
                        'AVAILABLE', $gid
                    )
                ");
            }

            // AFTER inserting full bins: consume empty bins OUT
            consume_empty_bins_out($mysqli, $grower, $type, $qty, $gid);

            $msg = "Group created with $qty bins.";
        } else {
            $err = "Grower and Variety are required.";
        }
    }

    // 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 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 deleted.";
        }
    }
}

/*-----------------------------------------
  VIEW DATA (GROUPS) - ONLY_FULL_GROUP_BY SAFE
-----------------------------------------*/
$groups = $mysqli->query("
SELECT 
    MIN(gp.name) AS grower,
    MIN(vl.name) AS variety,
    MIN(tl.name) AS type,
    MIN(bi.date) AS date,
    MIN(bi.lot) AS lot,
    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
ORDER BY date DESC, grower ASC
")->fetch_all(MYSQLI_ASSOC);

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

<style>
.arrow {
    transition: transform 0.25s ease;
    cursor: pointer;
    font-size: 18px;
}
.arrow.open {
    transform: rotate(90deg);
}
.group-row {
    background-color: #f9fafb;
}
.group-row:hover {
    background-color: #eef2ff;
}
.badge-size {
    font-size: 0.75rem;
    padding: 6px 10px;
}
.group-details-table td {
    padding: 6px 10px !important;
}
</style>

<div class="container-fluid">

    <h3 class="mb-3">Full Bin Receiving</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; ?>

    <!-- ADD FULL BINS -->
    <div class="card mb-4 shadow-sm">
        <div class="card-header fw-semibold">Add Full Bins</div>
        <div class="card-body">
            <form method="post" class="row g-3">
                <input type="hidden" name="action" value="add">

                <!-- Grower -->
                <div class="col-md-3">
                    <label class="form-label fw-semibold">Grower</label>
                    <div class="input-group">
                        <select name="grower" 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"
                                data-bs-toggle="modal"
                                data-bs-target="#addGrowerModal">
                            + New
                        </button>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Variety -->
                <div class="col-md-3">
                    <label class="form-label fw-semibold">Variety</label>
                    <div class="input-group">
                        <select name="variety" class="form-select" required>
                            <option value="">Select...</option>
                            <?php foreach ($varieties as $v): ?>
                                <option value="<?= htmlspecialchars($v['name']) ?>">
                                    <?= htmlspecialchars($v['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <?php if ($role === 'admin'): ?>
                        <button type="button"
                                class="btn btn-outline-primary btn-sm"
                                data-bs-toggle="modal"
                                data-bs-target="#addVarietyModal">
                            + New
                        </button>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Type -->
                <div class="col-md-2">
                    <label class="form-label fw-semibold">Type</label>
                    <div class="input-group">
                        <select name="type" 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"
                                data-bs-toggle="modal"
                                data-bs-target="#addTypeModal">
                            + New
                        </button>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Lot -->
                <div class="col-md-2">
                    <label class="form-label fw-semibold">Lot</label>
                    <input type="text" name="lot" class="form-control">
                </div>

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

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

                <div class="col-md-12">
                    <button class="btn btn-success">Add</button>
                </div>
            </form>
        </div>
    </div>

    <!-- FULL BINS INVENTORY -->
    <div class="card shadow-sm">
        <div class="card-header d-flex justify-content-between align-items-center">
            <span class="fw-semibold">Full Bins Inventory</span>
            <div class="btn-group btn-group-sm">
                <button type="button" class="btn btn-outline-secondary" onclick="expandAll()">Expand All</button>
                <button type="button" class="btn btn-outline-secondary" onclick="collapseAll()">Collapse All</button>
            </div>
        </div>
        <div class="card-body">

            <div class="row mb-3">
                <div class="col-md-3">
                    <input id="searchInput" class="form-control" placeholder="🔍 Search (grower, variety, lot)">
                </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="filterVariety" class="form-select">
                        <option value="">All Varieties</option>
                        <?php foreach ($varieties as $v): ?>
                            <option value="<?= htmlspecialchars($v['name']) ?>"><?= htmlspecialchars($v['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>

            <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
                    foreach ($groups as $g):
                        $gid = (int)$g['group_id'];

                        $details = $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
                            ORDER BY bi.id ASC
                        ")->fetch_all(MYSQLI_ASSOC);
                    ?>
                        <!-- ROW GROUP -->
                        <tr class="group-row"
                            data-id="<?= $gid ?>"
                            data-grower="<?= htmlspecialchars($g['grower']) ?>"
                            data-variety="<?= htmlspecialchars($g['variety']) ?>"
                            data-type="<?= htmlspecialchars($g['type']) ?>"
                            data-lot="<?= htmlspecialchars($g['lot']) ?>"
                            onclick="toggleGroup(<?= $gid ?>)">
                            <td>
                                <span class="arrow" id="arrow_<?= $gid ?>">➤</span>
                            </td>

                            <td id="g_grower_<?= $gid ?>"><?= htmlspecialchars($g['grower']) ?></td>
                            <td id="g_variety_<?= $gid ?>"><?= htmlspecialchars($g['variety']) ?></td>
                            <td id="g_type_<?= $gid ?>"><?= htmlspecialchars($g['type']) ?></td>
                            <td id="g_lot_<?= $gid ?>"><?= htmlspecialchars($g['lot']) ?></td>
                            <td id="g_date_<?= $gid ?>"><?= htmlspecialchars($g['date']) ?></td>
                            <td>
                                <span class="badge badge-size
                                    <?php
                                        $q = (int)$g['total_bins'];
                                        if ($q <= 2) echo ' bg-danger';
                                        else if ($q <= 5) echo ' bg-warning';
                                        else echo ' bg-success';
                                    ?>
                                ">
                                    <?= (int)$g['total_bins'] ?>
                                </span>
                            </td>

                            <td id="g_actions_<?= $gid ?>">
                                <a href="print_bin_label_group.php?group_id=<?= $gid ?>"
                                   target="_blank"
                                   class="btn btn-sm btn-outline-primary">
                                    Print All
                                </a>

                                <button type="button"
                                        class="btn btn-sm btn-warning"
                                        onclick="event.stopPropagation(); editGroupInline(<?= $gid ?>);">
                                    Edit
                                </button>

                                <?php if ($role === 'admin'): ?>
                                <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>

                        <!-- GROUP DETAILS -->
                        <tr class="collapse" id="group_<?= $gid ?>">
                            <td colspan="8">
                                <table class="table table-sm table-bordered group-details-table ms-4 mb-0">
                                    <thead class="table-secondary">
                                        <tr>
                                            <th>ID</th>
                                            <th>Barcode</th>
                                            <th>Grower</th>
                                            <th>Variety</th>
                                            <th>Type</th>
                                            <th>Lot</th>
                                            <th>Date</th>
                                            <th>Label</th>
                                            <th>Actions</th>
                                            <th>Delete</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    <?php foreach ($details as $b):
                                        $barcode = "FBIN-" . str_pad($b['id'], 6, '0', STR_PAD_LEFT);
                                    ?>
                                    <tr id="bin_row_<?= $b['id'] ?>">
                                        <td><?= $b['id'] ?></td>
                                        <td><?= htmlspecialchars($barcode) ?></td>
                                        <td id="b_grower_<?= $b['id'] ?>"><?= htmlspecialchars($b['grower']) ?></td>
                                        <td id="b_variety_<?= $b['id'] ?>"><?= htmlspecialchars($b['variety']) ?></td>
                                        <td id="b_type_<?= $b['id'] ?>"><?= htmlspecialchars($b['type']) ?></td>
                                        <td id="b_lot_<?= $b['id'] ?>"><?= htmlspecialchars($b['lot']) ?></td>
                                        <td id="b_date_<?= $b['id'] ?>"><?= htmlspecialchars($b['date']) ?></td>

                                        <td>
                                            <a href="print_bin_label.php?id=<?= $b['id'] ?>"
                                               target="_blank"
                                               class="btn btn-sm btn-outline-secondary">
                                                Print
                                            </a>
                                        </td>

                                        <td id="b_actions_<?= $b['id'] ?>">
                                            <button type="button"
                                                    class="btn btn-sm btn-warning"
                                                    onclick="event.stopPropagation(); editBinInline(<?= $b['id'] ?>);">
                                                Edit
                                            </button>
                                        </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="<?= $b['id'] ?>">
                                                <button class="btn btn-sm btn-danger">Del</button>
                                            </form>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </td>
                        </tr>

                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

        </div>
    </div>

</div>

<!-- MODALS -->

<!-- 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="action" value="add_grower">
      <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" name="new_grower" class="form-control" required>
      </div>
      <div class="modal-footer">
        <button class="btn btn-success">
          Save
        </button>
      </div>
    </form>
  </div>
</div>

<!-- Add Variety -->
<div class="modal fade" id="addVarietyModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <form class="modal-content" method="post">
      <input type="hidden" name="action" value="add_variety">
      <div class="modal-header">
        <h5 class="modal-title">Add Variety</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <label class="form-label">Variety name</label>
        <input type="text" name="new_variety" class="form-control" required>
      </div>
      <div class="modal-footer">
        <button class="btn btn-success">
          Save
        </button>
      </div>
    </form>
  </div>
</div>

<!-- Add Type -->
<div class="modal fade" id="addTypeModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <form class="modal-content" method="post">
      <input type="hidden" name="action" value="add_type">
      <div class="modal-header">
        <h5 class="modal-title">Add Bin Type</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <label class="form-label">Type name</label>
        <input type="text" name="new_type" class="form-control" required>
      </div>
      <div class="modal-footer">
        <button class="btn btn-success">
          Save
        </button>
      </div>
    </form>
  </div>
</div>

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

<!-- TEMPLATE SELECTS PER INLINE EDIT BIN -->
<script type="text/template" id="tmplGrowerSelect">
<select class="form-select form-select-sm">
    <option value="">Select...</option>
    <?php foreach ($growers as $g): ?>
        <option value="<?= htmlspecialchars($g['name'], ENT_QUOTES) ?>">
            <?= htmlspecialchars($g['name']) ?>
        </option>
    <?php endforeach; ?>
</select>
</script>

<script type="text/template" id="tmplVarietySelect">
<select class="form-select form-select-sm">
    <option value="">Select...</option>
    <?php foreach ($varieties as $v): ?>
        <option value="<?= htmlspecialchars($v['name'], ENT_QUOTES) ?>">
            <?= htmlspecialchars($v['name']) ?>
        </option>
    <?php endforeach; ?>
</select>
</script>

<script type="text/template" id="tmplTypeSelect">
<select class="form-select form-select-sm">
    <option value="">Select...</option>
    <?php foreach ($types as $t): ?>
        <option value="<?= htmlspecialchars($t['name'], ENT_QUOTES) ?>">
            <?= htmlspecialchars($t['name']) ?>
        </option>
    <?php endforeach; ?>
</select>
</script>

<script>
function editGroupInline(gid) {
    let g = document.getElementById('g_grower_'+gid).innerText.trim();
    let v = document.getElementById('g_variety_'+gid).innerText.trim();
    let t = document.getElementById('g_type_'+gid).innerText.trim();
    let l = document.getElementById('g_lot_'+gid).innerText.trim();
    let d = document.getElementById('g_date_'+gid).innerText.trim();

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

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

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

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

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

    document.getElementById('g_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("bins_ingresso.php", {
        method:"POST",
        body: fd
    }).then(r => r.text())
     .then(txt => {
        if (txt.trim() === 'OK') {
            location.reload();
        } else {
            alert('Error saving group edit');
        }
     });
}

// Helper per creare select dai template
function createSelectFromTemplate(tmplId, selectedValue, newId) {
    const tmpl = document.getElementById(tmplId);
    if (!tmpl) return null;
    const wrapper = document.createElement('div');
    wrapper.innerHTML = tmpl.innerHTML.trim();
    const select = wrapper.firstElementChild;
    if (!select) return null;
    if (newId) select.id = newId;
    select.value = selectedValue || '';
    return select;
}

// INLINE EDIT SINGOLO BIN
function editBinInline(id) {
    const growerCell  = document.getElementById('b_grower_'+id);
    const varietyCell = document.getElementById('b_variety_'+id);
    const typeCell    = document.getElementById('b_type_'+id);
    const lotCell     = document.getElementById('b_lot_'+id);
    const dateCell    = document.getElementById('b_date_'+id);
    const actionsCell = document.getElementById('b_actions_'+id);

    if (!growerCell || !varietyCell || !typeCell || !lotCell || !dateCell || !actionsCell) return;

    const currentGrower  = growerCell.innerText.trim();
    const currentVariety = varietyCell.innerText.trim();
    const currentType    = typeCell.innerText.trim();
    const currentLot     = lotCell.innerText.trim();
    const currentDate    = dateCell.innerText.trim();

    const growerSelect  = createSelectFromTemplate('tmplGrowerSelect',  currentGrower,  'edit_bin_grower_'+id);
    const varietySelect = createSelectFromTemplate('tmplVarietySelect', currentVariety, 'edit_bin_variety_'+id);
    const typeSelect    = createSelectFromTemplate('tmplTypeSelect',    currentType,    'edit_bin_type_'+id);

    if (!growerSelect || !varietySelect || !typeSelect) {
        alert('Error preparing inline edit controls');
        return;
    }

    growerCell.innerHTML = '';
    growerCell.appendChild(growerSelect);

    varietyCell.innerHTML = '';
    varietyCell.appendChild(varietySelect);

    typeCell.innerHTML = '';
    typeCell.appendChild(typeSelect);

    lotCell.innerHTML =
        `<input type="text" class="form-control form-control-sm" id="edit_bin_lot_${id}" value="${currentLot}">`;

    dateCell.innerHTML =
        `<input type="date" class="form-control form-control-sm" id="edit_bin_date_${id}" value="${currentDate}">`;

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

function saveBinInline(id) {
    const growerEl  = document.getElementById('edit_bin_grower_'+id);
    const varietyEl = document.getElementById('edit_bin_variety_'+id);
    const typeEl    = document.getElementById('edit_bin_type_'+id);
    const lotEl     = document.getElementById('edit_bin_lot_'+id);
    const dateEl    = document.getElementById('edit_bin_date_'+id);

    if (!growerEl || !varietyEl || !typeEl || !lotEl || !dateEl) {
        alert('Missing inline edit fields');
        return;
    }

    const fd = new FormData();
    fd.append('action','edit_single_inline');
    fd.append('id', id);
    fd.append('grower',  growerEl.value);
    fd.append('variety', varietyEl.value);
    fd.append('type',    typeEl.value);
    fd.append('lot',     lotEl.value);
    fd.append('date',    dateEl.value);

    fetch('bins_ingresso.php', {
        method: 'POST',
        body: fd
    })
    .then(r => r.text())
    .then(txt => {
        if (txt.trim() === 'OK') {
            location.reload();
        } else {
            alert('Error saving bin edit');
        }
    });
}

function toggleGroup(id) {
    let row = document.getElementById("group_" + id);
    let arrow = document.getElementById("arrow_" + id);
    if (!row || !arrow) return;

    document.querySelectorAll('.collapse').forEach(function(el) {
        if (el.id !== "group_" + id) el.classList.remove('show');
    });
    document.querySelectorAll('.arrow').forEach(function(a) {
        if (a.id !== "arrow_" + id) a.classList.remove('open');
    });

    if (row.classList.contains('show')) {
        row.classList.remove('show');
        arrow.classList.remove('open');
    } else {
        row.classList.add('show');
        arrow.classList.add('open');
    }
}

function applyFilters() {
    let searchEl = document.getElementById("searchInput");
    let growerEl = document.getElementById("filterGrower");
    let varietyEl = document.getElementById("filterVariety");
    let typeEl = document.getElementById("filterType");

    if (!searchEl || !growerEl || !varietyEl || !typeEl) return;

    let search = searchEl.value.toLowerCase();
    let grower = growerEl.value.toLowerCase();
    let variety = varietyEl.value.toLowerCase();
    let type = typeEl.value.toLowerCase();

    document.querySelectorAll(".group-row").forEach(function(row) {
        let g = (row.dataset.grower || '').toLowerCase();
        let v = (row.dataset.variety || '').toLowerCase();
        let t = (row.dataset.type || '').toLowerCase();
        let l = (row.dataset.lot || '').toLowerCase();
        let id = row.dataset.id;

        let match = true;

        if (search && !(g.includes(search) || v.includes(search) || l.includes(search))) match = false;
        if (grower && g !== grower) match = false;
        if (variety && v !== variety) match = false;
        if (type && t !== type) match = false;

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

        let sub = document.getElementById("group_" + id);
        if (sub && !match) {
            sub.classList.remove('show');
            let a = document.getElementById("arrow_" + id);
            if (a) a.classList.remove('open');
        }
    });
}

window.addEventListener('DOMContentLoaded', function() {
    let searchEl = document.getElementById("searchInput");
    let growerEl = document.getElementById("filterGrower");
    let varietyEl = document.getElementById("filterVariety");
    let typeEl = document.getElementById("filterType");

    if (searchEl) searchEl.addEventListener("input", applyFilters);
    if (growerEl) growerEl.addEventListener("change", applyFilters);
    if (varietyEl) varietyEl.addEventListener("change", applyFilters);
    if (typeEl) typeEl.addEventListener("change", applyFilters);
});

function expandAll() {
    document.querySelectorAll('.collapse').forEach(c => c.classList.add('show'));
    document.querySelectorAll('.arrow').forEach(a => a.classList.add('open'));
}

function collapseAll() {
    document.querySelectorAll('.collapse').forEach(c => c.classList.remove('show'));
    document.querySelectorAll('.arrow').forEach(a => a.classList.remove('open'));
}
</script>
