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

if (session_status() === PHP_SESSION_NONE) { 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('Accesso negato');
}

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

$table = $_GET['table'] ?? '';
if ($table === '') {
    die('Nessuna tabella selezionata.');
}
$tableSafe = $mysqli->real_escape_string($table);

// carica metadati colonne
$colsRes = $mysqli->query("SHOW COLUMNS FROM `$tableSafe`");
if (!$colsRes) {
    die('Errore nel caricamento delle colonne per la tabella: ' . htmlspecialchars($table));
}
$cols = $colsRes->fetch_all(MYSQLI_ASSOC);
$colNames = array_column($cols, 'Field');

// chiave primaria (se esiste)
$primaryKey = null;
foreach ($cols as $c) {
    if ($c['Key'] === 'PRI') {
        $primaryKey = $c['Field'];
        break;
    }
}
$allowDelete = (bool)$primaryKey;

// filtri
$search = trim($_GET['search'] ?? '');
$colFilters = $_GET['col_filters'] ?? [];
if (!is_array($colFilters)) $colFilters = [];

$whereParts = [];

// ricerca globale
if ($search !== '') {
    $s = $mysqli->real_escape_string($search);
    $likes = [];
    foreach ($colNames as $c) {
        $likes[] = "`$c` LIKE '%$s%'";
    }
    if ($likes) {
        $whereParts[] = '(' . implode(' OR ', $likes) . ')';
    }
}

// filtri per colonna
foreach ($colFilters as $col => $val) {
    if ($val === '' || !in_array($col, $colNames, true)) continue;
    $v = $mysqli->real_escape_string($val);
    $whereParts[] = "`$col` LIKE '%$v%'";
}
$whereSql = $whereParts ? 'WHERE ' . implode(' AND ', $whereParts) : '';

// ordinamento
$defaultOrderCol = $primaryKey ?: ($colNames[0] ?? null);
$sortCol = $_GET['sort_col'] ?? $defaultOrderCol;
if (!in_array($sortCol, $colNames, true)) {
    $sortCol = $defaultOrderCol;
}
$sortDir = strtolower($_GET['sort_dir'] ?? 'desc');
if (!in_array($sortDir, ['asc','desc'], true)) {
    $sortDir = 'desc';
}
$orderSql = $sortCol ? "ORDER BY `$sortCol` $sortDir" : '';

// paginazione
$page = max(1, (int)($_GET['page'] ?? 1));
$pageSize = 50;
$offset = ($page - 1) * $pageSize;

$countSql = "SELECT COUNT(*) AS c FROM `$tableSafe` $whereSql";
$countRes = $mysqli->query($countSql);
$totalRows = $countRes ? (int)($countRes->fetch_assoc()['c'] ?? 0) : 0;

$dataSql = "SELECT * FROM `$tableSafe` $whereSql $orderSql LIMIT $pageSize OFFSET $offset";
$dataRes = $mysqli->query($dataSql);
$rows = $dataRes ? $dataRes->fetch_all(MYSQLI_ASSOC) : [];

$totalPages = max(1, (int)ceil($totalRows / $pageSize));

$jsCols    = json_encode($colNames);
$jsTable   = json_encode($table);
$jsPrimary = json_encode($primaryKey);
$jsSortCol = json_encode($sortCol);
$jsSortDir = json_encode($sortDir);

include('../includes/header.php');
include('../includes/sidebar.php');
?>
<style>
.ibc-card {
    border-radius: 12px;
    box-shadow: 0 6px 16px rgba(15,23,42,0.06);
}
.ibc-table thead th {
    background-color: #f9fafb;
    position: sticky;
    top: 0;
    z-index: 5;
}
.ibc-table tbody tr:hover {
    background-color: #eef2ff;
}
.ibc-badge-col {
    font-size: 0.8rem;
    padding: 4px 8px;
    border-radius: 999px;
    background-color: #e5e7eb;
}
.ibc-toolbar .btn {
    margin-right: 6px;
}
.ibc-search-input {
    max-width: 280px;
}
.ibc-table td,
.ibc-table th {
    padding-top: 0.45rem;
    padding-bottom: 0.45rem;
    vertical-align: middle;
    white-space: nowrap;
}
.ibc-table td {
    max-width: 260px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
}
</style>

