<?php
/**
 * settings-deactivate-reasons.php — Manage list of deactivate reasons
 * Role: admin only
 * Note: assumes table `deactivate_reasons(id, reason_text, active, sort_order, created_at, updated_at)`
 */
session_start();
require_once "db.php";

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

function redirect_ok(string $msg=''){ header("Location: settings-deactivate-reasons.php".($msg?("?success=".urlencode($msg)):"")); exit; }
function redirect_err(string $msg=''){ header("Location: settings-deactivate-reasons.php".($msg?("?error=".urlencode($msg)):"")); exit; }
function post($k,$d=''){ return trim($_POST[$k] ?? $d); }

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

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

/* ---------- Create / Update ---------- */
if ($_SERVER['REQUEST_METHOD']==='POST') {
    $csrf = $_POST['csrf_token'] ?? '';
    if (!hash_equals($CSRF, $csrf)) { http_response_code(400); die('Invalid CSRF token.'); }

    $rid    = (int)($_POST['id'] ?? 0);
    $text   = post('reason_text');
    $active = (int)(post('active','1')==='1'?1:0);
    $sort   = (int)(post('sort_order','0'));

    if ($text==='') redirect_err("Reason text is required.");
    if (mb_strlen($text) > 255) redirect_err("Reason text too long (max 255).");

    // Unik? (case-insensitive)
    if ($rid>0) {
        $chk = $conn->prepare("SELECT id FROM deactivate_reasons WHERE LOWER(reason_text)=LOWER(?) AND id<>? LIMIT 1");
        $chk->bind_param("si", $text, $rid);
    } else {
        $chk = $conn->prepare("SELECT id FROM deactivate_reasons WHERE LOWER(reason_text)=LOWER(?) LIMIT 1");
        $chk->bind_param("s", $text);
    }
    $chk->execute(); $exists = $chk->get_result()->num_rows > 0; $chk->close();
    if ($exists) redirect_err("Reason already exists.");

    if ($rid>0) {
        $stmt=$conn->prepare("UPDATE deactivate_reasons SET reason_text=?, active=?, sort_order=?, updated_at=NOW() WHERE id=?");
        $stmt->bind_param("siii",$text,$active,$sort,$rid);
        $ok=$stmt->execute(); $stmt->close();
        $ok ? redirect_ok("Reason updated.") : redirect_err("Failed to update.");
    } else {
        $stmt=$conn->prepare("INSERT INTO deactivate_reasons (reason_text,active,sort_order) VALUES (?,?,?)");
        $stmt->bind_param("sii",$text,$active,$sort);
        $ok=$stmt->execute(); $stmt->close();
        $ok ? redirect_ok("Reason added.") : redirect_err("Failed to add.");
    }
}

/* ---------- Toggle active ---------- */
if ($action==='toggle' && $id>0) {
    $stmt = $conn->prepare("UPDATE deactivate_reasons SET active = 1 - active, updated_at=NOW() WHERE id = ?");
    $stmt->bind_param("i", $id);
    $ok = $stmt->execute(); $stmt->close();
    $ok ? redirect_ok("Reason status toggled.") : redirect_err("Failed to toggle.");
}

/* ---------- Delete ---------- */
if ($action==='delete' && $id>0) {
    // check in use
    $c = 0;
    $chk = $conn->prepare("SELECT COUNT(*) c FROM members WHERE deactivated_reason_id = ?");
    $chk->bind_param("i", $id);
    $chk->execute(); $res = $chk->get_result(); if ($res) { $row=$res->fetch_assoc(); $c=(int)($row['c'] ?? 0); }
    $chk->close();
    if ($c > 0) redirect_err("Cannot delete: reason already used by members.");

    $del = $conn->prepare("DELETE FROM deactivate_reasons WHERE id = ?");
    $del->bind_param("i", $id);
    $ok = $del->execute(); $del->close();
    $ok ? redirect_ok("Reason deleted.") : redirect_err("Failed to delete.");
}

