<?php
// settings-rejection-reasons.php
require_once 'db.php';
session_start();

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

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

// ===== Ensure table exists =====
$conn->query("
CREATE TABLE IF NOT EXISTS rejection_reasons (
  id INT AUTO_INCREMENT PRIMARY KEY,
  code VARCHAR(50) NOT NULL UNIQUE,
  reason VARCHAR(255) NOT NULL,
  active TINYINT(1) NOT NULL DEFAULT 1,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

// ===== Defaults (seed) =====
$DEFAULTS = [
  ['DOC_INCOMPLETE', 'Dokumen tidak lengkap'],
  ['IC_INVALID',     'IC tidak sah / tidak padan'],
  ['RECEIPT_ISSUE',  'Isu resit bayaran'],
  ['NAME_MISMATCH',  'Nama tidak mengikut rekod'],
];
function seed_default_reasons(mysqli $conn, array $defs): void {
  $sql = "INSERT INTO rejection_reasons (code, reason, active)
          VALUES (?, ?, 1)
          ON DUPLICATE KEY UPDATE reason=VALUES(reason), active=VALUES(active)";
  $st = $conn->prepare($sql);
  foreach ($defs as [$code, $reason]) {
    $c = strtoupper($code);
    $st->bind_param('ss', $c, $reason);
    $st->execute();
  }
  $st->close();
}
function back($msg='', $ok=true){ header('Location: settings-rejection-reasons.php?'.http_build_query([$ok?'success':'error'=>$msg])); exit; }
function valid_code($s){ return (bool)preg_match('/^[A-Z0-9_\-]+$/', $s); }

// Auto-seed if empty
$cnt = 0;
if ($rs = $conn->query("SELECT COUNT(*) c FROM rejection_reasons")) { $cnt = (int)$rs->fetch_assoc()['c']; $rs->close(); }
if ($cnt === 0) seed_default_reasons($conn, $DEFAULTS);

// ===== Actions =====
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!hash_equals($CSRF, $_POST['csrf'] ?? '')) back('Invalid request token.', false);
  $action = $_POST['action'] ?? '';

  if ($action === 'seed_defaults'){ seed_default_reasons($conn, $DEFAULTS); back('Default reasons added/updated.'); }

  if ($action === 'create') {
    $code = strtoupper(str_replace(' ', '_', trim($_POST['code'] ?? '')));
    $reason = trim($_POST['reason'] ?? '');
    $active = isset($_POST['active']) ? 1 : 0;

    if ($code==='' || $reason==='') back('Code dan Reason wajib diisi.', false);
    if (!valid_code($code)) back('Code hanya A-Z, 0-9, _ atau -.', false);

    $st = $conn->prepare("SELECT id FROM rejection_reasons WHERE code=?"); $st->bind_param('s',$code); $st->execute(); $st->store_result();
    if ($st->num_rows>0){ $st->close(); back('Code sudah wujud.', false); } $st->close();

    $ins = $conn->prepare("INSERT INTO rejection_reasons (code,reason,active) VALUES (?,?,?)");
    $ins->bind_param('ssi',$code,$reason,$active); $ins->execute(); $ins->close();
    back('Reason baharu ditambah.');
  }

  if ($action === 'update') {
    $id = (int)($_POST['id'] ?? 0);
    $code = strtoupper(str_replace(' ', '_', trim($_POST['code'] ?? '')));
    $reason = trim($_POST['reason'] ?? '');
    if ($id<=0 || $code==='' || $reason==='') back('Data tidak lengkap.', false);
    if (!valid_code($code)) back('Code hanya A-Z, 0-9, _ atau -.', false);
    $st = $conn->prepare("SELECT id FROM rejection_reasons WHERE code=? AND id<>?"); $st->bind_param('si',$code,$id); $st->execute(); $st->store_result();
    if ($st->num_rows>0){ $st->close(); back('Code sudah digunakan.', false); } $st->close();
    $up = $conn->prepare("UPDATE rejection_reasons SET code=?, reason=? WHERE id=?");
    $up->bind_param('ssi',$code,$reason,$id); $up->execute(); $up->close();
    back('Reason dikemaskini.');
  }

  if ($action === 'toggle') {
    $id = (int)($_POST['id'] ?? 0); if ($id<=0) back('ID tidak sah.', false);
    $conn->query("UPDATE rejection_reasons SET active=1-active WHERE id=".(int)$id);
    back('Status reason ditukar.');
  }

  if ($action === 'delete') {
    $id = (int)($_POST['id'] ?? 0); if ($id<=0) back('ID tidak sah.', false);
    $used = 0;
    $st = $conn->prepare("SELECT COUNT(*) c FROM approval_logs WHERE rejection_reason_id=?"); $st->bind_param('i',$id); $st->execute(); $used += (int)$st->get_result()->fetch_assoc()['c']; $st->close();
    $st = $conn->prepare("SELECT COUNT(*) c FROM rejected_user WHERE rejection_reason_id=?"); $st->bind_param('i',$id); $st->execute(); $used += (int)$st->get_result()->fetch_assoc()['c']; $st->close();
    if ($used>0) { $conn->query("UPDATE rejection_reasons SET active=0 WHERE id=".(int)$id); back('Reason sedang digunakan. Ia dinyahaktifkan (tidak boleh dipadam).'); }
    else { $del = $conn->prepare("DELETE FROM rejection_reasons WHERE id=?"); $del->bind_param('i',$id); $del->execute(); $del->close(); back('Reason dipadam.'); }
  }

  back('Tiada tindakan diambil.', false);
}