<div class="container-fluid py-4">
  <h3 class="mb-3">
    IBC Manager – Tabella
    <span class="badge bg-secondary-subtle border text-dark"><?= htmlspecialchars($table) ?></span>
  </h3>

  <div class="card mb-4 ibc-card">
    <div class="card-header d-flex justify-content-between align-items-center">
      <span class="fw-semibold">Dati tabella</span>
      <span class="text-muted small">
        <?= number_format($totalRows) ?> righe · <?= count($colNames) ?> colonne
      </span>
    </div>
    <div class="card-body">

      <!-- TOOLBAR -->
      <div class="row mb-3 align-items-center">
        <div class="col-md-4 mb-2">
          <form method="get" class="d-flex gap-2">
            <input type="hidden" name="table" value="<?= htmlspecialchars($table) ?>">
            <input type="hidden" name="sort_col" value="<?= htmlspecialchars($sortCol) ?>">
            <input type="hidden" name="sort_dir" value="<?= htmlspecialchars($sortDir) ?>">
            <input type="text"
                   name="search"
                   class="form-control ibc-search-input"
                   placeholder="Cerca in tutte le colonne..."
                   value="<?= htmlspecialchars($search) ?>">
            <button class="btn btn-outline-primary">Cerca</button>
          </form>
        </div>
        <div class="col-md-8 mb-2 text-md-end ibc-toolbar">
          <?php if ($allowDelete): ?>
          <button class="btn btn-danger btn-sm" onclick="ibcDeleteSelected()">
            Elimina selezionati
          </button>
          <?php else: ?>
          <button class="btn btn-danger btn-sm" disabled
                  title="Questa tabella non ha una chiave primaria; eliminazione di massa disabilitata.">
            Elimina selezionati
          </button>
          <?php endif; ?>

          <button class="btn btn-secondary btn-sm" onclick="ibcExportCSV()">
            Esporta CSV
          </button>

          <a href="ibc_manager.php" class="btn btn-outline-secondary btn-sm">
            Lista tabelle
          </a>

          <a href="?table=<?= urlencode($table) ?>" class="btn btn-outline-primary btn-sm">
            Aggiorna
          </a>
        </div>
      </div>

      <!-- FORM NASCOSTO FILTRI -->
      <form id="ibcFilterForm" method="get" class="d-none">
        <input type="hidden" name="table" value="<?= htmlspecialchars($table) ?>">
        <input type="hidden" name="search" value="<?= htmlspecialchars($search) ?>">
        <input type="hidden" name="sort_col" value="<?= htmlspecialchars($sortCol) ?>">
        <input type="hidden" name="sort_dir" value="<?= htmlspecialchars($sortDir) ?>">
        <?php foreach ($colNames as $c): ?>
          <input type="hidden"
                 name="col_filters[<?= htmlspecialchars($c) ?>]"
                 value="<?= htmlspecialchars($colFilters[$c] ?? '') ?>">
        <?php endforeach; ?>
      </form>

      <!-- TABELLA DATI -->
      <div class="table-responsive" style="border-radius:10px; border:1px solid #e5e7eb; overflow:auto;">
        <table class="table table-hover mb-0 ibc-table align-middle">
          <thead class="table-light">
            <tr>
              <th style="width:34px;">
                <?php if ($allowDelete): ?>
                  <input type="checkbox" onclick="ibcToggleAll(this)">
                <?php endif; ?>
              </th>
              <?php foreach ($colNames as $c): ?>
                <?php
                  $isSorted = ($c === $sortCol);
                  $nextDir  = ($isSorted && $sortDir === 'asc') ? 'desc' : 'asc';
                  $icon = '';
                  if ($isSorted) $icon = $sortDir === 'asc' ? '▲' : '▼';
                  $params = [
                    'table'    => $table,
                    'search'   => $search,
                    'sort_col' => $c,
                    'sort_dir' => $nextDir,
                    'page'     => 1,
                  ];
                  foreach ($colFilters as $fc => $fv) {
                      $params["col_filters[$fc]"] = $fv;
                  }
                  $sortUrl = '?' . http_build_query($params);
                ?>
                <th>
                  <a href="<?= htmlspecialchars($sortUrl) ?>" class="text-decoration-none text-dark">
                    <span class="ibc-badge-col"><?= htmlspecialchars($c) ?></span>
                    <?php if ($icon): ?>
                      <span class="ibc-sort-indicator"><?= $icon ?></span>
                    <?php endif; ?>
                  </a>
                </th>
              <?php endforeach; ?>
              <th style="width:150px;">Azioni</th>
            </tr>
            <tr>
              <th></th>
              <?php foreach ($colNames as $c): ?>
                <th>
                  <input type="text"
                         class="form-control form-control-sm"
                         placeholder="Filtro..."
                         value="<?= htmlspecialchars($colFilters[$c] ?? '') ?>"
                         onchange="ibcSetColumnFilter('<?= htmlspecialchars($c) ?>', this.value)">
                </th>
              <?php endforeach; ?>
              <th class="text-end">
                <button type="button"
                        class="btn btn-sm btn-outline-primary"
                        onclick="document.getElementById('ibcFilterForm').submit();">
                  Applica
                </button>
              </th>
            </tr>
          </thead>
          <tbody>
          <?php if (!$rows): ?>
            <tr>
              <td colspan="<?= count($colNames) + 2 ?>" class="text-center text-muted py-4">
                Nessun dato trovato.
              </td>
            </tr>
          <?php else: ?>
            <?php foreach ($rows as $row): ?>
              <?php
                $pkValue = $primaryKey ? ($row[$primaryKey] ?? null) : null;
                $rowJson = htmlspecialchars(json_encode($row), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
              ?>
              <tr
                <?php if ($pkValue !== null): ?>
                data-pk="<?= htmlspecialchars($pkValue) ?>"
                <?php endif; ?>
                data-row="<?= $rowJson ?>"
              >
                <td>
                  <?php if ($allowDelete && $pkValue !== null): ?>
                    <input type="checkbox" class="ibc-row-check">
                  <?php endif; ?>
                </td>
                <?php foreach ($colNames as $c): ?>
                  <td data-col="<?= htmlspecialchars($c) ?>">
                    <?= htmlspecialchars($row[$c] ?? '') ?>
                  </td>
                <?php endforeach; ?>
                <td>
                  <div class="btn-group btn-group-sm">
                    <button type="button"
                            class="btn btn-outline-secondary"
                            onclick="ibcShowRowDetails(this)">
                      Dettagli
                    </button>
                    <?php if ($primaryKey): ?>
                    <button type="button"
                            class="btn btn-outline-primary"
                            onclick="ibcInlineEditRow(this)">
                      Modifica
                    </button>
                    <button type="button"
                            class="btn btn-outline-danger"
                            onclick="ibcDeleteSingle(this)">
                      Elimina
                    </button>
                    <?php endif; ?>
                  </div>
                </td>
              </tr>
            <?php endforeach; ?>
          <?php endif; ?>
          </tbody>
        </table>
      </div>

      <!-- PAGINAZIONE -->
      <div class="mt-3 d-flex justify-content-between align-items-center">
        <div class="small text-muted">
          Pagina <?= $page ?> di <?= $totalPages ?> ·
          <?= count($rows) ?> righe visualizzate
        </div>
        <nav>
          <ul class="pagination pagination-sm mb-0">
            <?php for ($p = 1; $p <= $totalPages; $p++):
              $params = [
                'table'    => $table,
                'page'     => $p,
                'search'   => $search,
                'sort_col' => $sortCol,
                'sort_dir' => $sortDir,
              ];
              foreach ($colFilters as $fc => $fv) {
                  $params["col_filters[$fc]"] = $fv;
              }
              $pageUrl = '?' . http_build_query($params);
            ?>
              <li class="page-item <?= $p === $page ? 'active' : '' ?>">
                <a class="page-link" href="<?= htmlspecialchars($pageUrl) ?>">
                  <?= $p ?>
                </a>
              </li>
            <?php endfor; ?>
          </ul>
        </nav>
      </div>

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

<!-- MODALE DETTAGLI RIGA -->
<div class="modal fade" id="ibcRowModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Dettagli riga</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <table class="table table-sm table-striped">
          <tbody id="ibcRowDetailsBody"></tbody>
        </table>
        <label class="form-label small text-muted">JSON</label>
        <pre id="ibcRowJson" class="bg-light p-2 small" style="max-height:200px; overflow:auto;"></pre>
      </div>
      <div class="modal-footer">
        <button type="button"
                class="btn btn-outline-secondary btn-sm"
                onclick="ibcCopyJson()">
          Copia JSON
        </button>
        <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">
          Chiudi
        </button>
      </div>
    </div>
  </div>
</div>

<script>
const IBC_COLS    = <?= $jsCols ?>;
const IBC_TABLE   = <?= $jsTable ?>;
const IBC_PK      = <?= $jsPrimary ?>;
const IBC_SORTCOL = <?= $jsSortCol ?>;
const IBC_SORTDIR = <?= $jsSortDir ?>;

function ibcToggleAll(master) {
  document.querySelectorAll('.ibc-row-check').forEach(cb => cb.checked = master.checked);
}

function ibcSetColumnFilter(col, value) {
  const form = document.getElementById('ibcFilterForm');
  if (!form) return;
  const name = 'col_filters[' + col + ']';
  let input = form.querySelector('input[name="' + name + '"]');
  if (!input) {
    input = document.createElement('input');
    input.type = 'hidden';
    input.name = name;
    form.appendChild(input);
  }
  input.value = value;
}

function ibcDeleteSelected() {
  const checks = Array.from(document.querySelectorAll('.ibc-row-check:checked'));
  if (!checks.length) {
    alert('Nessuna riga selezionata.');
    return;
  }
  if (!IBC_PK) {
    alert('Tabella senza chiave primaria, impossibile eliminare in blocco.');
    return;
  }
  if (!confirm('Eliminare le righe selezionate?')) return;

  const ids = checks
    .map(cb => cb.closest('tr').dataset.pk)
    .filter(v => v !== undefined && v !== null);

  fetch('ibc_table_delete.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      table: IBC_TABLE,
      primaryKey: IBC_PK,
      ids: ids
    })
  }).then(r => r.text())
    .then(txt => {
      if (txt.trim() === 'OK') {
        location.reload();
      } else {
        console.error(txt);
        alert('Errore durante l\'eliminazione. Vedi console.');
      }
    });
}

