<?php
session_start();

const TENANTS_FILE = __DIR__ . '/storage/tenants.json';

// ====== AUTH SEDERHANA ======
const ADMIN_USER = 'erwan';
const ADMIN_PASS = 'rahasia-kuat-123'; // GANTI!

if(isset($_POST['logout'])){ unset($_SESSION['admin_ok']); header('Location: ?'); exit; }

if(empty($_SESSION['admin_ok'])){
  if(isset($_POST['u'], $_POST['p']) && $_POST['u']===ADMIN_USER && $_POST['p']===ADMIN_PASS){
    $_SESSION['admin_ok'] = true;
    header('Location: ?'); exit;
  }
  // Form login admin
  ?>
  <!doctype html><html lang="id"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Admin Masa Aktif</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;800&display=swap" rel="stylesheet">
  <style>
    body{font-family:'Nunito',sans-serif;background:linear-gradient(135deg,#29ABE2,#4ECDC4);min-height:100vh;display:grid;place-items:center;margin:0;padding:18px;color:#0f172a}
    .card{background:rgba(255,255,255,.9);border-radius:16px;box-shadow:0 30px 80px rgba(2,6,23,.25);max-width:420px;width:100%;padding:26px}
    h1{margin:0 0 12px}
    .field{margin:10px 0}
    input{width:100%;padding:12px;border-radius:10px;border:1px solid #cbd5e1}
    button{margin-top:10px;width:100%;padding:12px;border:none;border-radius:12px;background:linear-gradient(90deg,#29ABE2,#4ECDC4);color:#fff;font-weight:800;cursor:pointer}
  </style></head><body>
  <div class="card">
    <h1>Login Admin</h1>
    <form method="post">
      <div class="field"><input name="u" placeholder="Username" required></div>
      <div class="field"><input name="p" type="password" placeholder="Password" required></div>
      <button type="submit">Masuk</button>
    </form>
  </div>
  </body></html>
  <?php
  exit;
}

// ====== UTIL ======
function load_tenants(){
  if(!file_exists(TENANTS_FILE)){
    @mkdir(dirname(TENANTS_FILE), 0777, true);
    file_put_contents(TENANTS_FILE, json_encode(new stdClass(), JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES));
  }
  $data = json_decode(@file_get_contents(TENANTS_FILE), true);
  return is_array($data) ? $data : [];
}
function save_tenants($data){
  @mkdir(dirname(TENANTS_FILE), 0777, true);
  file_put_contents(TENANTS_FILE, json_encode($data, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES));
}
function days_left($date){
  $now = new DateTime('today');
  $exp = DateTime::createFromFormat('Y-m-d', substr($date,0,10)) ?: new DateTime($date);
  return (int)$now->diff($exp)->format('%r%a');
}

// ====== PROSES SIMPAN ======
$tenants = load_tenants();

if(isset($_POST['save'])){
  $domain = strtolower(trim($_POST['domain']));
  if($domain==='') $domain = 'default';

  $tenants[$domain] = [
    'expires_at'  => $_POST['expires_at'] ?: date('Y-m-d', strtotime('+30 days')),
    'status'      => ($_POST['status'] ?? 'active') === 'active' ? 'active' : 'inactive',
    'auto_extend' => [
      'enabled'        => isset($_POST['auto_enabled']),
      'days'           => max(1, (int)($_POST['auto_days'] ?? 30)),
      'threshold_days' => max(0, (int)($_POST['auto_threshold'] ?? 3)),
    ],
    'note'        => $_POST['note'] ?? ''
  ];
  save_tenants($tenants);
  $msg = 'Tersimpan untuk '.$domain;
}

if(isset($_POST['delete'])){
  $domain = $_POST['domain_del'] ?? '';
  if($domain && isset($tenants[$domain])){
    unset($tenants[$domain]); save_tenants($tenants); $msg = 'Dihapus: '.$domain;
  }
}

// ====== TAMPIL ======
$hostNow = $_SERVER['HTTP_HOST'] ?? 'default';
$tenantNow = $tenants[strtolower($hostNow)] ?? ($tenants['default'] ?? []);
?>
<!doctype html><html lang="id"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Panel Admin Masa Aktif</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;800&display=swap" rel="stylesheet">
<style>
  body{font-family:'Nunito',sans-serif;background:linear-gradient(135deg,#29ABE2,#4ECDC4);min-height:100vh;margin:0;padding:18px;color:#0f172a}
  .container{max-width:1000px;margin:0 auto}
  .topbar{display:flex;gap:12px;justify-content:space-between;align-items:center;color:#fff}
  .card{background:rgba(255,255,255,.95);border-radius:16px;box-shadow:0 30px 80px rgba(2,6,23,.25);padding:18px;margin-top:14px}
  h2{margin:0 0 10px}
  .grid{display:grid;grid-template-columns:1fr;gap:14px}
  @media(min-width:900px){ .grid{grid-template-columns:1.2fr .8fr} }
  input,select,textarea{width:100%;padding:10px;border:1px solid #cbd5e1;border-radius:10px}
  label{font-weight:800;margin:6px 0 4px;display:block}
  button{appearance:none;border:none;border-radius:12px;background:linear-gradient(90deg,#29ABE2,#4ECDC4);color:#fff;font-weight:800;padding:12px 16px;cursor:pointer}
  .table{width:100%;border-collapse:collapse}
  .table th,.table td{border-bottom:1px solid #e2e8f0;padding:8px 6px;text-align:left}
  .pill{display:inline-block;padding:4px 8px;border-radius:999px;font-size:12px}
  .pill-ok{background:#dcfce7;color:#166534}
  .pill-bad{background:#fee2e2;color:#991b1b}
  .pill-warn{background:#fef3c7;color:#92400e}
  .msg{margin:8px 0 0;color:#065f46;font-weight:800}
</style>
</head><body>
<div class="container">
  <div class="topbar">
    <h1>Panel Admin — Masa Aktif</h1>
    <form method="post"><button name="logout">Logout</button></form>
  </div>

  <?php if(!empty($msg)): ?><div class="card"><div class="msg"><?= htmlspecialchars($msg,ENT_QUOTES,'UTF-8') ?></div></div><?php endif; ?>

  <div class="grid">
    <div class="card">
      <h2>Setel / Perpanjang</h2>
      <form method="post">
        <label>Domain/Subdomain</label>
        <input name="domain" placeholder="contoh: mikhmon1.erwanhost.com (atau kosongkan = default)" value="<?= htmlspecialchars($_SERVER['HTTP_HOST'] ?? '',ENT_QUOTES,'UTF-8') ?>">

        <label>Tanggal Expired (YYYY-MM-DD)</label>
        <input type="date" name="expires_at" value="<?= htmlspecialchars($tenantNow['expires_at'] ?? '',ENT_QUOTES,'UTF-8') ?>">

        <label>Status</label>
        <select name="status">
          <?php $st = $tenantNow['status'] ?? 'active'; ?>
          <option value="active" <?= $st==='active'?'selected':'' ?>>Active</option>
          <option value="inactive" <?= $st!=='active'?'selected':'' ?>>Inactive</option>
        </select>

        <label><input type="checkbox" name="auto_enabled" <?= !empty(($tenantNow['auto_extend']['enabled']??false))?'checked':''; ?>> Aktifkan Perpanjangan Otomatis</label>

        <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:8px">
          <div>
            <label>Tambah (hari)</label>
            <input type="number" name="auto_days" min="1" value="<?= (int)($tenantNow['auto_extend']['days'] ?? 30) ?>">
          </div>
          <div>
            <label>Threshold sisa (hari)</label>
            <input type="number" name="auto_threshold" min="0" value="<?= (int)($tenantNow['auto_extend']['threshold_days'] ?? 3) ?>">
          </div>
          <div>
            <label>Catatan</label>
            <input name="note" value="<?= htmlspecialchars($tenantNow['note'] ?? '',ENT_QUOTES,'UTF-8') ?>">
          </div>
        </div>
        <div style="margin-top:10px;display:flex;gap:8px;flex-wrap:wrap">
          <button name="save" value="1">Simpan</button>
          <a href="./" style="padding:12px 16px;border-radius:12px;background:#e2e8f0;text-decoration:none;color:#0f172a;font-weight:800">Kembali ke Login</a>
        </div>
      </form>
    </div>

    <div class="card">
      <h2>Daftar Tenant</h2>
      <table class="table">
        <thead><tr><th>Domain</th><th>Expired</th><th>Sisa</th><th>Status</th><th>Aksi</th></tr></thead>
        <tbody>
          <?php
          if(!$tenants) echo '<tr><td colspan="5">Belum ada data</td></tr>';
          foreach($tenants as $domain=>$t){
            $d = $t['expires_at'] ?? date('Y-m-d');
            $left = days_left($d);
            $pill = $left<0?'pill-bad':($left<=7?'pill-warn':'pill-ok');
            $txt  = $left<0?($left.' hari'):($left.' hari');
            $status = ($t['status'] ?? 'active')==='active' ? 'Active' : 'Inactive';
            echo '<tr>';
            echo '<td>'.htmlspecialchars($domain,ENT_QUOTES,'UTF-8').'</td>';
            echo '<td>'.htmlspecialchars($d,ENT_QUOTES,'UTF-8').'</td>';
            echo '<td><span class="pill '.$pill.'">'.$txt.'</span></td>';
            echo '<td>'.$status.'</td>';
            echo '<td>
                    <form method="post" onsubmit="return confirm(\'Hapus tenant ini?\')">
                      <input type="hidden" name="domain_del" value="'.htmlspecialchars($domain,ENT_QUOTES,'UTF-8').'">
                      <button name="delete" value="1" style="background:#ef4444">Hapus</button>
                    </form>
                  </td>';
            echo '</tr>';
          }
          ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
</body></html>
