<?php
session_start();
require_once __DIR__ . '/db.php';

// ===== Auth: admin only =====
if (!isset($_SESSION['user']) || (($_SESSION['user']['role'] ?? '') !== 'admin')) {
    header("Location: dashboard.php");
    exit;
}

// ===== CSRF token =====
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(16));
}
$CSRF = $_SESSION['csrf_token'];

// ===== Helpers =====
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

function table_exists(mysqli $conn, string $table): bool {
    $sql = "SELECT COUNT(*) AS c
              FROM INFORMATION_SCHEMA.TABLES
             WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?";
    $stmt = $conn->prepare($sql);
    if (!$stmt) return false;
    $stmt->bind_param('s', $table);
    $stmt->execute();
    $res = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    return ((int)($res['c'] ?? 0)) > 0;
}

function write_audit(mysqli $conn, int $adminId, ?int $memberId, string $action): void {
    if (!table_exists($conn,'audit_logs')) return;
    $stmt = $conn->prepare("INSERT INTO audit_logs (admin_id, member_id, action) VALUES (?, ?, ?)");
    if ($stmt) { $stmt->bind_param("iis", $adminId, $memberId, $action); $stmt->execute(); $stmt->close(); }
}

$adminId = (int)($_SESSION['user']['id'] ?? 0);
$keyName = 'permohonan_ahli_baharu';

$flash_ok  = '';
$flash_err = '';