function ibcDeleteSingle(btn) {
  const tr = btn.closest('tr');
  if (!tr || !IBC_PK) return;
  const id = tr.dataset.pk;
  if (!id) return;
  if (!confirm('Eliminare questa riga?')) return;

  fetch('ibc_table_delete.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      table: IBC_TABLE,
      primaryKey: IBC_PK,
      ids: [id]
    })
  }).then(r => r.text())
    .then(txt => {
      if (txt.trim() === 'OK') {
        location.reload();
      } else {
        console.error(txt);
        alert('Errore durante l\'eliminazione. Vedi console.');
      }
    });
}

function ibcExportCSV() {
  const url = new URL(window.location.href);
  url.pathname = url.pathname.replace(/ibc_table_view\.php$/, 'ibc_export_csv.php');
  window.location = url.toString();
}

function ibcShowRowDetails(btn) {
  const tr = btn.closest('tr');
  if (!tr) return;
  const data = tr.dataset.row ? JSON.parse(tr.dataset.row) : {};
  const tbody = document.getElementById('ibcRowDetailsBody');
  const pre   = document.getElementById('ibcRowJson');
  if (!tbody || !pre) return;

  tbody.innerHTML = '';
  IBC_COLS.forEach(col => {
    const val = (data[col] !== null && data[col] !== undefined) ? data[col] : '';
    const trDetail = document.createElement('tr');
    trDetail.innerHTML = `
      <th style="width: 180px;">${escapeHtml(col)}</th>
      <td>${escapeHtml(String(val))}</td>
    `;
    tbody.appendChild(trDetail);
  });

  pre.textContent = JSON.stringify(data, null, 2);

  const modalEl = document.getElementById('ibcRowModal');
  if (modalEl) {
    const m = new bootstrap.Modal(modalEl);
    m.show();
  }
}

