<?php
session_start();

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

function load_tenants(){
  if(!file_exists(TENANTS_FILE)) return [];
  return json_decode(file_get_contents(TENANTS_FILE), true) ?: [];
}
function save_tenants($data){
  @mkdir(dirname(TENANTS_FILE),0777,true);
  file_put_contents(TENANTS_FILE, json_encode($data, JSON_PRETTY_PRINT));
}

$tenants = load_tenants();
$host    = $_POST['host'] ?? '';
if(isset($_POST['save'])){
  $tenants[$host] = [
    'expires_at'=>$_POST['expires_at'],
    'status'=>$_POST['status'],
    'note'=>$_POST['note'] ?? ''
  ];
  save_tenants($tenants);
  $msg = "Data tenant $host tersimpan!";
}
?>
<!DOCTYPE html>
<html lang="id">
<head><meta charset="UTF-8"><title>Admin Masa Aktif</title></head>
<body>
<h2>Admin Masa Aktif</h2>
<?php if(!empty($msg)) echo "<p><b>$msg</b></p>"; ?>
<form method="post">
  <p>Host/Subdomain: <input name="host" required value="<?= htmlspecialchars($host) ?>"></p>
  <p>Expired sampai: <input type="date" name="expires_at" required></p>
  <p>Status:
    <select name="status">
      <option value="active">Active</option>
      <option value="inactive">Inactive</option>
    </select>
  </p>
  <p>Note: <input name="note"></p>
  <p><button type="submit" name="save">Simpan</button></p>
</form>

<h3>Daftar Tenant</h3>
<ul>
<?php foreach($tenants as $h=>$t): ?>
  <li><?= htmlspecialchars($h) ?> - <?= htmlspecialchars($t['expires_at']) ?> (<?= htmlspecialchars($t['status']) ?>)</li>
<?php endforeach; ?>
</ul>
</body>
</html>
