<?php
/**
 * Demo requests — Oric team only.
 * Review incoming demo requests, approve them (issues a time-limited access
 * code), and send the code to the school via WhatsApp or email.
 *
 * Locked to real admins: a demo session ($_SESSION['is_demo']) can never open
 * this page, so visitors can't see other schools' contact details.
 */
if (session_status() === PHP_SESSION_NONE) session_start();

if (!isset($_SESSION['user_id'])) { header('Location: ../login.php'); exit; }
if (($_SESSION['role'] ?? '') !== 'admin' || !empty($_SESSION['is_demo'])) {
    header('Location: ../dashboard.php?error=access_denied');
    exit;
}

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../demo_helpers.php';

$conn = getDBConnection();
ensureDemoRequestsTable($conn);

$flash = '';
$DEFAULT_VALID_DAYS = 14;
$DEFAULT_USES       = 50;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id     = (int) ($_POST['id'] ?? 0);
    $action = $_POST['action'] ?? '';
    $row    = null;
    if ($id) {
        $r = $conn->query("SELECT * FROM demo_requests WHERE id = " . $id . " LIMIT 1");
        $row = $r ? $r->fetch_assoc() : null;
    }

    if ($row && in_array($action, ['approve', 'regenerate'], true)) {
        $code = generateDemoCode();
        $days = max(1, (int) ($_POST['valid_days'] ?? $DEFAULT_VALID_DAYS));
        $uses = max(1, (int) ($_POST['uses_allowed'] ?? $DEFAULT_USES));
        $stmt = $conn->prepare(
            "UPDATE demo_requests
             SET status='approved', access_code=?, uses_allowed=?, uses_count=0,
                 code_expires_at=DATE_ADD(NOW(), INTERVAL ? DAY), approved_at=NOW()
             WHERE id=?"
        );
        $stmt->bind_param('siii', $code, $uses, $days, $id);
        $stmt->execute();
        $stmt->close();

        // Notify the school (best-effort).
        $base = rtrim(BASE_URL, '/');
        $msg  = "EduTrack demo approved! Go to {$base}/demo-access.php and enter code: {$code} "
              . "(valid {$days} days).";
        try {
            if (!empty($row['whatsapp']) && function_exists('sendSMS')) {
                sendSMS($row['whatsapp'], $msg);
            }
            if (!empty($row['email']) && function_exists('sendEmail')) {
                $html = '<p>Hello ' . htmlspecialchars($row['contact_name']) . ',</p>'
                      . '<p>Your EduTrack demo is approved. Enter the system here:</p>'
                      . '<p><a href="' . $base . '/demo-access.php">' . $base . '/demo-access.php</a></p>'
                      . '<p>Your access code: <b style="font-size:1.2em">' . htmlspecialchars($code) . '</b><br>'
                      . 'Valid for ' . $days . ' days.</p><p>— The Oric / EduTrack team</p>';
                sendEmail($row['email'], 'Your EduTrack demo access code', $html);
            }
        } catch (Throwable $e) {
            error_log('Demo approval notify failed: ' . $e->getMessage());
        }
        $flash = '<div class="alert alert-success">Approved. Code <b>' . htmlspecialchars($code)
               . '</b> issued for <b>' . htmlspecialchars($row['school_name']) . '</b>.</div>';
    } elseif ($row && $action === 'reject') {
        $conn->query("UPDATE demo_requests SET status='rejected', access_code=NULL WHERE id=" . $id);
        $flash = '<div class="alert alert-secondary">Request from <b>' . htmlspecialchars($row['school_name']) . '</b> rejected.</div>';
    } elseif ($row && $action === 'revoke') {
        $conn->query("UPDATE demo_requests SET status='pending', access_code=NULL, code_expires_at=NULL WHERE id=" . $id);
        $flash = '<div class="alert alert-warning">Access revoked for <b>' . htmlspecialchars($row['school_name']) . '</b>.</div>';
    }
}

$filter = $_GET['status'] ?? 'all';
$where  = in_array($filter, ['pending', 'approved', 'rejected'], true) ? "WHERE status='" . $filter . "'" : '';
$rows   = $conn->query("SELECT * FROM demo_requests {$where} ORDER BY created_at DESC LIMIT 300");

$counts = ['pending' => 0, 'approved' => 0, 'rejected' => 0];
$cr = $conn->query("SELECT status, COUNT(*) c FROM demo_requests GROUP BY status");
while ($cr && $row = $cr->fetch_assoc()) { $counts[$row['status']] = (int) $row['c']; }