// ===== Fetch list =====
$kw = trim($_GET['q'] ?? ''); $show = $_GET['show'] ?? 'all';
$where=[]; $params=[]; $types='';
if ($kw!==''){ $where[]='(code LIKE ? OR reason LIKE ?)'; $k="%$kw%"; $params[]=$k; $params[]=$k; $types.='ss'; }
if ($show==='active'){ $where[]='active=1'; }
if ($show==='inactive'){ $where[]='active=0'; }
$wsql = $where ? 'WHERE '.implode(' AND ',$where) : '';
$sql = "SELECT id, code, reason, active, created_at FROM rejection_reasons $wsql ORDER BY active DESC, reason ASC";
$st = $conn->prepare($sql); if ($types!=='') $st->bind_param($types, ...$params); $st->execute();
$res = $st->get_result(); $rows = $res->fetch_all(MYSQLI_ASSOC); $st->close();

// usage counts
$usage=[];
if ($rows){
  $ids = implode(',', array_map('intval', array_column($rows,'id')));
  $q1 = $conn->query("SELECT rejection_reason_id rid, COUNT(*) c FROM approval_logs WHERE rejection_reason_id IN ($ids) GROUP BY rid");
  if ($q1) while($r=$q1->fetch_assoc()) $usage[(int)$r['rid']] = ($usage[(int)$r['rid']] ?? 0) + (int)$r['c'];
  $q2 = $conn->query("SELECT rejection_reason_id rid, COUNT(*) c FROM rejected_user WHERE rejection_reason_id IN ($ids) GROUP BY rid");
  if ($q2) while($r=$q2->fetch_assoc()) $usage[(int)$r['rid']] = ($usage[(int)$r['rid']] ?? 0) + (int)$r['c'];
}

