<?php
/**
 * view-user.php — District-based access guard + layout.php wrapper
 * - EXCO/AJK hanya boleh lihat rekod dalam district lantikan mereka
 * - Stage infer (EXCO/AJK) jika tidak diberi
 * - Modal Reject dengan master rejection_reasons
 */

session_start();
require_once 'db.php';

// ========= Auth =========
if (!isset($_SESSION['user'])) { header('Location: login.php'); exit; }
$viewerRole = $_SESSION['user']['role']; // admin|exco|ajk
$viewerName = $_SESSION['user']['name'] ?? ($_SESSION['user']['full_name'] ?? '');
$userId     = (int)($_SESSION['user']['id'] ?? 0);

// ========= Validate parameters =========
$id     = isset($_GET['id']) ? (int) $_GET['id'] : 0;
$level  = $_GET['level'] ?? ''; // exco|ajk|admin (viewer)
$stageQ = $_GET['stage'] ?? ''; // EXCO|AJK (paparan)
if (!$id || !in_array($level, ['exco','ajk','admin'], true)) { echo "Invalid request."; exit; }

// ========= Helpers =========
function existsIn(mysqli $conn, string $table, int $id): bool {
  $sql = "SELECT 1 FROM {$table} WHERE id=? LIMIT 1";
  $stmt = $conn->prepare($sql); if (!$stmt) return false;
  $stmt->bind_param('i', $id);
  $stmt->execute();
  $stmt->store_result();
  $ok = $stmt->num_rows > 0;
  $stmt->close();
  return $ok;
}
function userHasDistrictAccess(mysqli $conn, int $memberId, string $role, int $districtId): bool {
  if ($memberId <= 0 || !$districtId) return false;
  $sql = "SELECT 1 FROM district_role_assignment
          WHERE member_id=? AND role=? AND is_active=1 AND district_id=? LIMIT 1";
  $stmt = $conn->prepare($sql);
  if (!$stmt) return false;
  $stmt->bind_param('isi', $memberId, $role, $districtId);
  $stmt->execute(); $stmt->store_result();
  $ok = $stmt->num_rows > 0;
  $stmt->close();
  return $ok;
}

// ========= Determine source table & stage (DISPLAY in UPPER, POST in lower) =========
$stageUp = strtoupper(trim($stageQ)); // EXCO|AJK untuk paparan
$table   = '';

if ($stageUp === 'AJK') {
  $table = 'pending_ajk';
} elseif ($stageUp === 'EXCO') {
  $table = 'pending_exco';
} else {
  // Tiada stage eksplisit — infer
  if     ($level === 'ajk'  && existsIn($conn,'pending_ajk',$id))  { $table = 'pending_ajk';  $stageUp='AJK'; }
  elseif ($level === 'exco' && existsIn($conn,'pending_exco',$id)) { $table = 'pending_exco'; $stageUp='EXCO'; }
  else {
    // admin: cuba detect mana-mana wujud
    if     (existsIn($conn,'pending_exco',$id)) { $table='pending_exco'; $stageUp='EXCO'; }
    elseif (existsIn($conn,'pending_ajk',$id))  { $table='pending_ajk';  $stageUp='AJK';  }
  }
}

if ($table==='') { echo "Record not found."; exit; }
$stageLo = strtolower($stageUp); // exco|ajk

// ========= Fetch user record (JOIN districts untuk nama) =========
$cols = "p.id, p.full_name, p.staff_number, p.ic_number, p.email, p.job_title,
         p.home_phone, p.phone, p.race, p.location, p.address, p.postcode,
         p.exco_auto, p.exco_select, p.created_at, p.receipt, p.ack_form, p.ack_date,
         p.district_id, d.name AS district_name";

$sql = "SELECT {$cols} FROM {$table} p
        LEFT JOIN districts d ON d.id = p.district_id
        WHERE p.id=? LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$user) { echo "User not found in {$table}."; exit; }

// ========= Access guard (district-based visibility) =========
// Admin: boleh lihat semua
if ($viewerRole !== 'admin') {
  $recordDistrictId = (int)($user['district_id'] ?? 0);
  if ($recordDistrictId <= 0) { echo "Record does not have a valid district."; exit; }
  // EXCO boleh lihat pending_exco dalam district lantikan EXCO
  if ($viewerRole==='exco' && $table==='pending_exco') {
    if (!userHasDistrictAccess($conn, $userId, 'exco', $recordDistrictId)) {
      echo "You are not allowed to view this record (outside your district)."; exit;
    }
  }
  // AJK boleh lihat pending_ajk dalam district lantikan AJK
  if ($viewerRole==='ajk' && $table==='pending_ajk') {
    if (!userHasDistrictAccess($conn, $userId, 'ajk', $recordDistrictId)) {
      echo "You are not allowed to view this record (outside your district)."; exit;
    }
  }
}

// ========= Master: Rejection Reasons (active) =========
$reasons = [];
$qr = $conn->query("SELECT id, reason FROM rejection_reasons WHERE active=1 ORDER BY reason ASC");
if ($qr) while ($r = $qr->fetch_assoc()) $reasons[] = $r;