function ibcCopyJson() {
  const pre = document.getElementById('ibcRowJson');
  if (!pre) return;
  const text = pre.textContent;
  navigator.clipboard.writeText(text).then(
    () => alert('JSON copiato negli appunti'),
    () => alert('Impossibile copiare il JSON')
  );
}

function ibcInlineEditRow(btn) {
  const tr = btn.closest('tr');
  if (!tr || !IBC_PK) return;
  if (tr.classList.contains('ibc-editing')) return;
  tr.classList.add('ibc-editing');

  const data = tr.dataset.row ? JSON.parse(tr.dataset.row) : {};
  const tds  = tr.querySelectorAll('td[data-col]');
  if (!tds.length) return;

  tds.forEach(td => {
    const col = td.dataset.col;
    const val = (data[col] !== null && data[col] !== undefined) ? String(data[col]) : '';
    if (col === IBC_PK) return;
    td.innerHTML = `<input class="form-control form-control-sm" value="${escapeHtml(val)}">`;
  });

  const actionTd = btn.closest('td');
  if (!actionTd) return;
  actionTd.innerHTML = `
    <div class="btn-group btn-group-sm">
      <button type="button" class="btn btn-success" onclick="ibcSaveInlineEdit(this)">Salva</button>
      <button type="button" class="btn btn-secondary" onclick="ibcCancelInlineEdit(this)">Annulla</button>
    </div>
  `;
}

