<?php
// /edenrms/pages/approval_view.php
declare(strict_types=1);
@header('Content-Type: text/html; charset=utf-8');

$DEBUG = isset($_GET['debug']) && $_GET['debug'] === '1';
if ($DEBUG) {
  @ini_set('display_errors', '1');
  @ini_set('display_startup_errors', '1');
  error_reporting(E_ALL);
} else {
  error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);
}

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

/* ---------- DB bootstrap ---------- */
$ROOT = dirname(__DIR__);
$db = null;

try {
  $AUTH = $ROOT . '/includes/auth.php';
  if (is_file($AUTH)) {
    require_once $AUTH;
    if (function_exists('ec_db')) $db = ec_db();
  }

  if (!$db instanceof mysqli) {
    $INC = $ROOT . '/includes/db.php';
    if (is_file($INC)) {
      require_once $INC;
      if (isset($conn) && $conn instanceof mysqli) $db = $conn;
    }
  }

  if (!$db instanceof mysqli) {
    $db = new mysqli('localhost', 'root', '', 'edencamp_edencampus');
  }

  $db->set_charset('utf8mb4');
  mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
} catch (Throwable $e) {
  http_response_code(500);
  echo $DEBUG ? "<pre>DB error: " . $e->getMessage() . "</pre>" : "DB error.";
  exit;
}

/* ---------- helpers ---------- */
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }

function t_exists(mysqli $db, string $t): bool {
  try {
    $st = $db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=?");
    $st->bind_param('s', $t);
    $st->execute();
    $st->store_result();
    $ok = $st->num_rows > 0;
    $st->free_result();
    $st->close();
    return $ok;
  } catch (Throwable $e) {
    return false;
  }
}

function c_exists(mysqli $db, string $t, string $c): bool {
  try {
    if (!t_exists($db, $t)) return false;
    $st = $db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=?");
    $st->bind_param('ss', $t, $c);
    $st->execute();
    $st->store_result();
    $ok = $st->num_rows > 0;
    $st->free_result();
    $st->close();
    return $ok;
  } catch (Throwable $e) {
    return false;
  }
}

function stmt_all_assoc(mysqli_stmt $st): array {
  $meta = $st->result_metadata();
  if (!$meta) return [];
  $fields = [];
  $row = [];
  $bind = [];
  while ($f = $meta->fetch_field()) {
    $fields[] = $f->name;
    $row[$f->name] = null;
    $bind[] = &$row[$f->name];
  }
  $meta->free();
  call_user_func_array([$st, 'bind_result'], $bind);

  $out = [];
  while ($st->fetch()) {
    $r = [];
    foreach ($fields as $f) $r[$f] = $row[$f];
    $out[] = $r;
  }
  return $out;
}

function fmt_dt($v): string {
  $v = trim((string)$v);
  if ($v === '' || $v === '0000-00-00' || $v === '0000-00-00 00:00:00') return '—';
  $ts = strtotime($v);
  return $ts ? date('Y-m-d h:i A', $ts) : h($v);
}

function rowv(string $label, $value): string {
  $show = trim((string)$value);
  if ($show === '') $show = '—';
  return '<tr><th style="width:220px">' . h($label) . '</th><td>' . h($show) . '</td></tr>';
}

/* ---------- guard ---------- */
if ($id <= 0 || !t_exists($db, 'approval_requests')) {
  echo '<!doctype html><html><body class="p-3"><div class="alert alert-danger">Invalid request.</div></body></html>';
  exit;
}

/* ---------- tolerant SELECT ---------- */
$typeExpr = c_exists($db,'approval_requests','type') ? 'ar.type' :
           (c_exists($db,'approval_requests','req_type') ? 'ar.req_type' : "''");

$coSidParts = array_filter([
  c_exists($db,'approval_requests','student_id') ? 'ar.student_id' : null,
  c_exists($db,'approval_requests','ref_id')     ? 'ar.ref_id'     : null,
  c_exists($db,'approval_requests','sid')        ? 'ar.sid'        : null,
  c_exists($db,'approval_requests','entity_id')  ? 'ar.entity_id'  : null,
]);
$coSidExpr = $coSidParts ? ("COALESCE(" . implode(',', $coSidParts) . ")") : "NULL";