// ========= Build $content untuk layout.php =========
ob_start();
?>
<style>
/* ------- self-contained styles for this page ------- */
.content{max-width:1080px;margin:24px auto;padding:0 16px}
.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;display:flex;justify-content:space-between;align-items:center}
.card-body{padding:16px}
.grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}
.kv{display:flex;gap:10px}
.kv .k{min-width:220px;color:#6b7280}
.badge{display:inline-block;padding:3px 8px;border-radius:9999px;font-size:12px;font-weight:600;vertical-align:middle}
.badge-exco{background:#e8efff;color:#1d4ed8;border:1px solid #c7d2fe}
.badge-ajk{background:#fff2d8;color:#92400e;border:1px solid #fde68a}
.btn{border:1px solid #d1d5db;background:#fff;border-radius:8px;padding:8px 12px;font-size:14px;cursor:pointer}
.btn-success{background:#16a34a;color:#fff;border-color:#16a34a}
.btn-danger{background:#dc2626;color:#fff;border-color:#dc2626}
.btn-light{background:#f3f4f6}
.actions{display:flex;gap:8px;flex-wrap:wrap}
.small{font-size:12px;color:#6b7280}
.hr{border-top:1px solid #eef2f7;margin:12px 0}
a.link{color:#2563eb;text-decoration:none}
a.link:hover{text-decoration:underline}
.modal{position:fixed;inset:0;background:rgba(0,0,0,.35);display:none;align-items:center;justify-content:center;z-index:50}
.modal.show{display:flex}
.modal-card{background:#fff;border-radius:12px;box-shadow:0 10px 30px rgba(0,0,0,.2);width:min(520px,92vw);overflow:hidden}
.modal-head{padding:12px 16px;border-bottom:1px solid #f1f5f9;font-weight:600}
.modal-body{padding:16px}
.modal-foot{padding:12px 16px;border-top:1px solid #f1f5f9;display:flex;gap:8px;justify-content:flex-end}
.select{padding:6px 8px;border:1px solid #d1d5db;border-radius:8px;min-width:260px}
.badge-district{background:#eefdf3;color:#065f46;border:1px solid #a7f3d0}
</style>

<div class="content">
  <div class="card">
    <div class="card-header">
      <div>
        View User —
        <span class="badge <?= $stageUp==='EXCO'?'badge-exco':'badge-ajk' ?>"><?= htmlspecialchars($stageUp) ?></span>
        <?php if (!empty($user['district_name'])): ?>
          <span class="badge badge-district" style="margin-left:8px"><?= htmlspecialchars($user['district_name']) ?></span>
        <?php endif; ?>
      </div>
      <div class="small">Created at: <?= !empty($user['created_at']) ? date('d M Y H:i', strtotime($user['created_at'])) : '-' ?></div>
    </div>

    <div class="card-body">
      <div class="grid">
        <div class="kv"><div class="k">Full Name</div><div class="v"><strong><?= htmlspecialchars($user['full_name'] ?? '') ?></strong></div></div>
        <div class="kv"><div class="k">Staff Number</div><div class="v"><?= htmlspecialchars($user['staff_number'] ?? '') ?></div></div>
        <div class="kv"><div class="k">IC Number</div><div class="v"><?= htmlspecialchars($user['ic_number'] ?? '') ?></div></div>
        <div class="kv"><div class="k">Email</div><div class="v">
          <?php if (!empty($user['email'])): ?>
            <a class="link" href="mailto:<?= htmlspecialchars($user['email']) ?>"><?= htmlspecialchars($user['email']) ?></a>
          <?php else: ?><span class="small">-</span><?php endif; ?>
        </div></div>
        <div class="kv"><div class="k">Phone (Home)</div><div class="v"><?= htmlspecialchars($user['home_phone'] ?? '') ?></div></div>
        <div class="kv"><div class="k">Phone (Mobile)</div><div class="v">
          <?php if (!empty($user['phone'])): ?>
            <a class="link" href="tel:<?= htmlspecialchars($user['phone']) ?>"><?= htmlspecialchars($user['phone']) ?></a>
          <?php else: ?><span class="small">-</span><?php endif; ?>
        </div></div>
        <div class="kv"><div class="k">Race</div><div class="v"><?= htmlspecialchars($user['race'] ?? '') ?></div></div>
        <div class="kv"><div class="k">Work Location</div><div class="v"><?= htmlspecialchars($user['location'] ?? '') ?></div></div>
        <div class="kv"><div class="k">District</div><div class="v"><?= htmlspecialchars($user['district_name'] ?? '—') ?></div></div>
        <div class="kv"><div class="k">EXCO (Auto)</div><div class="v"><?= htmlspecialchars($user['exco_auto'] ?? '') ?></div></div>
        <div class="kv"><div class="k">AJK (Selected)</div><div class="v"><?= htmlspecialchars($user['exco_select'] ?? '') ?></div></div>
        <div class="kv"><div class="k">Address</div><div class="v"><?= nl2br(htmlspecialchars($user['address'] ?? '')) ?></div></div>
        <div class="kv"><div class="k">Postcode</div><div class="v"><?= htmlspecialchars($user['postcode'] ?? '') ?></div></div>
        <div class="kv"><div class="k">Acknowledgement</div>
          <div class="v">
            <?= !empty($user['ack_form']) ? 'Yes ('.htmlspecialchars($user['ack_date'] ?? '').')' : 'No' ?>
          </div>
        </div>
        <div class="kv"><div class="k">Receipt</div>
          <div class="v">
            <?php if(!empty($user['receipt'])): ?>
              <a class="link" href="<?= htmlspecialchars($user['receipt']) ?>" target="_blank" rel="noopener">View / Download</a>
            <?php else: ?>
              <span class="small">-</span>
            <?php endif; ?>
          </div>
        </div>
      </div>

      <div class="hr"></div>

      <!-- Actions -->
      <div class="actions">
        <!-- Back -->
        <a class="btn btn-light" href="javascript:history.back()">Back</a>

        <!-- Post with proper stage -->
        <form id="approvalForm" method="post" action="approval-action.php" onsubmit="return validateRejectReason(event, this);">
          <input type="hidden" name="id" value="<?= (int)($user['id'] ?? 0) ?>">
          <input type="hidden" name="level" value="<?= htmlspecialchars($level) ?>">
          <input type="hidden" name="stage" value="<?= htmlspecialchars($stageLo) ?>">
          <input type="hidden" name="action" value="approve" class="action-field">

          <button class="btn btn-success" type="submit" data-action="approve"
                  onclick="this.closest('form').querySelector('.action-field').value='approve'">
            ✅ Approve
          </button>

          <button class="btn btn-danger" type="button" onclick="openRejectModal()">
            ❌ Reject
          </button>
        </form>
      </div>
    </div>
  </div>
</div>

<!-- Reject Modal -->
<div id="rejectModal" class="modal" aria-hidden="true">
  <div class="modal-card">
    <div class="modal-head">Reject Application</div>
    <div class="modal-body">
      <?php if (count($reasons)): ?>
        <div class="small" style="margin-bottom:6px;font-weight:600">Pilih Alasan Penolakan</div>
        <!-- Mula disabled; enable bila modal dibuka -->
        <select name="reason_id" id="reasonSelect" form="approvalForm" class="select" disabled>
          <option value="">-- Pilih alasan --</option>
          <?php foreach($reasons as $rs): ?>
            <option value="<?= (int)$rs['id'] ?>"><?= htmlspecialchars($rs['reason']) ?></option>
          <?php endforeach; ?>
        </select>
      <?php else: ?>
        <div class="small" style="color:#b91c1c">
          Tiada senarai alasan aktif. Sila tambah di <em>Settings → Rejection Reasons</em>.
        </div>
      <?php endif; ?>
    </div>
    <div class="modal-foot">
      <button class="btn btn-light" type="button" onclick="closeRejectModal()">Batal</button>
      <button class="btn btn-danger" type="button" onclick="submitReject()">Hantar Penolakan</button>
    </div>
  </div>
</div>

<script>
// ===== Modal helpers =====
function openRejectModal(){
  var m = document.getElementById('rejectModal'); if (!m) return;
  m.classList.add('show');
  // enable select & set action=reject
  var sel = document.getElementById('reasonSelect'); if (sel) sel.disabled = false;
  var form = document.getElementById('approvalForm');
  var actionField = form?.querySelector('.action-field'); if (actionField) actionField.value='reject';
}
function closeRejectModal(){
  var m = document.getElementById('rejectModal'); if (!m) return;
  m.classList.remove('show');
  // disable select & reset nilai & action=approve
  var sel = document.getElementById('reasonSelect');
  if (sel) { sel.disabled = true; sel.value=''; }
  var form = document.getElementById('approvalForm');
  var actionField = form?.querySelector('.action-field'); if (actionField) actionField.value='approve';
}
function submitReject(){
  var form = document.getElementById('approvalForm'); if (!form) return;
  var actionField = form.querySelector('.action-field'); if (actionField) actionField.value='reject';
  form.submit();
}

// ===== Validator: enforce alasan hanya bila Reject =====
function validateRejectReason(ev, f){
  var intendedAction = (f.querySelector('.action-field') || {}).value || 'approve';

  // Jika browser support event.submitter (Chrome/Edge/Firefox baharu)
  if (ev && ev.submitter && ev.submitter.dataset && ev.submitter.dataset.action) {
    intendedAction = ev.submitter.dataset.action;
  }

  if (intendedAction !== 'reject') return true;

  // Reject → reason wajib & select mesti enabled
  var sel = document.getElementById('reasonSelect');
  if (!sel || sel.disabled || !sel.value) {
    alert('Sila pilih alasan penolakan.');
    return false;
  }
  return true;
}
</script>
<?php
$content = ob_get_clean();

require 'layout.php';