ob_start();
?>
<style>
.card{background:#fff;border:1px solid #e5e7eb;border-radius:10px;box-shadow:0 1px 2px rgba(0,0,0,.04)}
.card-header{padding:14px 16px;border-bottom:1px solid #f0f0f0;font-weight:600}
.card-body{padding:12px 16px}
.table{width:100%;border-collapse:separate;border-spacing:0;table-layout:fixed}
.table th,.table td{padding:10px 12px;border-bottom:1px solid #f0f0f0;vertical-align:middle}
.table thead th{background:#f8fafc;font-size:12px;text-transform:uppercase;letter-spacing:.02em;color:#4b5563}
.table tbody tr:hover{background:#fafafa}
th.col-idx{width:56px} th.col-code{width:220px} th.col-status{width:110px}
th.col-used{width:90px;text-align:right} th.col-actions{width:260px;text-align:right}
.badge{display:inline-block;padding:4px 10px;border-radius:9999px;font-size:12px;font-weight:600}
.badge-active{background:#e6f7ed;color:#065f46;border:1px solid #a7f3d0}
.badge-inactive{background:#fff1f2;color:#9f1239;border:1px solid #fecdd3}
.btn{border:1px solid #d1d5db;background:#fff;border-radius:8px;padding:6px 10px;font-size:13px;cursor:pointer}
.btn-primary{background:#2563eb;color:#fff;border-color:#2563eb}
.btn-danger{background:#dc2626;color:#fff;border-color:#dc2626}
.btn-light{background:#f3f4f6}
.input,.select{padding:8px;border:1px solid #d1d5db;border-radius:8px;width:100%}
.input-code{font-family:ui-monospace, SFMono-Regular, Menlo, monospace;text-transform:uppercase;letter-spacing:.02em}
.add-toolbar{display:flex;gap:8px;flex-wrap:wrap;align-items:center}
.add-form{display:flex;gap:8px;flex-wrap:wrap;align-items:center}
.form-inline{display:inline}
.small{font-size:12px;color:#6b7280;margin-top:6px}
.text-end{text-align:right}
.actions{display:inline-flex;gap:6px;flex-wrap:wrap;justify-content:flex-end}

/* ===== Flash (align center) ===== */
.flash{
  position:relative;
  display:flex; align-items:flex-start; gap:10px;
  padding:12px 40px 12px 12px; border-radius:12px; margin:10px 0;
  border:1px solid;
}
.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>

<div class="content">
  <h2>Settings — Rejection 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; ?>

  <!-- Add new (two separate forms; no nesting) -->
  <div class="card" style="margin:12px 0;">
    <div class="card-header">Tambah Reason Baharu</div>
    <div class="card-body">
      <div class="add-toolbar">
        <!-- Create form -->
        <form method="post" class="add-form" id="create-form">
          <input type="hidden" name="csrf" value="<?= htmlspecialchars($CSRF) ?>">
          <input type="hidden" name="action" value="create">
          <input class="input input-code" type="text" name="code" placeholder="CODE (A-Z/0-9/_/-)" style="max-width:220px" required>
          <input class="input" type="text" name="reason" placeholder="Contoh: Dokumen tidak lengkap" style="flex:1;min-width:260px" required>
          <label class="small"><input type="checkbox" name="active" checked> Active</label>
          <button class="btn btn-primary" type="submit">Add</button>
        </form>

        <!-- Seed defaults form (separate) -->
        <form method="post" id="seed-form" onsubmit="return confirm('Add/refresh default reasons?');">
          <input type="hidden" name="csrf" value="<?= htmlspecialchars($CSRF) ?>">
          <input type="hidden" name="action" value="seed_defaults">
          <button class="btn btn-light" type="submit">Add default reasons</button>
        </form>
      </div>
    </div>
  </div>

  <!-- List -->
  <div class="card">
    <div class="card-body" style="padding:0">
      <table class="table">
        <thead>
          <tr>
            <th class="col-idx">#</th>
            <th class="col-code">Code</th>
            <th>Reason</th>
            <th class="col-status">Status</th>
            <th class="col-used">Used</th>
            <th class="col-actions">Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php if (!$rows): ?>
            <tr><td colspan="6"><em class="small">Tiada data.</em></td></tr>
          <?php else: $i=1; foreach ($rows as $r):
            $id=(int)$r['id']; $used=(int)($usage[$id] ?? 0); $active=(int)$r['active']===1;
            $formId = "fr-".$id;
          ?>
          <tr>
            <td><?= $i++ ?></td>

            <!-- Code -->
            <td>
              <input class="input input-code" type="text" name="code" value="<?= htmlspecialchars($r['code']) ?>" form="<?= $formId ?>" required>
              <div class="small">Created: <?= htmlspecialchars($r['created_at']) ?></div>
            </td>

            <!-- Reason -->
            <td>
              <input class="input" type="text" name="reason" value="<?= htmlspecialchars($r['reason']) ?>" form="<?= $formId ?>" required>
            </td>

            <!-- Status -->
            <td>
              <span class="badge <?= $active?'badge-active':'badge-inactive' ?>"><?= $active?'Active':'Inactive' ?></span>
            </td>

            <!-- Used -->
            <td class="text-end"><?= number_format($used) ?></td>

            <!-- Actions -->
            <td class="text-end">
              <form id="<?= $formId ?>" method="post" class="form-inline">
                <input type="hidden" name="csrf" value="<?= htmlspecialchars($CSRF) ?>">
                <input type="hidden" name="action" value="update">
                <input type="hidden" name="id" value="<?= $id ?>">
                <div class="actions">
                  <button class="btn btn-primary" type="submit">Save</button>
                </div>
              </form>

              <form method="post" class="form-inline" style="margin-left:6px;">
                <input type="hidden" name="csrf" value="<?= htmlspecialchars($CSRF) ?>">
                <input type="hidden" name="action" value="toggle">
                <input type="hidden" name="id" value="<?= $id ?>">
                <button class="btn" type="submit"><?= $active?'Deactivate':'Activate' ?></button>
              </form>

              <form method="post" class="form-inline" style="margin-left:6px;" onsubmit="return confirmDelete(<?= $used ?>);">
                <input type="hidden" name="csrf" value="<?= htmlspecialchars($CSRF) ?>">
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="id" value="<?= $id ?>">
                <button class="btn btn-danger" type="submit">Delete</button>
              </form>
            </td>
          </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<script>
// Uppercase + ganti space kepada underscore pada field CODE semasa taip
document.addEventListener('input', function(e){
  if (e.target && e.target.name === 'code') {
    e.target.value = e.target.value.replace(/\s+/g,'_').toUpperCase();
  }
});
function confirmDelete(used){
  if (used > 0) {
    return confirm('Reason ini telah digunakan ('+used+'). Ia tidak akan dipadam, tetapi akan dinyahaktifkan. Teruskan?');
  }
  return confirm('Padam reason ini? Tindakan tidak boleh diundur.');
}

// Auto-hide flash + scroll to top
(function(){
  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';