function ibcCancelInlineEdit(btn) {
  location.reload();
}

function ibcSaveInlineEdit(btn) {
  const tr = btn.closest('tr');
  if (!tr || !IBC_PK) return;

  const data = tr.dataset.row ? JSON.parse(tr.dataset.row) : {};
  const tds  = tr.querySelectorAll('td[data-col]');
  const payload = {};
  let pkValue = null;

  tds.forEach(td => {
    const col = td.dataset.col;
    if (!col) return;
    if (col === IBC_PK) {
      pkValue = String((data[col] !== undefined && data[col] !== null) ? data[col] : '');
      return;
    }
    const input = td.querySelector('input');
    const val   = input ? input.value : (data[col] ?? '');
    payload[col] = val;
  });

  if (!pkValue) {
    alert('Chiave primaria non trovata, impossibile salvare.');
    return;
  }

  fetch('ibc_table_edit.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      table: IBC_TABLE,
      primaryKey: IBC_PK,
      id: pkValue,
      data: payload
    })
  }).then(r => r.text())
    .then(txt => {
      if (txt.trim() === 'OK') {
        location.reload();
      } else {
        console.error(txt);
        alert('Errore durante il salvataggio:\n' + txt);
      }
    });
}

function escapeHtml(str) {
  return str
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;');
}
</script>

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