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

session_start();
if (!isset($_SESSION['user'])) {
    header('Location: /smproduce/auth/login.php');
    exit;
}

require_once __DIR__ . '/../config/database_ibc.php';
$mysqli = ibc_get_connection();

// MESSAGGI
$msg = null;
$err = null;

// Ensure movement log table exists
$mysqli->query("
    CREATE TABLE IF NOT EXISTS bin_movements (
        id INT AUTO_INCREMENT PRIMARY KEY,
        group_id INT NOT NULL,
        bin_id INT NOT NULL,
        related_bin_id INT DEFAULT NULL,
        movement_type ENUM('IN','OUT') NOT NULL,
        quantity INT NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

// Helper to get next dump batch id
function bm_next_group_id($mysqli) {
    $res = $mysqli->query("SELECT COALESCE(MAX(group_id),0)+1 AS next_id FROM bin_movements");
    if ($res && $row = $res->fetch_assoc()) {
        return (int)$row['next_id'];
    }
    return 1;
}

// Undo last dump batch
function bm_undo_last_dump($mysqli, &$msg, &$err) {
    // Find last OUT group
    $res = $mysqli->query("
        SELECT group_id
        FROM bin_movements
        WHERE movement_type='OUT'
        ORDER BY id DESC
        LIMIT 1
    ");
    if (!$res || !$res->num_rows) {
        $err = "No dump batches found to undo.";
        return;
    }
    $row = $res->fetch_assoc();
    $group_id = (int)$row['group_id'];

    // Load movements for that batch
    $res = $mysqli->query("
        SELECT id, bin_id, related_bin_id, quantity
        FROM bin_movements
        WHERE group_id={$group_id} AND movement_type='OUT'
        ORDER BY id ASC
    ");
    if (!$res || !$res->num_rows) {
        $err = "No movements found for last dump.";
        return;
    }

    $restored_bins = 0;
    $restored_qty  = 0;

    while ($mv = $res->fetch_assoc()) {
        $bin_id        = (int)$mv['bin_id'];
        $related_id    = $mv['related_bin_id'] !== null ? (int)$mv['related_bin_id'] : 0;
        $q             = (int)$mv['quantity'];

        if ($bin_id <= 0 || $q <= 0) continue;

        if ($related_id > 0) {
            // Partial dump: dumped row -> delete, add qty back to original AVAILABLE row
            $mysqli->query("UPDATE bins_ingresso SET quantity = quantity + {$q} WHERE id={$related_id} AND status='AVAILABLE'");
            if ($mysqli->affected_rows > 0) {
                $mysqli->query("DELETE FROM bins_ingresso WHERE id={$bin_id} AND status='DUMPED'");
                $restored_bins++;
                $restored_qty += $q;
            }
        } else {
            // Full dump: same row was marked DUMPED -> set back to AVAILABLE
            $mysqli->query("UPDATE bins_ingresso SET status='AVAILABLE' WHERE id={$bin_id} AND status='DUMPED'");
            if ($mysqli->affected_rows > 0) {
                $restored_bins++;
                $restored_qty += $q;
            }
        }
    }

    // Remove movements for that batch (optional)
    $mysqli->query("DELETE FROM bin_movements WHERE group_id={$group_id} AND movement_type='OUT'");

    if ($restored_bins > 0) {
        $msg = "Undo last dump: restored {$restored_bins} bins, quantity {$restored_qty}.";
    } else {
        $err = "Nothing could be restored from last dump.";
    }
}

// ----- AZIONI POST (BULK) -----
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $action = isset($_POST['action']) ? $_POST['action'] : '';

    // Undo last dump does not require selection
    if ($action === 'undo_last_dump') {
        bm_undo_last_dump($mysqli, $msg, $err);
    } else {
        $selected = isset($_POST['bins']) && is_array($_POST['bins']) ? $_POST['bins'] : [];

        // filtra ID numerici
        $ids = [];
        foreach ($selected as $id) {
            $id = (int)$id;
            if ($id > 0) {
                $ids[] = $id;
            }
        }

        if (empty($ids)) {
            $err = "No bins selected.";
        } else {
            $idList = implode(',', $ids);

            if ($action === 'bulk_dump') {
                $mode   = isset($_POST['dump_mode'])   ? $_POST['dump_mode']   : 'full';
                $amount = isset($_POST['dump_amount']) ? (int)$_POST['dump_amount'] : 0;

                if ($mode === 'partial' && $amount <= 0) {
                    $err = "For partial dump you must specify a quantity > 0.";
                } else {
                    // Load selected bins (only AVAILABLE)
                    $res = $mysqli->query("
                        SELECT id, grower, date, variety, lot, quantity, status
                        FROM bins_ingresso
                        WHERE id IN ($idList) AND status='AVAILABLE'
                        ORDER BY id ASC
                    ");
                    if (!$res || !$res->num_rows) {
                        $err = "No AVAILABLE bins found for dumping.";
                    } else {
                        $group_id = bm_next_group_id($mysqli);
                        $processed = 0;
                        $processed_qty = 0;

                        while ($bin = $res->fetch_assoc()) {
                            $bin_id  = (int)$bin['id'];
                            $qty_now = (int)$bin['quantity'];
                            if ($qty_now <= 0) continue;

                            if ($mode === 'full') {
                                $dump_qty = $qty_now;
                                // Mark same row as DUMPED, keep quantity for stats
                                $mysqli->query("
                                    UPDATE bins_ingresso
                                    SET status='DUMPED', updated_at=NOW()
                                    WHERE id={$bin_id} AND status='AVAILABLE'
                                ");
                                if ($mysqli->affected_rows > 0) {
                                    // Log movement: OUT full
                                    $mysqli->query("
                                        INSERT INTO bin_movements (group_id, bin_id, related_bin_id, movement_type, quantity)
                                        VALUES ({$group_id}, {$bin_id}, NULL, 'OUT', {$dump_qty})
                                    ");
                                    $processed++;
                                    $processed_qty += $dump_qty;
                                }
                            } else {
                                // PARTIAL dump
                                $dump_qty = min($amount, $qty_now);
                                if ($dump_qty <= 0) continue;
                                $remaining = $qty_now - $dump_qty;

                                if ($remaining <= 0) {
                                    // Equivalent to full dump
                                    $mysqli->query("
                                        UPDATE bins_ingresso
                                        SET status='DUMPED', updated_at=NOW()
                                        WHERE id={$bin_id} AND status='AVAILABLE'
                                    ");
                                    if ($mysqli->affected_rows > 0) {
                                        $mysqli->query("
                                            INSERT INTO bin_movements (group_id, bin_id, related_bin_id, movement_type, quantity)
                                            VALUES ({$group_id}, {$bin_id}, NULL, 'OUT', {$dump_qty})
                                        ");
                                        $processed++;
                                        $processed_qty += $dump_qty;
                                    }
                                } else {
                                    // True partial dump: reduce AVAILABLE row and create DUMPED row
                                    $mysqli->query("
                                        UPDATE bins_ingresso
                                        SET quantity={$remaining}, updated_at=NOW()
                                        WHERE id={$bin_id} AND status='AVAILABLE'
                                    ");
                                    if ($mysqli->affected_rows > 0) {
                                        $grower  = $mysqli->real_escape_string($bin['grower']);
                                        $variety = $mysqli->real_escape_string($bin['variety']);
                                        $lot     = $mysqli->real_escape_string($bin['lot']);
                                        $date    = $bin['date'];

                                        $mysqli->query("
                                            INSERT INTO bins_ingresso (grower, date, variety, lot, quantity, status, created_at, updated_at)
                                            VALUES ('{$grower}', '{$date}', '{$variety}', '{$lot}', {$dump_qty}, 'DUMPED', NOW(), NOW())
                                        ");
                                        $new_id = $mysqli->insert_id;

                                        if ($new_id > 0) {
                                            $mysqli->query("
                                                INSERT INTO bin_movements (group_id, bin_id, related_bin_id, movement_type, quantity)
                                                VALUES ({$group_id}, {$new_id}, {$bin_id}, 'OUT', {$dump_qty})
                                            ");
                                            $processed++;
                                            $processed_qty += $dump_qty;
                                        }
                                    }
                                }
                            }
                        } // while bins

                        if ($processed > 0) {
                            $msg = "Dump completed: {$processed} bins processed, quantity {$processed_qty}.";
                        } else {
                            $err = "No bins were dumped. They may no longer be AVAILABLE.";
                        }
                    }
                }

            } elseif ($action === 'bulk_export') {
                // handled client-side

            } elseif ($action === 'bulk_mark_used') {
                $sql = "UPDATE bins_ingresso SET status = 'USED' WHERE id IN ($idList)";
                if ($mysqli->query($sql)) {
                    $msg = "Marked " . count($ids) . " bins as USED.";
                } else {
                    $err = "Error marking bins as used: " . $mysqli->error;
                }

            } elseif ($action === 'bulk_mark_damaged') {
                $sql = "UPDATE bins_ingresso SET status = 'DAMAGED' WHERE id IN ($idList)";
                if ($mysqli->query($sql)) {
                    $msg = "Marked " . count($ids) . " bins as DAMAGED.";
                } else {
                    $err = "Error marking bins as damaged: " . $mysqli->error;
                }

            } elseif ($action === 'bulk_delete') {
                $sql = "DELETE FROM bins_ingresso WHERE id IN ($idList)";
                if ($mysqli->query($sql)) {
                    $msg = "Deleted " . $mysqli->affected_rows . " bins.";
                } else {
                    $err = "Error deleting bins: " . $mysqli->error;
                }
            }
        }
    }
}

// ----- CARICA INVENTARIO BINS -----
$bins = [];
$res = $mysqli->query("SELECT * FROM bins_ingresso ORDER BY id DESC");
if ($res) {
    while ($row = $res->fetch_assoc()) {
        $bins[] = $row;
    }
    $res->free();
}

// Colonne dinamiche
$columns = [];
if (!empty($bins)) {
    $columns = array_keys($bins[0]);
}
?>
<?php include __DIR__ . '/../includes/header.php'; ?>
<main class="flex-grow-1">
  <div class="container-fluid">

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

    <div class="card mb-3 mt-2">
      <div class="card-header d-flex justify-content-between align-items-center">
        <span>Inventory (bins_ingresso)</span>
        <input type="text" id="globalFilter" class="form-control form-control-sm" style="max-width:220px;" placeholder="Search all columns...">
      </div>
      <div class="card-body">

        <form method="post" id="binsForm">
          <input type="hidden" name="action" id="binsAction">
          <input type="hidden" name="dump_mode" id="dumpMode">
          <input type="hidden" name="dump_amount" id="dumpAmount">

          <div class="d-flex justify-content-between align-items-center mb-2">
            <div class="toolbar-gap">
              <div class="btn-group btn-group-sm">
                <button type="button" class="btn btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown">
                  Bulk actions
                </button>
                <ul class="dropdown-menu">
                  <li><button class="dropdown-item" type="button" onclick="openDumpModal()">Dump selected...</button></li>
                  <li><button class="dropdown-item" type="button" onclick="undoLastDump()">Undo last dump</button></li>
                  <li><button class="dropdown-item" type="button" onclick="exportSelectedCSV()">Export selected CSV</button></li>
                  <li><hr class="dropdown-divider"></li>
                  <li><button class="dropdown-item" type="button" onclick="bulkAction('bulk_mark_used')">Mark as USED</button></li>
                  <li><button class="dropdown-item" type="button" onclick="bulkAction('bulk_mark_damaged')">Mark as DAMAGED</button></li>
                  <li><hr class="dropdown-divider"></li>
                  <li><button class="dropdown-item text-danger" type="button" onclick="bulkAction('bulk_delete')">Delete selected</button></li>
                </ul>
              </div>
            </div>
            <small class="text-muted"><?= count($bins) ?> rows</small>
          </div>

          <div class="table-wrapper">
            <table class="table table-sm table-striped mb-0" id="binsTable">
              <thead class="sticky-header">
                <tr>
                  <th style="width:30px;">
                    <input type="checkbox" id="checkAllBins">
                  </th>
                  <?php foreach ($columns as $colName): ?>
                    <th>
                      <span class="col-title"><?= htmlspecialchars($colName) ?></span>
                      <span class="sort-icons">
                        <span class="sort-icon sort-asc">▲</span>
                        <span class="sort-icon sort-desc">▼</span>
                      </span>
                    </th>
                  <?php endforeach; ?>
                </tr>
              </thead>
              <thead class="sticky-filters">
                <tr>
                  <th></th>
                  <?php foreach ($columns as $index => $colName): ?>
                    <th>
                      <input type="text"
                             class="form-control form-control-sm column-filter"
                             data-col-index="<?= $index ?>"
                             placeholder="Filter">
                    </th>
                  <?php endforeach; ?>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($bins as $row): ?>
                  <tr>
                    <td>
                      <input type="checkbox" class="binchk" name="bins[]" value="<?= htmlspecialchars($row['id']) ?>">
                    </td>
                    <?php foreach ($columns as $colName): ?>
                      <td><?= htmlspecialchars((string)$row[$colName]) ?></td>
                    <?php endforeach; ?>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>

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

    <!-- Modal dump -->
    <div class="modal" tabindex="-1" id="dumpModal">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">Dump selected bins</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <p>Choose how you want to dump the selected bins:</p>
            <div class="form-check mb-2">
              <input class="form-check-input" type="radio" name="dump_mode_radio" id="dumpFull" value="full" checked>
              <label class="form-check-label" for="dumpFull">
                Full dump (set quantity to 0)
              </label>
            </div>
            <div class="form-check mb-3">
              <input class="form-check-input" type="radio" name="dump_mode_radio" id="dumpPartial" value="partial">
              <label class="form-check-label" for="dumpPartial">
                Partial dump (subtract quantity from each bin)
              </label>
            </div>
            <div class="mb-3">
              <label class="form-label small" for="dumpAmountInput">Quantity to subtract (only used for partial dump)</label>
              <input type="number" min="1" class="form-control" id="dumpAmountInput" placeholder="e.g. 1, 2, 5...">
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
            <button type="button" class="btn btn-danger" onclick="confirmDump()">Confirm dump</button>
          </div>
        </div>
      </div>
    </div>

  </div>
</main>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
(function() {
  const tableEl = document.getElementById('binsTable');
  if (!tableEl) return;
  const ths = tableEl.querySelectorAll('thead.sticky-header th');
  const sortStorageKey = 'bins_sort_bins_ingresso';

  function applySort(colIndex, direction, save) {
    const tbody = tableEl.querySelector('tbody');
    if (!tbody) return;
    const rows = Array.from(tbody.querySelectorAll('tr'));

    ths.forEach(th => {
      th.removeAttribute('data-dir');
      const ascIcon = th.querySelector('.sort-icon.sort-asc');
      const descIcon = th.querySelector('.sort-icon.sort-desc');
      if (ascIcon) ascIcon.classList.remove('active');
      if (descIcon) descIcon.classList.remove('active');
    });

    const th = ths[colIndex];
    if (!th) return;

    th.setAttribute('data-dir', direction);
    const ascIcon = th.querySelector('.sort-icon.sort-asc');
    const descIcon = th.querySelector('.sort-icon.sort-desc');
    if (direction === 'asc') {
      if (ascIcon) ascIcon.classList.add('active');
    } else {
      if (descIcon) descIcon.classList.add('active');
    }

    rows.sort((a, b) => {
      const A = (a.children[colIndex] && a.children[colIndex].innerText || '').trim();
      const B = (b.children[colIndex] && b.children[colIndex].innerText || '').trim();
      return direction === 'asc'
        ? A.localeCompare(B, undefined, {numeric: true})
        : B.localeCompare(A, undefined, {numeric: true});
    });

    rows.forEach(r => tbody.appendChild(r));

    if (save) {
      try {
        localStorage.setItem(sortStorageKey, JSON.stringify({idx: colIndex, dir: direction}));
      } catch (e) {}
    }
  }

  ths.forEach((th, idx) => {
    if (idx === 0) return; // checkbox col
    if (!th.querySelector('.sort-icons')) return;
    th.style.cursor = 'pointer';
    th.addEventListener('click', () => {
      const current = th.getAttribute('data-dir') || 'none';
      const nextDir = (current === 'asc') ? 'desc' : 'asc';
      applySort(idx, nextDir, true);
    });
  });

  try {
    const saved = localStorage.getItem(sortStorageKey);
    if (saved) {
      const data = JSON.parse(saved);
      if (data && typeof data.idx === 'number' && (data.dir === 'asc' || data.dir === 'desc')) {
        applySort(data.idx, data.dir, false);
      }
    }
  } catch (e) {}
})();

// filtri per colonna + filtro globale
(function() {
  const tableEl = document.getElementById('binsTable');
  if (!tableEl) return;
  const filterInputs = document.querySelectorAll('.column-filter');
  const globalFilter = document.getElementById('globalFilter');

  function applyFilters() {
    const tbody = tableEl.querySelector('tbody');
    const rows = tbody.querySelectorAll('tr');

    const filters = [];
    filterInputs.forEach(input => {
      const idx = parseInt(input.getAttribute('data-col-index'), 10);
      const val = input.value.toLowerCase();
      filters[idx] = val;
    });

    const globalVal = globalFilter.value.toLowerCase();

    rows.forEach(row => {
      const cells = row.querySelectorAll('td');
      let visible = true;

      // filtro per colonna
      filters.forEach((val, idx) => {
        if (!val) return;
        const cell = cells[idx + 1]; // +1 per checkbox col
        if (!cell) return;
        if (cell.innerText.toLowerCase().indexOf(val) === -1) {
          visible = false;
        }
      });

      // filtro globale
      if (visible && globalVal) {
        const text = row.innerText.toLowerCase();
        if (text.indexOf(globalVal) === -1) {
          visible = false;
        }
      }

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

  filterInputs.forEach(input => {
    input.addEventListener('input', applyFilters);
  });
  if (globalFilter) {
    globalFilter.addEventListener('input', applyFilters);
  }
})();

// select all
(function() {
  const checkAll = document.getElementById('checkAllBins');
  if (!checkAll) return;
  checkAll.addEventListener('change', function() {
    const checks = document.querySelectorAll('.binchk');
    checks.forEach(ch => { ch.checked = checkAll.checked; });
  });
})();

function bulkAction(actionName) {
  const anySelected = !!document.querySelector('.binchk:checked');
  if (!anySelected) {
    alert('No bins selected.');
    return;
  }
  if (actionName === 'bulk_delete') {
    if (!confirm('Delete selected bins?')) return;
  }
  document.getElementById('binsAction').value = actionName;
  document.getElementById('binsForm').submit();
}

let dumpModalInstance = null;
function openDumpModal() {
  const anySelected = !!document.querySelector('.binchk:checked');
  if (!anySelected) {
    alert('No bins selected.');
    return;
  }
  const modalEl = document.getElementById('dumpModal');
  if (!modalEl) return;
  if (!dumpModalInstance) {
    dumpModalInstance = new bootstrap.Modal(modalEl);
  }
  dumpModalInstance.show();
}

function confirmDump() {
  const fullRadio = document.getElementById('dumpFull');
  const partialRadio = document.getElementById('dumpPartial');
  const amountInput = document.getElementById('dumpAmountInput');
  const modeInput = document.getElementById('dumpMode');
  const amountHidden = document.getElementById('dumpAmount');

  let mode = 'full';
  let amount = 0;

  if (partialRadio.checked) {
    mode = 'partial';
    amount = parseInt(amountInput.value, 10);
    if (isNaN(amount) || amount <= 0) {
      alert('Please enter a valid quantity > 0 for partial dump.');
      return;
    }
  }

  modeInput.value = mode;
  amountHidden.value = amount;
  document.getElementById('binsAction').value = 'bulk_dump';

  if (dumpModalInstance) dumpModalInstance.hide();

  document.getElementById('binsForm').submit();
}

function exportSelectedCSV() {
  const rows = Array.from(document.querySelectorAll('#binsTable tbody tr'))
    .filter(tr => {
      const cb = tr.querySelector('.binchk');
      return cb && cb.checked;
    });

  if (rows.length === 0) {
    alert('No bins selected.');
    return;
  }

  const headerRow = document.querySelector('#binsTable thead.sticky-header tr');
  const headers = [];
  headerRow.querySelectorAll('th').forEach((th, idx) => {
    if (idx === 0) return; // skip checkbox
    const titleEl = th.querySelector('.col-title');
    if (titleEl) {
      headers.push('"' + titleEl.innerText.replace(/"/g, '""') + '"');
    }
  });

  let csv = headers.join(',') + "\n";

  rows.forEach(tr => {
    const cells = tr.querySelectorAll('td');
    const rowVals = [];
    for (let i = 1; i < cells.length; i++) { // skip checkbox col
      const txt = (cells[i].innerText || '').trim();
      rowVals.push('"' + txt.replace(/"/g, '""') + '"');
    }
    csv += rowVals.join(',') + "\n";
  });

  const blob = new Blob([csv], {type: 'text/csv;charset=utf-8;'});
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'bins_ingresso_selected.csv';
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}

function undoLastDump() {
  if (!confirm('Undo last dump batch?')) return;
  const form = document.getElementById('binsForm');
  if (!form) return;
  document.getElementById('binsAction').value = 'undo_last_dump';
  form.submit();
}


</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>