$courseExpr  = c_exists($db,'approval_requests','course_id')    ? 'ar.course_id'    : 'NULL';
$payloadExpr = c_exists($db,'approval_requests','payload')      ? 'ar.payload'      : 'NULL';
$statusExpr  = c_exists($db,'approval_requests','status')       ? 'ar.status'       : "''";
$reqAtExpr   = c_exists($db,'approval_requests','requested_at') ? 'ar.requested_at' : 'NULL';
$decAtExpr   = c_exists($db,'approval_requests','decided_at')   ? 'ar.decided_at'   : 'NULL';
$noteExpr    = c_exists($db,'approval_requests','note')         ? 'ar.note'
             : (c_exists($db,'approval_requests','reason')      ? 'ar.reason' : "''");
$refIdExpr   = c_exists($db,'approval_requests','ref_id')       ? 'ar.ref_id'       : 'NULL';

$sql = "SELECT
          ar.id,
          {$typeExpr}    AS type,
          {$statusExpr}  AS status,
          {$coSidExpr}   AS sid,
          {$courseExpr}  AS course_id,
          {$refIdExpr}   AS ref_id,
          {$payloadExpr} AS payload,
          {$reqAtExpr}   AS requested_at,
          {$decAtExpr}   AS decided_at,
          {$noteExpr}    AS note
        FROM approval_requests ar
        WHERE ar.id=? LIMIT 1";

try {
  $st = $db->prepare($sql);
  $st->bind_param('i', $id);
  $st->execute();
  $rows = stmt_all_assoc($st);
  $st->close();
} catch (Throwable $e) {
  $rows = [];
}

$r = $rows[0] ?? null;
if (!$r) {
  echo '<!doctype html><html><body class="p-3"><div class="alert alert-warning">Request not found.</div></body></html>';
  exit;
}

/* ---------- payload ---------- */
$payload = [];
if (!empty($r['payload'])) {
  $tmp = json_decode((string)$r['payload'], true);
  if (is_array($tmp)) $payload = $tmp;
}

/* ---------- student display ---------- */
$studentName = '—';
$studentReg  = '—';
$studentId   = (int)($r['sid'] ?? 0);

if ($studentId <= 0 && isset($payload['student_id'])) {
  $studentId = (int)$payload['student_id'];
}

$stuTbl = t_exists($db, 'studentss') ? 'studentss' : (t_exists($db, 'students') ? 'students' : null);
if ($studentId > 0 && $stuTbl) {
  $nameCol = c_exists($db, $stuTbl, 'full_name') ? 'full_name' : (c_exists($db, $stuTbl, 'name') ? 'name' : null);
  $regCol  = c_exists($db, $stuTbl, 'center_reg_no') ? 'center_reg_no'
          : (c_exists($db, $stuTbl, 'reference_no') ? 'reference_no' : null);

  $sel = "SELECT " . ($nameCol ? "`$nameCol`" : "NULL") . " AS nm, " . ($regCol ? "`$regCol`" : "NULL") . " AS rg
          FROM `$stuTbl`
          WHERE id=? LIMIT 1";
  try {
    $q = $db->prepare($sel);
    $q->bind_param('i', $studentId);
    $q->execute();
    $q->bind_result($nm, $rg);
    if ($q->fetch()) {
      $studentName = $nm ?: '—';
      $studentReg  = $rg ?: '—';
    }
    $q->close();
  } catch (Throwable $e) {}
}

/* payload fallback */
if ($studentName === '—' && !empty($payload['full_name'])) {
  $studentName = (string)$payload['full_name'];
}
if ($studentReg === '—') {
  if (!empty($payload['center_reg_no'])) $studentReg = (string)$payload['center_reg_no'];
  elseif (!empty($payload['reference_no'])) $studentReg = (string)$payload['reference_no'];
}

/* ---------- course name ---------- */
$courseName = '—';
$courseId = (int)($r['course_id'] ?? 0);
if ($courseId > 0 && t_exists($db, 'courses')) {
  $courseCol = c_exists($db, 'courses', 'course_name') ? 'course_name'
            : (c_exists($db, 'courses', 'name') ? 'name' : null);
  if ($courseCol) {
    try {
      $q = $db->prepare("SELECT `$courseCol` FROM courses WHERE id=? LIMIT 1");
      $q->bind_param('i', $courseId);
      $q->execute();
      $q->bind_result($cn);
      if ($q->fetch()) $courseName = (string)$cn;
      $q->close();
    } catch (Throwable $e) {}
  }
}
if ($courseName === '—' && !empty($payload['course_name'])) {
  $courseName = (string)$payload['course_name'];
}