// Pastikan row wujud – kalau tak, create default
if (table_exists($conn, 'meeting_sequences')) {
    $stmt = $conn->prepare("SELECT id, current_no, note, updated_by, updated_at
                              FROM meeting_sequences
                             WHERE key_name = ?
                             LIMIT 1");
    $stmt->bind_param('s', $keyName);
    $stmt->execute();
    $stmt->bind_result($seqId, $currentNo, $note, $updatedBy, $updatedAt);
    if (!$stmt->fetch()) {
        $stmt->close();
        // create default
        $ins = $conn->prepare("
            INSERT INTO meeting_sequences (key_name, current_no, note, updated_by)
            VALUES (?, 1, 'Bilangan mesyuarat untuk cetak senarai permohonan ahli baharu', ?)
        ");
        $ins->bind_param('si', $keyName, $adminId);
        $ins->execute();
        $ins->close();
        $seqId = $conn->insert_id;
        $currentNo = 1;
        $note = 'Bilangan mesyuarat untuk cetak senarai permohonan ahli baharu';
        $updatedBy = $adminId;
        $updatedAt = date('Y-m-d H:i:s');
    } else {
        $stmt->close();
    }
} else {
    // Kalau table pun belum ada
    $flash_err = 'Jadual meeting_sequences belum wujud. Sila jalankan skrip CREATE TABLE terlebih dahulu.';
    $seqId = 0;
    $currentNo = 1;
    $note = '';
    $updatedBy = null;
    $updatedAt = null;
}

// Handle POST (kemaskini)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $seqId > 0 && empty($flash_err)) {
    $postedToken = $_POST['csrf_token'] ?? '';
    if (!hash_equals($CSRF, $postedToken)) {
        $flash_err = 'CSRF token tidak sah. Sila cuba semula.';
    } else {
        $newNo = (int)($_POST['current_no'] ?? 1);
        if ($newNo < 1) $newNo = 1;

        $newNote = trim((string)($_POST['note'] ?? ''));

        $stmt = $conn->prepare("
            UPDATE meeting_sequences
               SET current_no = ?, note = ?, updated_by = ?, updated_at = NOW()
             WHERE id = ?
        ");
        $stmt->bind_param('isii', $newNo, $newNote, $adminId, $seqId);
        if ($stmt->execute()) {
            $flash_ok   = 'Bilangan mesyuarat berjaya dikemaskini kepada ' . $newNo . '.';
            $currentNo  = $newNo;
            $note       = $newNote;
            $updatedBy  = $adminId;
            $updatedAt  = date('Y-m-d H:i:s');

            write_audit($conn, $adminId, null, "Update meeting_sequences[$keyName] to $newNo");
        } else {
            $flash_err = 'Gagal mengemaskini bilangan mesyuarat.';
        }
        $stmt->close();
    }
}

// Ambil nama admin terakhir update (jika ada)
$updatedByName = '';
if ($updatedBy) {
    $stU = $conn->prepare("SELECT full_name FROM members WHERE id=? LIMIT 1");
    if ($stU) {
        $stU->bind_param('i', $updatedBy);
        $stU->execute();
        $stU->bind_result($updatedByName);
        $stU->fetch();
        $stU->close();
    }
}

// ===== View (guna layout.php) =====
ob_start();
?>
<style>
  :root{
    --border:#e5e7eb; --muted:#6b7280; --text:#0f172a;
    --pri:#2563eb; --pri-ink:#1d4ed8; --ok:#16a34a; --err:#b91c1c;
  }
  *{box-sizing:border-box;}
  body{margin:0;font-family:system-ui,-apple-system,Segoe UI,Roboto;background:#f6f7fb;color:var(--text);}
  .wrap{max-width:900px;margin:0 auto;padding:22px 16px 36px;}
  .page-title{margin:0 0 8px;font-size:clamp(20px,2.2vw,26px);}
  .sub{margin:0 0 18px;font-size:13px;color:var(--muted);}
  .card{background:#fff;border-radius:16px;border:1px solid rgba(0,0,0,.06);box-shadow:0 8px 24px rgba(15,23,42,.06);padding:18px 18px 20px;}
  .field{margin-bottom:14px;}
  .field label{display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:#111827;}
  .field small{display:block;font-size:11.5px;color:var(--muted);margin-top:4px;}
  .input{width:100%;padding:9px 11px;border-radius:10px;border:1px solid var(--border);font-size:14px;}
  .input[readonly]{background:#f9fafb;color:#6b7280;}
  .textarea{width:100%;min-height:70px;padding:9px 11px;border-radius:10px;border:1px solid var(--border);font-size:14px;resize:vertical;}
  .actions{display:flex;gap:10px;align-items:center;margin-top:4px;}
  .btn{padding:9px 14px;border-radius:999px;border:1px solid transparent;font-size:14px;font-weight:600;cursor:pointer;}
  .btn.primary{background:var(--pri);border-color:var(--pri);color:#fff;}
  .btn.primary:hover{background:var(--pri-ink);}
  .btn.ghost{background:#fff;border-color:var(--border);color:#111827;}
  .flash{padding:9px 11px;border-radius:10px;margin-bottom:12px;font-size:13px;border:1px solid transparent;}
  .flash.ok{background:#ecfdf5;border-color:#bbf7d0;color:#166534;}
  .flash.err{background:#fef2f2;border-color:#fecaca;color:#b91c1c;}
  .meta{font-size:12px;color:var(--muted);margin-top:6px;}
</style>

<div class="wrap">
  <h2 class="page-title">Tetapan Bilangan Mesyuarat</h2>
  <p class="sub">
    Nombor ini akan digunakan sebagai <strong>Bil. Mesyuarat</strong> pada cetakan
    <em>Senarai Permohonan Ahli Baharu</em> di Dashboard. Selepas cetakan, sistem akan auto-increment
    nombor ini untuk mesyuarat seterusnya.
  </p>

  <?php if ($flash_ok): ?><div class="flash ok"><?= h($flash_ok) ?></div><?php endif; ?>
  <?php if ($flash_err): ?><div class="flash err"><?= h($flash_err) ?></div><?php endif; ?>

  <div class="card">
    <?php if (!$seqId): ?>
      <p style="font-size:13px;color:var(--err);margin:0;">
        Konfigurasi tidak tersedia kerana jadual <code>meeting_sequences</code> tiada.
        Sila pastikan jadual tersebut telah dicipta di dalam pangkalan data.
      </p>
    <?php else: ?>
      <form method="post">
        <input type="hidden" name="csrf_token" value="<?= h($CSRF) ?>">

        <div class="field">
          <label for="current_no">Bilangan mesyuarat semasa</label>
          <input
            class="input"
            type="number"
            id="current_no"
            name="current_no"
            min="1"
            value="<?= h($currentNo) ?>"
            required
          >
          <small>
            Nilai ini akan digunakan untuk cetakan <strong>seterusnya</strong>.
            Selepas cetakan berjaya dijana, sistem akan menaikkan nombor ini secara automatik (+1).
          </small>
        </div>

        <div class="field">
          <label for="note">Catatan (optional)</label>
          <textarea
            class="textarea"
            id="note"
            name="note"
            placeholder="Contoh: Selaras dengan Bil. Mesyuarat KPPRS 3/2025"
          ><?= h($note ?? '') ?></textarea>
          <small>Boleh digunakan sebagai rujukan dalaman untuk admin (tidak dipaparkan di cetakan).</small>
        </div>

        <div class="actions">
          <button class="btn primary" type="submit">Simpan Tetapan</button>
          <a class="btn ghost" href="dashboard.php">Kembali ke Dashboard</a>
        </div>

        <div class="meta">
          Key: <code><?= h($keyName) ?></code><br>
          Bilangan semasa dalam DB: <strong><?= h($currentNo) ?></strong><br>
          <?php if ($updatedAt): ?>
            Dikemaskini kali terakhir pada: <?= h(date('d M Y, H:i', strtotime($updatedAt))) ?>
            <?php if ($updatedByName): ?>
              oleh <strong><?= h($updatedByName) ?></strong>
            <?php endif; ?>
          <?php endif; ?>
        </div>
      </form>
    <?php endif; ?>
  </div>
</div>

<?php
$content = ob_get_clean();
include __DIR__ . '/layout.php';
