<?php
// settings-job-titles.php
session_start();
require_once __DIR__ . '/db.php';

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

function out($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

$action = $_GET['action'] ?? '';
$id     = isset($_GET['id']) ? (int)$_GET['id'] : 0;

/* ========== CREATE ========== */
if ($action === 'create' && $_SERVER['REQUEST_METHOD'] === 'POST') {
  $name   = trim($_POST['name'] ?? '');
  $active = isset($_POST['active']) ? 1 : 0;

  if ($name === '') {
    header('Location: settings-job-titles.php?error=' . urlencode('Nama jawatan wajib diisi'));
    exit;
  }

  if (!$stmt = $conn->prepare("SELECT id FROM job_titles WHERE name=?")) {
    header('Location: settings-job-titles.php?error=' . urlencode('Ralat DB (SELECT): '.$conn->error)); exit;
  }
  $stmt->bind_param('s', $name);
  $stmt->execute(); $stmt->store_result();
  if ($stmt->num_rows > 0) { $stmt->close(); header('Location: settings-job-titles.php?error=' . urlencode('Nama jawatan sudah wujud.')); exit; }
  $stmt->close();

  if (!$stmt = $conn->prepare("INSERT INTO job_titles (name, active) VALUES (?, ?)")) {
    header('Location: settings-job-titles.php?error=' . urlencode('Ralat DB (INSERT): '.$conn->error)); exit;
  }
  $stmt->bind_param('si', $name, $active);
  $ok = $stmt->execute(); $stmt->close();

  $q = $ok ? 'success=' . urlencode('Jawatan berjaya ditambah.')
           : 'error='   . urlencode('Gagal tambah jawatan: '.$conn->error);
  header('Location: settings-job-titles.php?' . $q); exit;
}

/* ========== UPDATE (papar form) ========== */
$editRow = null;
if ($action === 'edit' && $id) {
  if (!$stmt = $conn->prepare("SELECT id, name, active FROM job_titles WHERE id=?")) {
    header('Location: settings-job-titles.php?error=' . urlencode('Ralat DB (SELECT): '.$conn->error)); exit;
  }
  $stmt->bind_param('i', $id);
  $stmt->execute();
  $res = $stmt->get_result();
  $editRow = $res->fetch_assoc();
  $stmt->close();

  if (!$editRow) { header('Location: settings-job-titles.php?error=' . urlencode('Rekod tidak dijumpai')); exit; }
}

/* ========== UPDATE (submit) ========== */
if ($action === 'update' && $_SERVER['REQUEST_METHOD'] === 'POST') {
  $id2    = (int)($_POST['id'] ?? 0);
  $name   = trim($_POST['name'] ?? '');
  $active = isset($_POST['active']) ? 1 : 0;

  if (!$id2 || $name === '') {
    header('Location: settings-job-titles.php?error=' . urlencode('Data tidak lengkap')); exit;
  }

  if (!$stmt = $conn->prepare("SELECT id FROM job_titles WHERE name=? AND id<>?")) {
    header('Location: settings-job-titles.php?error=' . urlencode('Ralat DB (SELECT): '.$conn->error)); exit;
  }
  $stmt->bind_param('si', $name, $id2);
  $stmt->execute(); $stmt->store_result();
  if ($stmt->num_rows > 0) { $stmt->close(); header('Location: settings-job-titles.php?error=' . urlencode('Nama jawatan sudah wujud.')); exit; }
  $stmt->close();

  if (!$stmt = $conn->prepare("UPDATE job_titles SET name=?, active=?, updated_at=NOW() WHERE id=?")) {
    header('Location: settings-job-titles.php?error=' . urlencode('Ralat DB (UPDATE): '.$conn->error)); exit;
  }
  $stmt->bind_param('sii', $name, $active, $id2);
  $ok = $stmt->execute(); $stmt->close();

  $q = $ok ? 'success=' . urlencode('Jawatan dikemas kini.')
           : 'error='   . urlencode('Gagal kemas kini: '.$conn->error);
  header('Location: settings-job-titles.php?' . $q); exit;
}

/* ========== TOGGLE ========== */
if ($action === 'toggle' && $id) {
  if (!$stmt = $conn->prepare("SELECT active FROM job_titles WHERE id=?")) {
    header('Location: settings-job-titles.php?error=' . urlencode('Ralat DB (SELECT): '.$conn->error)); exit;
  }
  $stmt->bind_param('i',$id);
  $stmt->execute();
  $stmt->bind_result($activeNow);
  $okFetch = $stmt->fetch();
  $stmt->close();

  if (!$okFetch) { header('Location: settings-job-titles.php?error=' . urlencode('Rekod tidak dijumpai')); exit; }

  $new = $activeNow ? 0 : 1;

  if (!$stmt = $conn->prepare("UPDATE job_titles SET active=?, updated_at=NOW() WHERE id=?")) {
    header('Location: settings-job-titles.php?error=' . urlencode('Ralat DB (UPDATE): '.$conn->error)); exit;
  }
  $stmt->bind_param('ii', $new, $id);
  $ok = $stmt->execute(); $stmt->close();

  $q = $ok ? 'success=' . urlencode('Status dikemas kini.')
           : 'error='   . urlencode('Gagal kemas kini status: '.$conn->error);
  header('Location: settings-job-titles.php?' . $q); exit;
}

/* ========== DELETE (sekatan jika digunakan) ========== */
if ($action === 'delete' && $id) {
  $inUse = 0;
  foreach (['pending_exco','pending_ajk','members'] as $tbl) {
    $sql  = "SELECT COUNT(*) FROM `$tbl` WHERE job_title = (SELECT name FROM job_titles WHERE id=?)";
    if (!$stmt = $conn->prepare($sql)) {
      header('Location: settings-job-titles.php?error=' . urlencode('Ralat DB (CHECK USE): '.$conn->error)); exit;
    }
    $stmt->bind_param('i',$id);
    $stmt->execute();
    $stmt->bind_result($cnt);
    $stmt->fetch();
    $stmt->close();
    $inUse += (int)$cnt;
  }

  if ($inUse > 0) {
    header('Location: settings-job-titles.php?error=' . urlencode('Tidak boleh hapus: jawatan sedang digunakan pada rekod pendaftaran/ahli.'));
    exit;
  }

  if (!$stmt = $conn->prepare("DELETE FROM job_titles WHERE id=?")) {
    header('Location: settings-job-titles.php?error=' . urlencode('Ralat DB (DELETE): '.$conn->error)); exit;
  }
  $stmt->bind_param('i',$id);
  $ok = $stmt->execute(); $stmt->close();

  $q = $ok ? 'success=' . urlencode('Jawatan dipadam.')
           : 'error='   . urlencode('Gagal padam: '.$conn->error);
  header('Location: settings-job-titles.php?' . $q); exit;
}

/* ========== LIST ========== */
$rows = [];
$res = $conn->query("SELECT id, name, active, created_at, updated_at FROM job_titles ORDER BY active DESC, name ASC");
while($r = $res->fetch_assoc()) $rows[] = $r;

/* ========== Flash message (GET) ========== */
$flash_success = isset($_GET['success']) ? trim($_GET['success']) : '';
$flash_error   = isset($_GET['error'])   ? trim($_GET['error'])   : '';

/* ========== LAYOUT HOOKS ========== */
$page_title = 'Settings – Job Titles';
include __DIR__ . '/layout.php'; // header/topbar/sidebar
?>

<style>
  /* ——— base layout ——— */
  .sj-wrap{ margin-left:240px; padding:24px; min-height:calc(100vh - 70px); }
  @media (max-width: 992px){ .sj-wrap{ margin-left:0; } }

  .sj-header{ display:flex; align-items:center; justify-content:space-between; gap:12px; margin-bottom:16px; }
  .sj-title{ font-size:28px; font-weight:700; }
  .sj-bc{ list-style:none; display:flex; gap:8px; padding:0; margin:6px 0 0 0; font-size:14px; }
  .sj-bc li{ color:#6b7280; }
  .sj-bc a{ color:#2563eb; text-decoration:none; }
  .sj-bc a:hover{ text-decoration:underline; }

  .sj-grid{ display:grid; grid-template-columns: 1fr 1.5fr; gap:16px; }
  @media (max-width: 1200px){ .sj-grid{ grid-template-columns:1fr; } }

  .sj-card{ background:#fff; border:1px solid #e5e7eb; border-radius:12px; box-shadow:0 1px 2px rgba(0,0,0,.04); }
  .sj-card-hd{ padding:12px 16px; border-bottom:1px solid #e5e7eb; font-weight:600; }
  .sj-card-bd{ padding:16px; }

  .sj-form .sj-row{ margin-bottom:12px; }
  .sj-label{ display:block; font-weight:600; margin-bottom:6px; }
  .sj-input{ width:100%; padding:10px 12px; border:1px solid #cbd5e1; border-radius:8px; font-size:14px; }
  .sj-check{ display:flex; align-items:center; gap:8px; margin:6px 0 14px; }

  .sj-actions{ display:flex; gap:8px; flex-wrap:wrap; }
  .sj-btn{ border:1px solid transparent; background:#111827; color:#fff; padding:9px 14px; border-radius:10px; font-weight:600; cursor:pointer; text-decoration:none; }
  .sj-btn:hover{ opacity:.95; }
  .sj-btn.outline{ background:#fff; color:#111827; border-color:#d1d5db; }
  .sj-btn.warn{ background:#f59e0b; border-color:#f59e0b; }
  .sj-btn.danger{ background:#ef4444; border-color:#ef4444; }

  .sj-table-wrap{ overflow:auto; }
  table.sj-table{ width:100%; border-collapse:separate; border-spacing:0; }
  .sj-table th, .sj-table td{ text-align:left; padding:10px 12px; font-size:14px; white-space:nowrap; }
  .sj-table thead th{ background:#111827; color:#fff; position:sticky; top:0; }
  .sj-table tbody tr{ border-bottom:1px solid #e5e7eb; }
  .sj-badge{ padding:3px 8px; border-radius:999px; font-size:12px; font-weight:700; display:inline-block; }
  .sj-badge.green{ background:#e6fbe8; color:#166534; border:1px solid #bbf7d0; }
  .sj-badge.gray{ background:#f3f4f6; color:#374151; border:1px solid #e5e7eb; }

  /* ——— Flash style (align center) ——— */
  .flash{
    position:relative;
    display:flex; align-items:flex-start; gap:10px;
    padding:12px 40px 12px 12px; border-radius:12px; margin:0 0 14px;
    border:1px solid;
  }
  .flash.success{ background:#ecfdf5; border-color:#a7f3d0; color:#065f46; }
  .flash.error  { background:#fef2f2; border-color:#fecdd3; color:#7f1d1d; }

  /* center text block */
  .flash .msg{ flex:1; text-align:center; }

  /* close button fixed at top-right */
  .flash .close{
    position:absolute; top:8px; right:10px;
    border:0; background:transparent; font-size:18px; cursor:pointer; line-height:1;
  }
</style>

<div class="sj-wrap">
  <div class="sj-header">
    <div>
      <div class="sj-title">Settings</div>
      <ul class="sj-bc">
        <li><a href="dashboard.php">Dashboard</a></li>
        <li>›</li>
        <li>Settings</li>
        <li>›</li>
        <li><strong>Job Titles</strong></li>
      </ul>
    </div>
  </div>

  <?php if ($flash_success): ?>
    <div class="flash success" id="flashBox" role="alert" aria-live="polite">
      <div class="msg"><strong>Success:</strong> <span><?= out($flash_success) ?></span></div>
      <button class="close" aria-label="Close" onclick="this.parentElement.remove()">×</button>
    </div>
  <?php elseif ($flash_error): ?>
    <div class="flash error" id="flashBox" role="alert" aria-live="assertive">
      <div class="msg"><strong>Error:</strong> <span><?= out($flash_error) ?></span></div>
      <button class="close" aria-label="Close" onclick="this.parentElement.remove()">×</button>
    </div>
  <?php endif; ?>

  <div class="sj-grid">
    <!-- Kiri: Form -->
    <div class="sj-card">
      <div class="sj-card-hd"><?= $editRow ? 'Kemas Kini Jawatan' : 'Tambah Jawatan' ?></div>
      <div class="sj-card-bd">
        <form class="sj-form" method="post" action="settings-job-titles.php?action=<?= $editRow ? 'update' : 'create' ?>">
          <?php if ($editRow): ?>
            <input type="hidden" name="id" value="<?= (int)$editRow['id'] ?>">
          <?php endif; ?>

          <div class="sj-row">
            <label class="sj-label">Nama Jawatan</label>
            <input name="name" class="sj-input" placeholder="cth: Jurutera" required
                   value="<?= $editRow ? out($editRow['name']) : '' ?>">
          </div>

          <div class="sj-check">
            <input type="checkbox" id="active" name="active" <?= $editRow ? ($editRow['active']?'checked':'') : 'checked' ?>>
            <label for="active">Aktif</label>
          </div>

          <div class="sj-actions">
            <button class="sj-btn"><?= $editRow ? 'Kemas Kini' : 'Simpan' ?></button>
            <?php if ($editRow): ?>
              <a class="sj-btn outline" href="settings-job-titles.php">Batal</a>
            <?php endif; ?>
          </div>
        </form>
      </div>
    </div>

    <!-- Kanan: Table -->
    <div class="sj-card">
      <div class="sj-card-hd">Senarai Jawatan</div>
      <div class="sj-card-bd">
        <div class="sj-table-wrap">
          <table class="sj-table">
            <thead>
              <tr>
                <th style="width:60px">#</th>
                <th>Nama</th>
                <th>Status</th>
                <th>Dicipta</th>
                <th>Kemaskini</th>
                <th style="width:240px">Tindakan</th>
              </tr>
            </thead>
            <tbody>
            <?php if (!$rows): ?>
              <tr><td colspan="6">Tiada data</td></tr>
            <?php else: $i=1; foreach($rows as $r): ?>
              <tr>
                <td><?= $i++ ?></td>
                <td><?= out($r['name']) ?></td>
                <td><?= $r['active'] ? '<span class="sj-badge green">Aktif</span>' : '<span class="sj-badge gray">Tidak Aktif</span>' ?></td>
                <td><small><?= out($r['created_at']) ?></small></td>
                <td><small><?= out($r['updated_at'] ?? '-') ?></small></td>
                <td class="sj-actions">
                  <a class="sj-btn outline" href="settings-job-titles.php?action=edit&id=<?= (int)$r['id'] ?>">Edit</a>
                  <a class="sj-btn warn" href="settings-job-titles.php?action=toggle&id=<?= (int)$r['id'] ?>">
                    <?= $r['active'] ? 'Nyahaktif' : 'Aktifkan' ?>
                  </a>
                  <a class="sj-btn danger"
                     href="settings-job-titles.php?action=delete&id=<?= (int)$r['id'] ?>"
                     onclick="return confirm('Padam jawatan ini? Pastikan tidak digunakan pada sebarang rekod.');">
                     Padam
                  </a>
                </td>
              </tr>
            <?php endforeach; endif; ?>
            </tbody>
          </table>
        </div>
        <div style="margin-top:10px; color:#6b7280; font-size:12px">
          “Padam” disekat jika jawatan sedang digunakan.
        </div>
      </div>
    </div>
  </div><!-- /.sj-grid -->
</div><!-- /.sj-wrap -->

<script>
(function(){
  // Auto-hide flash after 4s + fade, dan scroll ke atas jika wujud
  const fb = document.getElementById('flashBox');
  if (fb) {
    window.scrollTo({top:0, behavior:'smooth'});
    setTimeout(()=>{ if(fb){ fb.style.transition='opacity .4s'; fb.style.opacity='0'; setTimeout(()=>fb.remove(), 400); } }, 4000);
  }
})();
</script>

<?php include __DIR__ . '/footer.php'; ?>