/* ---------- plan items ---------- */
$customItems = [];
$isPlanType = in_array(strtolower((string)$r['type']), ['custom_plan','custom_installment_plan','custom_installments','installment_plan'], true);

if ($isPlanType && !empty($r['ref_id']) && t_exists($db, 'custom_plan_request_items')) {
  try {
    $q = $db->prepare("SELECT installment_no, course_fee_lkr, registration_fee_lkr, certificate_fee_usd, due_date
                       FROM custom_plan_request_items
                       WHERE request_id=?
                       ORDER BY installment_no ASC, id ASC");
    $rid = (int)$r['ref_id'];
    $q->bind_param('i', $rid);
    $q->execute();
    $q->bind_result($no, $c, $rg, $usd, $dd);
    while ($q->fetch()) {
      $customItems[] = ['no'=>$no, 'c'=>$c, 'rg'=>$rg, 'usd'=>$usd, 'dd'=>$dd];
    }
    $q->close();
  } catch (Throwable $e) {}
}

if (!$customItems && isset($payload['items']) && is_array($payload['items'])) {
  foreach ($payload['items'] as $it) {
    $customItems[] = [
      'no'  => (int)($it['installment_no'] ?? $it['n'] ?? $it['no'] ?? 0),
      'c'   => (float)($it['course_fee_lkr'] ?? $it['course_fee'] ?? $it['course'] ?? 0),
      'rg'  => (float)($it['registration_fee_lkr'] ?? $it['reg_fee'] ?? $it['registration_fee'] ?? 0),
      'usd' => (float)($it['certificate_fee_usd'] ?? $it['cert_fee'] ?? $it['certificate_fee'] ?? 0),
      'dd'  => (string)($it['due_date'] ?? ''),
    ];
  }
}

if (!$customItems && isset($payload['rows']) && is_array($payload['rows'])) {
  foreach ($payload['rows'] as $it) {
    $customItems[] = [
      'no'  => (int)($it['installment_no'] ?? $it['n'] ?? $it['no'] ?? 0),
      'c'   => (float)($it['course_fee_lkr'] ?? $it['course_fee'] ?? $it['course'] ?? 0),
      'rg'  => (float)($it['registration_fee_lkr'] ?? $it['reg_fee'] ?? $it['registration_fee'] ?? 0),
      'usd' => (float)($it['certificate_fee_usd'] ?? $it['cert_fee'] ?? $it['certificate_fee'] ?? 0),
      'dd'  => (string)($it['due_date'] ?? ''),
    ];
  }
}

/* ---------- status display ---------- */
$rawStatus = strtolower((string)($r['status'] ?? 'pending'));
$statusClass = 'secondary';
if ($rawStatus === 'approved') $statusClass = 'success';
elseif ($rawStatus === 'rejected') $statusClass = 'danger';
elseif ($rawStatus === 'pending') $statusClass = 'warning';

$typeLabel = ucwords(str_replace('_', ' ', (string)($r['type'] ?? 'request')));
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Approval #<?= (int)$id ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
  body{background:transparent}
  .av-wrap{padding:16px}
  .av-card{border:1px solid #e5e7eb;border-radius:14px;overflow:hidden;background:#fff}
  .av-head{padding:14px 16px;border-bottom:1px solid #e5e7eb;background:linear-gradient(180deg,#f9fbff,#f3f6fb)}
  .av-title{font-weight:700;font-size:1.02rem;color:#111827}
  .av-sub{font-size:.82rem;color:#6b7280}
  .av-body{padding:16px}
  .kv th{width:220px;background:#fafafa;font-weight:600}
  .kv th,.kv td{padding:.65rem .8rem;border-color:#eceff3}
  .chip{display:inline-block;padding:.28rem .55rem;border-radius:999px;font-size:.74rem;font-weight:700}
  .chip-pending{background:#fff3cd;color:#8a6d3b}
  .chip-approved{background:#d1e7dd;color:#0f5132}
  .chip-rejected{background:#f8d7da;color:#842029}
  .code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace}
  pre.pretty-json{background:#0f172a;color:#e2e8f0;padding:12px;border-radius:12px;font-size:.8rem;max-height:280px;overflow:auto}
</style>
</head>
<body>
<div class="av-wrap">
  <div class="av-card" data-appr-id="<?= (int)$id ?>">
    <div class="av-head d-flex justify-content-between align-items-start gap-3 flex-wrap">
      <div>
        <div class="av-title">Approval Request #<?= (int)$id ?></div>
        <div class="av-sub"><?= h($typeLabel) ?></div>
      </div>
      <div class="text-end">
        <div id="statusCell" class="chip chip-<?= h($rawStatus) ?>"><?= h($rawStatus) ?></div>
        <div class="av-sub mt-1">Requested: <?= h(fmt_dt($r['requested_at'] ?? '')) ?></div>
        <div class="av-sub">Decided: <?= h(fmt_dt($r['decided_at'] ?? '')) ?></div>
      </div>
    </div>

    <div class="av-body">
      <div class="table-responsive">
        <table class="table table-bordered kv mb-3">
          <tbody>
            <?= rowv('Request ID', '#' . (int)$id) ?>
            <?= rowv('Request Type', $typeLabel) ?>
            <?= rowv('Status', $rawStatus) ?>
            <?= rowv('Student ID', $studentId > 0 ? (string)$studentId : '—') ?>
            <?= rowv('Student Name', $studentName) ?>
            <?= rowv('Registration / Ref No', $studentReg) ?>
            <?= rowv('Course', $courseName) ?>
            <?= rowv('Reason / Note', (string)($r['note'] ?? ($payload['reason'] ?? ''))) ?>
          </tbody>
        </table>
      </div>

      <?php if (!empty($payload)): ?>
        <div class="mb-3">
          <h6 class="fw-semibold mb-2">Snapshot / Payload Summary</h6>
          <div class="table-responsive">
            <table class="table table-sm table-bordered align-middle mb-0">
              <tbody>
              <?php foreach ($payload as $k => $v): ?>
                <?php if (is_array($v)) continue; ?>
                <tr>
                  <th style="width:220px"><?= h((string)$k) ?></th>
                  <td><?= h(is_scalar($v) || $v === null ? (string)$v : json_encode($v)) ?></td>
                </tr>
              <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>
      <?php endif; ?>

      <?php if (!empty($customItems)): ?>
        <div class="mb-3">
          <h6 class="fw-semibold mb-2">Installment Breakdown</h6>
          <div class="table-responsive">
            <table class="table table-bordered table-sm align-middle">
              <thead class="table-light">
                <tr>
                  <th>#</th>
                  <th>Course Fee (LKR)</th>
                  <th>Registration Fee (LKR)</th>
                  <th>Certificate Fee (USD)</th>
                  <th>Due Date</th>
                </tr>
              </thead>
              <tbody>
              <?php foreach ($customItems as $it): ?>
                <tr>
                  <td><?= (int)$it['no'] ?></td>
                  <td><?= number_format((float)$it['c'], 2) ?></td>
                  <td><?= number_format((float)$it['rg'], 2) ?></td>
                  <td><?= number_format((float)$it['usd'], 2) ?></td>
                  <td><?= h((string)$it['dd']) ?></td>
                </tr>
              <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>
      <?php endif; ?>

      <?php if (!empty($payload)): ?>
        <div class="mb-3">
          <h6 class="fw-semibold mb-2">Raw Payload</h6>
          <pre class="pretty-json mb-0"><?= h(json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)) ?></pre>
        </div>
      <?php endif; ?>

      <div class="d-flex justify-content-end gap-2 pt-2">
        <?php if ($rawStatus === 'pending'): ?>
          <button type="button"
                  class="btn btn-outline-danger js-reject"
                  id="btnReject"
                  data-id="<?= (int)$id ?>"
                  data-decision="reject"
                  data-summary="<?= h($typeLabel) ?>">
            Reject
          </button>

          <button type="button"
                  class="btn btn-success js-approve"
                  id="btnApprove"
                  data-id="<?= (int)$id ?>"
                  data-decision="approve"
                  data-summary="<?= h($typeLabel) ?>">
            Approve
          </button>
        <?php else: ?>
          <span class="text-muted small">This request has already been <?= h($rawStatus) ?>.</span>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>
</body>
</html>