<?php
require __DIR__ . '/../iris-pi-common/_common.php';
require_login();

$flash = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    try {
        // ── ESX hosts ─────────────────────────────────────────
        if ($action === 'esx_update') {
            db()->prepare(
                'UPDATE esx_hosts
                    SET fqdn = ?, datastore_default = ?, iso_path = ?, folder_root = ?
                  WHERE code = ?'
            )->execute([
                trim($_POST['fqdn']),
                trim($_POST['datastore_default']),
                trim($_POST['iso_path']),
                trim($_POST['folder_root']) ?: 'IRIS_V2',
                $_POST['code'],
            ]);
            $flash = "✓ ESX <code>{$_POST['code']}</code> mis à jour";
        }

        // ── Whitelist : add ───────────────────────────────────
        elseif ($action === 'wl_add') {
            db()->prepare(
                'INSERT OR IGNORE INTO esx_whitelist (ip, label, enabled)
                 VALUES (?, ?, 1)'
            )->execute([
                trim($_POST['ip']),
                trim($_POST['label']) ?: 'sans label',
            ]);
            $flash = "✓ IP <code>{$_POST['ip']}</code> ajoutée à la whitelist";
        }

        // ── Whitelist : toggle enabled ────────────────────────
        elseif ($action === 'wl_toggle') {
            db()->prepare(
                'UPDATE esx_whitelist SET enabled = 1 - enabled WHERE id = ?'
            )->execute([(int)$_POST['id']]);
            $flash = "✓ IP whitelist togglée";
        }

        // ── Whitelist : remove ────────────────────────────────
        elseif ($action === 'wl_delete') {
            db()->prepare('DELETE FROM esx_whitelist WHERE id = ?')
                ->execute([(int)$_POST['id']]);
            $flash = "✓ IP whitelist supprimée";
        }

        // ── Whitelist : add depuis access log ─────────────────
        elseif ($action === 'wl_add_from_log') {
            db()->prepare(
                'INSERT OR IGNORE INTO esx_whitelist (ip, label, enabled)
                 VALUES (?, ?, 1)'
            )->execute([
                trim($_POST['ip']),
                'auto-added from access log',
            ]);
            $flash = "✓ IP <code>{$_POST['ip']}</code> ajoutée depuis le log";
        }

    } catch (Throwable $e) {
        $flash = "✗ Erreur : " . h($e->getMessage());
    }
    header('Location: esx.php?flash=' . urlencode($flash));
    exit;
}

if (!empty($_GET['flash'])) $flash = $_GET['flash'];

// ── Données ─────────────────────────────────────────────────────
$esxs = db()->query(
    "SELECT e.*, s.label AS site_label
     FROM esx_hosts e LEFT JOIN sites s ON s.code = e.site_code
     ORDER BY e.code"
)->fetchAll();

$whitelist = db()->query(
    'SELECT * FROM esx_whitelist ORDER BY enabled DESC, label ASC'
)->fetchAll();

// IPs récentes ayant été REFUSÉES (pour bouton "ajouter au whitelist")
$recent_blocked = db()->query(
    "SELECT ip, COUNT(*) as hits, MAX(created_at) AS last_at,
            MAX(endpoint) AS last_endpoint
     FROM pi_access_log
     WHERE allowed = 0 AND created_at > strftime('%s','now','-7 days')
     GROUP BY ip
     ORDER BY last_at DESC
     LIMIT 20"
)->fetchAll();

// Stats des accès réussis (pour visibilité)
$recent_allowed = db()->query(
    "SELECT ip, COUNT(*) as hits, MAX(created_at) AS last_at
     FROM pi_access_log
     WHERE allowed = 1 AND created_at > strftime('%s','now','-7 days')
     GROUP BY ip
     ORDER BY last_at DESC
     LIMIT 10"
)->fetchAll();

$page = 'esx';
$page_title = 'ESX & whitelist IP';
require __DIR__ . '/_header.php';
?>

