<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';

$db = get_db(); // pastikan koneksi database
// Ambil data kontak (hanya satu baris)
$stmt = $db->query("SELECT * FROM contacts ORDER BY id DESC LIMIT 1");
$kontak = $stmt->fetch(PDO::FETCH_ASSOC);

// Proses simpan/update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $alamat = trim($_POST['alamat'] ?? '');
    $telepon = trim($_POST['telepon'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $maps = trim($_POST['maps'] ?? '');
    if ($kontak) {
        // Update
        $stmt = $db->prepare("UPDATE contacts SET alamat=?, telepon=?, email=?, maps=?, updated_at=CURRENT_TIMESTAMP WHERE id=?");
        $stmt->execute([$alamat, $telepon, $email, $maps, $kontak['id']]);
    } else {
        // Insert
        $stmt = $db->prepare("INSERT INTO contacts (alamat, telepon, email, maps) VALUES (?, ?, ?, ?)");
        $stmt->execute([$alamat, $telepon, $email, $maps]);
    }
    header('Location: kontak.php?sukses=1');
    exit;
}
// Ambil ulang data kontak setelah update/insert
$stmt = $db->query("SELECT * FROM contacts ORDER BY id DESC LIMIT 1");
$kontak = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<?php include '_header.php'; ?>
<div class="container py-8">
  <h2 class="mb-8">Kontak Sekolah</h2>
  <?php if (!empty($_GET['sukses'])): ?>
    <div class="alert alert-success">Data kontak berhasil disimpan.</div>
  <?php endif; ?>
  <form method="post" class="card p-4 shadow-sm" style="max-width:800px;">
    <div class="mb-3">
      <label class="form-label">Alamat</label>
      <textarea name="alamat" class="form-control" required rows="3"><?php echo htmlspecialchars($kontak['alamat'] ?? '', ENT_QUOTES, 'UTF-8'); ?></textarea>
    </div>
    <div class="mb-3">
      <label class="form-label">Telepon</label>
      <input type="text" name="telepon" class="form-control" value="<?php echo htmlspecialchars($kontak['telepon'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
    </div>
    <div class="mb-3">
      <label class="form-label">Email</label>
      <input type="email" name="email" class="form-control" value="<?php echo htmlspecialchars($kontak['email'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
    </div>
    <div class="mb-3">
      <label class="form-label">Embed Google Maps (opsional)</label>
      <textarea name="maps" class="form-control" rows="2" placeholder="<iframe ...>"><?php echo htmlspecialchars($kontak['maps'] ?? '', ENT_QUOTES, 'UTF-8'); ?></textarea>
      <small class="text-muted">Paste kode embed iframe Google Maps di sini jika ada.</small>
    </div>
    <button type="submit" class="btn btn-primary">Simpan</button>
  </form>
</div>
<?php include '_footer.php'; ?>
