<?php
// simulador_epa.php — Genesis SCI
header('Content-Type: text/html; charset=UTF-8');

// Pasta base do Genesis (este arquivo está em /var/www/html/genesis/)
$baseDir = __DIR__;
$inpDir  = $baseDir . "/epanet/inp";
$outDir  = $baseDir . "/epanet/resultados";

// Caminho do executável epanet (confira com: command -v epanet)
$epanetBin = "/usr/bin/epanet";

// Garante pastas
if (!is_dir($inpDir)) { die("Pasta INP não existe: $inpDir"); }
if (!is_dir($outDir)) { die("Pasta resultados não existe: $outDir"); }

function listInpFiles($dir) {
  $files = glob($dir . "/*.inp");
  $names = [];
  foreach ($files as $f) $names[] = basename($f);
  sort($names);
  return $names;
}

function safePickFromDir($dir, $filename) {
  // Aceita só nomes simples e existentes na pasta
  if (!preg_match('/^[a-zA-Z0-9._-]+\.inp$/', $filename)) return null;
  $full = $dir . "/" . $filename;
  if (!is_file($full)) return null;
  return $full;
}

$inpFiles = listInpFiles($inpDir);

$selected = $_POST["inp"] ?? ($inpFiles[0] ?? "");
$action   = $_POST["action"] ?? "";

$msg = "";
$rptPath = "";

$epanetExists = is_file($epanetBin) && is_executable($epanetBin);

if ($action === "run") {
  if (!$epanetExists) {
    $msg = "⚠ EPANET não encontrado em <code>".htmlspecialchars($epanetBin)."</code>.";
  } else {
    $inpFull = safePickFromDir($inpDir, $selected);
    if (!$inpFull) {
      $msg = "Arquivo .inp inválido ou não encontrado.";
    } else {
      $rptName = preg_replace('/\.inp$/i', '.rpt', basename($inpFull));
      $rptFull = $outDir . "/" . $rptName;

      $binName = preg_replace('/\.inp$/i', '.bin', basename($inpFull));
      $binFull = $outDir . "/" . $binName;

      // IMPORTANTE: roda "dentro" da pasta de saída, para resolver caminhos relativos do INP
      // epanet input.inp output.rpt output.bin
      $cmd = "cd " . escapeshellarg($outDir) . " && "
           . escapeshellarg($epanetBin) . " "
           . escapeshellarg($inpFull) . " "
           . escapeshellarg($rptFull) . " "
           . escapeshellarg($binFull) . " 2>&1";

      $output = shell_exec($cmd);

      if (is_file($rptFull) && filesize($rptFull) > 0) {
        $msg = "✅ Simulação executada: <b>".htmlspecialchars($rptName)."</b>"
             . (is_file($binFull) ? " (BIN OK)" : " (⚠ BIN não gerado)");
        $rptPath = $rptFull;
      } else {
        $msg = "❌ Falha ao gerar relatório. Saída do comando:<br><pre>"
             . htmlspecialchars($output ?? "(sem saída)")
             . "</pre>";
      }
    }
  }
}

if ($action === "view") {
  $rptName = preg_replace('/\.inp$/i', '.rpt', $selected);
  $rptFull = $outDir . "/" . basename($rptName);
  if (is_file($rptFull)) {
    $rptPath = $rptFull;
  } else {
    $msg = "Relatório não encontrado: " . htmlspecialchars($rptName);
  }
}
?>
<!doctype html>
<html lang="pt-BR">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>EPANET — Genesis SCI</title>
  <style>
    body{font-family:Arial,Helvetica,sans-serif; margin:20px; background:#0b1220; color:#e5e7eb;}
    .card{background:#111827; border:1px solid #1f2937; border-radius:14px; padding:16px; max-width:1100px;}
    select,button{padding:10px 12px; border-radius:10px; border:1px solid #334155; background:#0f172a; color:#e5e7eb;}
    button{cursor:pointer;}
    button[disabled]{opacity:.55; cursor:not-allowed;}
    .row{display:flex; gap:10px; align-items:center; flex-wrap:wrap;}
    .msg{margin-top:12px; padding:10px; border-radius:10px; background:#0f172a; border:1px solid #334155;}
    pre{white-space:pre-wrap; background:#0b1220; padding:12px; border-radius:10px; border:1px solid #334155; max-height:520px; overflow:auto;}
    code{color:#93c5fd;}
    a{color:#60a5fa;}
    .ok{color:#34d399;}
    .warn{color:#fbbf24;}
  </style>
</head>
<body>
  <div class="card">
    <h2>EPANET — Simulação no Servidor (Genesis SCI)</h2>

    <form method="post">
      <div class="row">
        <label for="inp">Modelo (.inp):</label>
        <select name="inp" id="inp">
          <?php foreach ($inpFiles as $f): ?>
            <option value="<?= htmlspecialchars($f) ?>" <?= ($f === $selected ? "selected" : "") ?>>
              <?= htmlspecialchars($f) ?>
            </option>
          <?php endforeach; ?>
        </select>

        <button type="submit" name="action" value="run" <?= (!$epanetExists ? 'disabled title="EPANET não localizado no servidor"' : '') ?>>
          Rodar Simulação
        </button>
        <button type="submit" name="action" value="view">Ver Relatório</button>
      </div>
    </form>

    <?php if ($msg): ?>
      <div class="msg"><?= $msg ?></div>
    <?php endif; ?>

    <div class="msg">
      <b>Pastas:</b><br>
      INP: <code><?= htmlspecialchars($inpDir) ?></code><br>
      Saída (RPT/BIN): <code><?= htmlspecialchars($outDir) ?></code><br>
      EPANET BIN: <code><?= htmlspecialchars($epanetBin) ?></code>
      <?= ($epanetExists ? '<span class="ok"> (OK)</span>' : '<span class="warn"> (não encontrado)</span>') ?>
    </div>

    <?php if ($rptPath): ?>
      <h3 style="margin-top:16px;">Relatório (.RPT)</h3>
      <pre><?php echo htmlspecialchars(@file_get_contents($rptPath) ?: "Não foi possível ler o arquivo RPT."); ?></pre>
    <?php endif; ?>
  </div>
</body>
</html>