<style>
.wl-row { display:grid; grid-template-columns: 200px 1fr 80px 180px 100px; gap:12px; align-items:center; padding:8px 14px; border-bottom:1px solid #21262d; font-size:13px; }
.wl-row:last-child { border-bottom:none; }
.wl-row .ip { font-family:'IBM Plex Mono', monospace; }
.wl-row .label { color:var(--muted); }
.wl-row .last-seen { color:var(--muted); font-size:11px; }
.wl-row .actions { text-align:right; }
.disabled { opacity:0.4; }
.add-ip-form { display:grid; grid-template-columns: 200px 1fr auto; gap:12px; padding:14px; }
.add-ip-form input { padding:8px 12px; background:#0d1117; border:1px solid var(--border); color:var(--text); font-family:inherit; border-radius:4px; }
.esx-edit { padding:14px; border-bottom:1px solid #21262d; }
.esx-edit form { display:grid; grid-template-columns: 200px 1fr 1fr 1fr auto; gap:10px; align-items:center; }
.esx-edit input { padding:6px 10px; background:#0d1117; border:1px solid var(--border); color:var(--text); font-family:inherit; border-radius:4px; font-size:12px; }
.tag { display:inline-block; padding:2px 6px; border-radius:3px; font-size:10px; font-weight:bold; text-transform:uppercase; }
.tag.ok  { background:#0d3920; color:var(--green); }
.tag.no  { background:#3d1e1e; color:#ff7b72; }
</style>

<?php if ($flash): ?>
  <div class="flash <?= str_contains($flash, '✗') ? 'error' : '' ?>"><?= $flash ?></div>
<?php endif; ?>

<!-- ─── ESX hosts ───────────────────────────────────────────── -->
<div class="panel">
  <div class="panel-header"><h2>ESX hosts (<?= count($esxs) ?>)</h2></div>
  <?php foreach ($esxs as $e): ?>
    <div class="esx-edit">
      <form method="post">
        <input type="hidden" name="action" value="esx_update">
        <input type="hidden" name="code" value="<?= h($e['code']) ?>">
        <div>
          <strong style="font-size:14px"><?= h($e['code']) ?></strong>
          <span class="muted" style="font-size:11px">(<?= h($e['site_code']) ?>)</span>
        </div>
        <input name="fqdn" value="<?= h($e['fqdn']) ?>" placeholder="ex2.fr.eu.hrig.tech" title="FQDN">
        <input name="datastore_default" value="<?= h($e['datastore_default']) ?>" placeholder="eu3-fr-gra-ds01" title="Datastore">
        <input name="iso_path" value="<?= h($e['iso_path']) ?>" placeholder="[ds] ISO/debian.iso" title="ISO path">
        <input name="folder_root" value="<?= h($e['folder_root']) ?>" placeholder="IRIS_V2" title="Folder root" style="width:90px">
        <button type="submit">Sauver</button>
      </form>
    </div>
  <?php endforeach; ?>
</div>

<!-- ─── Whitelist IP ────────────────────────────────────────── -->
<div class="panel">
  <div class="panel-header">
    <h2>Whitelist IP — accès aux endpoints /pi/</h2>
  </div>
  <div class="panel-body" style="padding:14px;color:var(--muted);font-size:12px">
    Les IPs listées ici peuvent accéder à <code>preseed.php</code>, <code>firstboot.sh</code>,
    <code>nodeconf.php</code> et <code>callback.php</code> sans authentification.
    Toute autre IP reçoit un <code>403</code>. Pour debug depuis ton domicile/bureau,
    ajoute ton IP publique. Pour les VMs, ajoute l'IP de sortie WAN de l'IPFire.
  </div>

  <form class="add-ip-form" method="post">
    <input type="hidden" name="action" value="wl_add">
    <input name="ip" placeholder="213.186.x.y" required pattern="[0-9.:a-fA-F]+">
    <input name="label" placeholder="fr1 WAN, home, office...">
    <button type="submit">+ Ajouter</button>
  </form>

  <?php if (!$whitelist): ?>
    <div class="empty">Aucune IP whitelistée. <strong>Aucun appel /pi/ ne passera tant qu'aucune IP n'est ici.</strong></div>
  <?php else: ?>
    <?php foreach ($whitelist as $w): ?>
      <div class="wl-row <?= $w['enabled'] ? '' : 'disabled' ?>">
        <span class="ip"><?= h($w['ip']) ?></span>
        <span class="label"><?= h($w['label']) ?></span>
        <span><?= $w['enabled']
                 ? '<span class="tag ok">enabled</span>'
                 : '<span class="tag no">disabled</span>' ?></span>
        <span class="last-seen">
          <?= $w['last_seen']
              ? 'last: ' . date('d/m H:i', $w['last_seen'])
              : 'jamais' ?>
        </span>
        <span class="actions">
          <form method="post" style="display:inline">
            <input type="hidden" name="action" value="wl_toggle">
            <input type="hidden" name="id" value="<?= (int)$w['id'] ?>">
            <button class="ghost" type="submit" title="Toggle"><?= $w['enabled'] ? '⏸' : '▶' ?></button>
          </form>
          <form method="post" style="display:inline" onsubmit="return confirm('Supprimer ?')">
            <input type="hidden" name="action" value="wl_delete">
            <input type="hidden" name="id" value="<?= (int)$w['id'] ?>">
            <button class="ghost" type="submit">✕</button>
          </form>
        </span>
      </div>
    <?php endforeach; ?>
  <?php endif; ?>
</div>

<!-- ─── IPs bloquées récemment (proposition d'ajout) ─────── -->
<?php if ($recent_blocked): ?>
<div class="panel">
  <div class="panel-header">
    <h2>IPs bloquées récemment (7 derniers jours)</h2>
  </div>
  <div class="panel-body" style="padding:14px;color:var(--muted);font-size:12px">
    Ces IPs ont essayé d'accéder à <code>/pi/</code> mais ne sont pas whitelistées.
    Si l'une d'elles correspond à ton infra (ESX, VPN), ajoute-la.
    Si c'est du bruit (bots de scan), ignore.
  </div>
  <table>
    <thead><tr>
      <th>IP source</th><th>Hits</th><th>Dernier endpoint</th><th>Vu il y a</th><th></th>
    </tr></thead>
    <tbody>
    <?php foreach ($recent_blocked as $r): ?>
      <tr>
        <td><code><?= h($r['ip']) ?></code></td>
        <td><?= (int)$r['hits'] ?></td>
        <td class="muted"><?= h($r['last_endpoint']) ?></td>
        <td class="muted"><?= date('d/m H:i', $r['last_at']) ?></td>
        <td>
          <form method="post" style="display:inline">
            <input type="hidden" name="action" value="wl_add_from_log">
            <input type="hidden" name="ip" value="<?= h($r['ip']) ?>">
            <button class="ghost" type="submit">+ whitelist</button>
          </form>
        </td>
      </tr>
    <?php endforeach; ?>
    </tbody>
  </table>
</div>
<?php endif; ?>

<!-- ─── IPs autorisées récemment (visibilité) ─────────────── -->
<?php if ($recent_allowed): ?>
<div class="panel">
  <div class="panel-header">
    <h2>Accès autorisés récents (7 derniers jours)</h2>
  </div>
  <table>
    <thead><tr><th>IP</th><th>Hits</th><th>Dernier accès</th></tr></thead>
    <tbody>
    <?php foreach ($recent_allowed as $r): ?>
      <tr>
        <td><code><?= h($r['ip']) ?></code></td>
        <td><?= (int)$r['hits'] ?></td>
        <td class="muted"><?= date('d/m H:i:s', $r['last_at']) ?></td>
      </tr>
    <?php endforeach; ?>
    </tbody>
  </table>
</div>
<?php endif; ?>

<?php require __DIR__ . '/_footer.php'; ?>