$wa = getDemoWhatsApp();
$base = rtrim(BASE_URL, '/');
$badge = ['pending' => 'warning', 'approved' => 'success', 'rejected' => 'secondary'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Demo Requests — EduTrack Admin</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<style>body{background:#f5f7fa}.code{font-family:monospace;font-weight:700;color:#006168}</style>
</head>
<body>
<div class="container py-4">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h3 class="fw-bold mb-0"><i class="fas fa-inbox me-2 text-info"></i>Demo Requests</h3>
    <a href="../dashboard.php" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Dashboard</a>
  </div>

  <?= $flash ?>

  <div class="btn-group mb-3">
    <a href="?status=all"      class="btn btn-sm btn-<?= $filter==='all'?'dark':'outline-dark' ?>">All</a>
    <a href="?status=pending"  class="btn btn-sm btn-<?= $filter==='pending'?'warning':'outline-warning' ?>">Pending (<?= $counts['pending'] ?>)</a>
    <a href="?status=approved" class="btn btn-sm btn-<?= $filter==='approved'?'success':'outline-success' ?>">Approved (<?= $counts['approved'] ?>)</a>
    <a href="?status=rejected" class="btn btn-sm btn-<?= $filter==='rejected'?'secondary':'outline-secondary' ?>">Rejected (<?= $counts['rejected'] ?>)</a>
  </div>

  <div class="card shadow-sm">
    <div class="table-responsive">
      <table class="table table-hover align-middle mb-0">
        <thead class="table-light">
          <tr><th>School / Contact</th><th>WhatsApp / Email</th><th>Region</th><th>Status</th><th>Code</th><th class="text-end">Actions</th></tr>
        </thead>
        <tbody>
        <?php if (!$rows || $rows->num_rows === 0): ?>
          <tr><td colspan="6" class="text-center text-muted py-4">No requests.</td></tr>
        <?php else: while ($row = $rows->fetch_assoc()):
            $wnum = preg_replace('/\D/', '', $row['whatsapp']);
            if (strpos($wnum, '0') === 0) { $wnum = '233' . substr($wnum, 1); }
            $codeMsg = rawurlencode("Hello {$row['contact_name']}, your EduTrack demo is approved. Visit {$base}/demo-access.php and enter code: {$row['access_code']}");
            $expired = !empty($row['code_expires_at']) && strtotime($row['code_expires_at']) < time();
        ?>
          <tr>
            <td>
              <div class="fw-semibold"><?= htmlspecialchars($row['school_name']) ?></div>
              <small class="text-muted"><?= htmlspecialchars($row['contact_name']) ?><?= $row['role'] ? ' · ' . htmlspecialchars($row['role']) : '' ?></small>
              <?php if ($row['message']): ?><div class="small text-muted fst-italic mt-1">"<?= htmlspecialchars(mb_strimwidth($row['message'],0,90,'…')) ?>"</div><?php endif; ?>
            </td>
            <td>
              <div><?= htmlspecialchars($row['whatsapp']) ?></div>
              <?php if ($row['email']): ?><small class="text-muted"><?= htmlspecialchars($row['email']) ?></small><?php endif; ?>
            </td>
            <td><?= htmlspecialchars($row['region'] ?: '—') ?></td>
            <td><span class="badge bg-<?= $badge[$row['status']] ?? 'light' ?>"><?= ucfirst($row['status']) ?></span></td>
            <td>
              <?php if ($row['access_code']): ?>
                <span class="code"><?= htmlspecialchars($row['access_code']) ?></span><br>
                <small class="text-<?= $expired?'danger':'muted' ?>">
                  <?= $expired ? 'expired' : 'exp ' . date('d M', strtotime($row['code_expires_at'])) ?>
                  · <?= (int)$row['uses_count'] ?>/<?= (int)$row['uses_allowed'] ?> uses
                </small>
              <?php else: ?><span class="text-muted">—</span><?php endif; ?>
            </td>
            <td class="text-end" style="min-width:230px">
              <?php if ($row['status'] !== 'approved'): ?>
                <form method="post" class="d-inline">
                  <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                  <input type="hidden" name="action" value="approve">
                  <button class="btn btn-sm btn-success"><i class="fas fa-check me-1"></i>Approve</button>
                </form>
                <form method="post" class="d-inline" onsubmit="return confirm('Reject this request?')">
                  <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                  <input type="hidden" name="action" value="reject">
                  <button class="btn btn-sm btn-outline-danger"><i class="fas fa-xmark"></i></button>
                </form>
              <?php else: ?>
                <a href="https://wa.me/<?= $wnum ?>?text=<?= $codeMsg ?>" target="_blank" rel="noopener" class="btn btn-sm btn-success"><i class="fab fa-whatsapp me-1"></i>Send code</a>
                <form method="post" class="d-inline">
                  <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                  <input type="hidden" name="action" value="regenerate">
                  <button class="btn btn-sm btn-outline-primary" title="New code"><i class="fas fa-rotate"></i></button>
                </form>
                <form method="post" class="d-inline" onsubmit="return confirm('Revoke access?')">
                  <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                  <input type="hidden" name="action" value="revoke">
                  <button class="btn btn-sm btn-outline-warning" title="Revoke"><i class="fas fa-ban"></i></button>
                </form>
              <?php endif; ?>
            </td>
          </tr>
        <?php endwhile; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
  <p class="text-muted small mt-3"><i class="fas fa-shield-halved me-1"></i>Approving issues a code and (if configured) auto-sends it by SMS/email. Use <b>Send code</b> to message via WhatsApp.</p>
</div>
</body>
</html>