/* ---------- Fetch list ---------- */
$rows=[];
$res=$conn->query("SELECT id,reason_text,active,sort_order,created_at,updated_at
                     FROM deactivate_reasons
                 ORDER BY sort_order ASC, reason_text ASC");
if ($res) while($r=$res->fetch_assoc()) $rows[]=$r;

/* ---------- For edit form ---------- */
$editRow = null;
if ($action==='edit' && $id>0) {
    $s=$conn->prepare("SELECT id,reason_text,active,sort_order FROM deactivate_reasons WHERE id=?");
    $s->bind_param("i",$id); $s->execute(); $r=$s->get_result();
    if ($r && $r->num_rows===1) $editRow=$r->fetch_assoc();
    $s->close();
}

ob_start();
?>
<style>
/* Layout */
.page   { display:flex; flex-direction:column; gap:14px; }
.card   { background:#fff; border:1px solid #eee; border-radius:14px; padding:18px; box-shadow:0 2px 10px rgba(0,0,0,.04); }
h2      { margin:0 0 8px; }
h3      { margin:0 0 10px; }

/* Table */
.table { width:100%; border-collapse: collapse; background:#fff; }
.table th,.table td { border:1px solid #eaeaea; padding:10px; }
.table thead th { background:#f8fafc; text-align:left; }

/* Inputs */
.grid  { display:grid; grid-template-columns: 2fr 1fr 1fr; gap:12px; }
label  { display:block; font-weight:600; margin-bottom:6px; }
input[type="text"], input[type="number"], select {
  width:100%; padding:10px; border:1px solid #d1d5db; border-radius:10px; background:#fff;
}

/* Badges & buttons */
.badge { padding:2px 8px; border-radius:12px; font-size:.8rem; border:1px solid transparent; }
.badge.on  { background:#d1fae5; color:#065f46; border-color:#a7f3d0; }
.badge.off { background:#fee2e2; color:#991b1b; border-color:#fecaca; }

.btn { display:inline-block; padding:8px 12px; border-radius:10px; border:1px solid #d1d5db; background:#fff; cursor:pointer; text-decoration:none; }
.btn-primary { background:#2563eb; color:#fff; border-color:#2563eb; }
.btn-danger  { background:#dc2626; color:#fff; border-color:#dc2626; }
.btn-ghost   { background:#f3f4f6; color:#111827; }

/* Flash (centered message + close) */
.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;
  box-shadow:0 2px 8px rgba(2,6,23,.06);
}
.flash.success{ background:#ecfdf5; border-color:#a7f3d0; color:#065f46; }
.flash.error  { background:#fef2f2; border-color:#fecaca; color:#991b1b; }
.flash .msg{ flex:1; text-align:center; }
.flash .close{
  position:absolute; top:8px; right:10px;
  border:0; background:transparent; font-size:18px; cursor:pointer; line-height:1;
}
</style>

<h2>🚫 Settings — Deactivate Reasons</h2>

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

<div class="page">

  <div class="card">
    <h3><?= $editRow ? 'Edit Reason' : 'Add Reason' ?></h3>
    <form method="post">
      <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($CSRF) ?>">
      <input type="hidden" name="id" value="<?= htmlspecialchars($editRow['id'] ?? 0) ?>">
      <div class="grid">
        <div>
          <label>Reason Text</label>
          <input type="text" name="reason_text" value="<?= htmlspecialchars($editRow['reason_text'] ?? '') ?>" required maxlength="255" placeholder="e.g. Resigned / Retired / Transferred">
        </div>
        <div>
          <label>Sort Order</label>
          <input type="number" name="sort_order" value="<?= htmlspecialchars($editRow['sort_order'] ?? 0) ?>">
        </div>
        <div>
          <label>Status</label>
          <select name="active">
            <option value="1" <?= ((($editRow['active'] ?? 1)==1)?'selected':'') ?>>Active</option>
            <option value="0" <?= ((($editRow['active'] ?? 1)==0)?'selected':'') ?>>Inactive</option>
          </select>
        </div>
      </div>
      <div style="margin-top:10px; display:flex; gap:8px; align-items:center;">
        <button class="btn btn-primary" type="submit"><?= $editRow ? 'Update' : 'Add' ?> Reason</button>
        <?php if ($editRow): ?>
          <a class="btn btn-ghost" href="settings-deactivate-reasons.php">Cancel</a>
        <?php endif; ?>
      </div>
    </form>
  </div>

  <div class="card">
    <h3>Reason List</h3>
    <table class="table">
      <thead>
        <tr>
          <th style="width:60px;">ID</th>
          <th>Reason</th>
          <th style="width:110px;">Sort</th>
          <th style="width:110px;">Status</th>
          <th style="width:260px;">Actions</th>
        </tr>
      </thead>
      <tbody>
      <?php if (!$rows): ?>
        <tr><td colspan="5">No reasons found.</td></tr>
      <?php else: foreach ($rows as $row): ?>
        <tr>
          <td><?= (int)$row['id'] ?></td>
          <td><?= htmlspecialchars($row['reason_text']) ?></td>
          <td><?= (int)$row['sort_order'] ?></td>
          <td>
            <span class="badge <?= $row['active']?'on':'off' ?>">
              <?= $row['active']?'Active':'Inactive' ?>
            </span>
          </td>
          <td style="display:flex; gap:8px; flex-wrap:wrap;">
            <a class="btn btn-primary" href="settings-deactivate-reasons.php?action=edit&id=<?= (int)$row['id'] ?>">Edit</a>
            <a class="btn" href="settings-deactivate-reasons.php?action=toggle&id=<?= (int)$row['id'] ?>">Toggle</a>
            <a class="btn btn-danger" href="settings-deactivate-reasons.php?action=delete&id=<?= (int)$row['id'] ?>"
               onclick="return confirm('Delete this reason? This cannot be undone.');">Delete</a>
          </td>
        </tr>
      <?php endforeach; endif; ?>
      </tbody>
    </table>
  </div>

</div>

<script>
(function(){
  // Auto-hide flash after 4s + fade, and scroll to top if present
  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
$content = ob_get_clean();
include 'layout.php';
