<?php
require_once __DIR__ . '/../config.php';
superAdminGuard();
requireCsrf();  // reject POSTs without a valid CSRF token
require_once __DIR__ . '/_layout.php';

$db    = db();
$msg   = '';
$error = '';

// Load super admin's own data for sending emails
$saRow = $db->prepare('SELECT * FROM admins WHERE id=?');
$saRow->execute([$_SESSION['admin_id']]);
$superAdmin = $saRow->fetch();

// ── Helper: send activation email ──────────────────────────
function sendActivationEmail(array $superAdmin, string $toEmail, string $toName,
                              string $token): bool {
    $link = BASE_URL . '/admin/activate.php?token=' . urlencode($token);
    $html = buildEmailHtml(
        $toName,
        'RSVP Event Management',
        "You have been invited to manage events on the RSVP platform.\n\n"
        . "Click the button below to activate your account and create your password. "
        . "This link is valid for 72 hours.",
        $link
    );
    // Replace the generic "View Your Ticket" button label in the built HTML
    $html = str_replace('View Your Ticket', 'Activate My Account', $html);
    return sendMail($superAdmin, $toEmail,
                    'Activate your RSVP Admin account', $html);
}

// ── Handle form submissions ─────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // ── Create admin ────────────────────────────────────────
    if (isset($_POST['create_admin'])) {
        $name  = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $maxEv = ($_POST['max_events'] ?? '') !== '' ? (int)$_POST['max_events'] : null;
        $maxGu = ($_POST['max_guests'] ?? '') !== '' ? (int)$_POST['max_guests'] : null;

        if (!$name || !$email) {
            $error = 'Name and email are required.';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Invalid email address.';
        } else {
            $dup = $db->prepare('SELECT id FROM admins WHERE email = ?');
            $dup->execute([$email]);
            if ($dup->fetch()) {
                $error = 'An admin with that email already exists.';
            } else {
                $token = bin2hex(random_bytes(32)); // 64-char hex
                $db->prepare(
                    'INSERT INTO admins
                     (name, email, password, role, status, activation_token, max_events, max_guests)
                     VALUES (?, ?, \'\', \'admin\', \'pending\', ?, ?, ?)'
                )->execute([$name, $email, $token, $maxEv, $maxGu]);
                adminLog('admin.create', 'admin', (int)$db->lastInsertId(), $email);

                $sent = sendActivationEmail($superAdmin, $email, $name, $token);
                $activationLink = BASE_URL . '/admin/activate.php?token=' . urlencode($token);

                if ($sent) {
                    $msg = "Admin account created and activation email sent to <strong>{$email}</strong>.";
                } else {
                    $msg = "Admin account created. Email could not be delivered — share this activation link manually:<br>"
                         . "<code style='word-break:break-all;color:var(--gold)'>{$activationLink}</code>";
                }
            }
        }
    }

    // ── Resend activation email ──────────────────────────────
    if (isset($_POST['resend_activation'])) {
        $id = (int)$_POST['admin_id'];
        $s  = $db->prepare('SELECT * FROM admins WHERE id=? AND role=\'admin\' AND status=\'pending\'');
        $s->execute([$id]);
        $a = $s->fetch();
        if ($a) {
            // Regenerate token for security
            $token = bin2hex(random_bytes(32));
            $db->prepare('UPDATE admins SET activation_token=? WHERE id=?')->execute([$token, $id]);
            $sent = sendActivationEmail($superAdmin, $a['email'], $a['name'], $token);
            $activationLink = BASE_URL . '/admin/activate.php?token=' . urlencode($token);
            if ($sent) {
                $msg = "Activation email resent to <strong>{$a['email']}</strong>.";
            } else {
                $msg = "Could not deliver email. Share this link manually:<br>"
                     . "<code style='word-break:break-all;color:var(--gold)'>{$activationLink}</code>";
            }
        } else {
            $error = 'Account not found or already activated.';
        }
    }

    // ── Update admin ────────────────────────────────────────
    if (isset($_POST['update_admin'])) {
        $id    = (int)$_POST['admin_id'];
        $name  = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $maxEv = ($_POST['max_events'] ?? '') !== '' ? (int)$_POST['max_events'] : null;
        $maxGu = ($_POST['max_guests'] ?? '') !== '' ? (int)$_POST['max_guests'] : null;

        if (!$name || !$email) {
            $error = 'Name and email are required.';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Invalid email address.';
        } elseif ($id === (int)$_SESSION['admin_id']) {
            $error = 'Edit your own account via Account Settings.';
        } else {
            $dup = $db->prepare('SELECT id FROM admins WHERE email = ? AND id != ?');
            $dup->execute([$email, $id]);
            if ($dup->fetch()) {
                $error = 'Another admin already uses that email.';
            } else {
                $newPass = $_POST['new_password'] ?? '';
                if ($newPass !== '') {
                    if (strlen($newPass) < 6) {
                        $error = 'New password must be at least 6 characters.';
                    } else {
                        $hash = password_hash($newPass, PASSWORD_BCRYPT);
                        // Setting a password also activates the account
                        $db->prepare(
                            'UPDATE admins SET password=?, status=\'active\', activation_token=NULL WHERE id=? AND role=\'admin\''
                        )->execute([$hash, $id]);
                    }
                }
                if (!$error) {
                    $db->prepare(
                        'UPDATE admins SET name=?, email=?, max_events=?, max_guests=?
                         WHERE id=? AND role=\'admin\''
                    )->execute([$name, $email, $maxEv, $maxGu, $id]);
                    $msg = 'Admin updated successfully.';
                }
            }
        }
    }

    // ── Delete admin ────────────────────────────────────────
    if (isset($_POST['delete_admin'])) {
        $id = (int)$_POST['admin_id'];
        if ($id === (int)$_SESSION['admin_id']) {
            $error = 'You cannot delete your own account.';
        } else {
            $db->prepare('DELETE FROM admins WHERE id=? AND role=\'admin\'')->execute([$id]);
            adminLog('admin.delete', 'admin', $id);
            header('Location: ' . BASE_URL . '/admin/manage_admins.php?msg=deleted');
            exit;
        }
    }
}

if (isset($_GET['msg']) && $_GET['msg'] === 'deleted') {
    $msg = 'Admin account deleted.';
}

// ── Load admins list ────────────────────────────────────────
$stmtList = $db->prepare(
    'SELECT a.*, COUNT(DISTINCT e.id) AS event_count
     FROM admins a
     LEFT JOIN events e ON e.admin_id = a.id
     WHERE a.role = \'admin\'
     GROUP BY a.id
     ORDER BY a.created_at DESC'
);
$stmtList->execute();
$adminList = $stmtList->fetchAll();

// ── Load single admin for edit ──────────────────────────────
$editAdmin = null;
if (isset($_GET['edit'])) {
    $s = $db->prepare('SELECT * FROM admins WHERE id=? AND role=\'admin\'');
    $s->execute([(int)$_GET['edit']]);
    $editAdmin = $s->fetch();
}

layout_start('Manage Admins', 'manage_admins');
?>

<?php if ($msg): ?><div class="alert alert-success"><?= $msg ?></div><?php endif; ?>
<?php if ($error): ?><div class="alert alert-danger"><?= htmlspecialchars($error) ?></div><?php endif; ?>

<!-- ── Page Header ─────────────────────────────────────────── -->
<div class="page-header">
  <div>
    <div class="page-header-sub">Super Admin</div>
    <h1>Manage Admins</h1>
  </div>
  <?php if (!$editAdmin): ?>
  <button class="btn btn-gold" onclick="document.getElementById('create-form').scrollIntoView({behavior:'smooth'})">
    + New Admin
  </button>
  <?php else: ?>
  <a href="<?= BASE_URL ?>/admin/manage_admins.php" class="btn btn-outline btn-sm">← Back to List</a>
  <?php endif; ?>
</div>

<?php if ($editAdmin): ?>

<!-- ── Edit Admin Form ─────────────────────────────────────── -->
<div class="card" style="max-width:620px">
  <div class="label-ui mb-1">Edit Admin</div>
  <div style="font-size:.85rem;color:var(--muted);margin-bottom:20px">
    <?= htmlspecialchars($editAdmin['name']) ?>
    <?php if ($editAdmin['status'] === 'pending'): ?>
      <span class="badge badge-muted" style="margin-left:8px">Pending Activation</span>
    <?php else: ?>
      <span class="badge badge-success" style="margin-left:8px">Active</span>
    <?php endif; ?>
  </div>

  <?php if ($editAdmin['status'] === 'pending'): ?>
  <div class="alert alert-info" style="margin-bottom:20px;font-size:.85rem">
    This account is waiting for the admin to set their password via the activation email.
    <form method="POST" style="display:inline;margin-left:8px">
      <input type="hidden" name="admin_id" value="<?= $editAdmin['id'] ?>">
      <button class="btn btn-outline btn-sm" name="resend_activation" type="submit">Resend Activation Email</button>
    </form>
  </div>
  <?php endif; ?>

  <form method="POST">
    <input type="hidden" name="admin_id" value="<?= $editAdmin['id'] ?>">

    <div class="grid-2">
      <div class="form-group">
        <label class="form-label">Full Name *</label>
        <input class="form-control" type="text" name="name"
               value="<?= htmlspecialchars($editAdmin['name']) ?>" required>
      </div>
      <div class="form-group">
        <label class="form-label">Email Address *</label>
        <input class="form-control" type="email" name="email"
               value="<?= htmlspecialchars($editAdmin['email']) ?>" required>
      </div>
    </div>

    <div class="grid-2">
      <div class="form-group">
        <label class="form-label">Max Events</label>
        <input class="form-control" type="number" name="max_events" min="0"
               value="<?= $editAdmin['max_events'] !== null ? (int)$editAdmin['max_events'] : '' ?>"
               placeholder="Leave blank for unlimited">
        <div class="form-hint">Max events this admin can create. Blank = unlimited.</div>
      </div>
      <div class="form-group">
        <label class="form-label">Max Guests Per Event</label>
        <input class="form-control" type="number" name="max_guests" min="0"
               value="<?= $editAdmin['max_guests'] !== null ? (int)$editAdmin['max_guests'] : '' ?>"
               placeholder="Leave blank for unlimited">
        <div class="form-hint">Max guests allowed per event. Blank = unlimited.</div>
      </div>
    </div>

    <div class="form-group">
      <label class="form-label">
        Set Password
        <span class="text-muted" style="font-weight:400">
          <?= $editAdmin['status'] === 'pending' ? '— sets password and activates account' : '— leave blank to keep current' ?>
        </span>
      </label>
      <input class="form-control" type="password" name="new_password"
             autocomplete="new-password" placeholder="Min 6 characters">
    </div>

    <div class="flex gap-2">
      <button class="btn btn-gold" name="update_admin" type="submit">Save Changes</button>
      <a href="<?= BASE_URL ?>/admin/manage_admins.php" class="btn btn-outline">Cancel</a>
    </div>
  </form>
</div>

<?php else: ?>

<!-- ── Admins Table ────────────────────────────────────────── -->
<div class="card mb-4">
  <div class="table-wrap">
    <table>
      <thead>
        <tr>
          <th>Name / Status</th>
          <th>Email</th>
          <th>Max Events</th>
          <th>Max Guests/Event</th>
          <th>Events Created</th>
          <th>Joined</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <?php if (empty($adminList)): ?>
          <tr>
            <td colspan="7" class="text-muted" style="padding:32px;text-align:center">
              No admin accounts yet. <a href="#create-form" style="color:var(--gold)">Create one below</a>.
            </td>
          </tr>
        <?php endif; ?>
        <?php foreach ($adminList as $a): ?>
        <tr>
          <td>
            <div style="font-weight:500"><?= htmlspecialchars($a['name']) ?></div>
            <?php if ($a['status'] === 'pending'): ?>
              <span class="badge badge-muted" style="font-size:.65rem">Pending Activation</span>
            <?php else: ?>
              <span class="badge badge-success" style="font-size:.65rem">Active</span>
            <?php endif; ?>
          </td>
          <td class="text-muted text-sm"><?= htmlspecialchars($a['email']) ?></td>
          <td>
            <?php if ($a['max_events'] !== null): ?>
              <span style="color:var(--gold);font-weight:600"><?= (int)$a['max_events'] ?></span>
              <span class="text-muted text-sm"> limit</span>
            <?php else: ?>
              <span class="text-muted">Unlimited</span>
            <?php endif; ?>
          </td>
          <td>
            <?php if ($a['max_guests'] !== null): ?>
              <span style="color:var(--gold);font-weight:600"><?= (int)$a['max_guests'] ?></span>
              <span class="text-muted text-sm"> limit</span>
            <?php else: ?>
              <span class="text-muted">Unlimited</span>
            <?php endif; ?>
          </td>
          <td>
            <?= (int)$a['event_count'] ?>
            <?php if ($a['max_events'] !== null): ?>
              <span class="text-muted text-sm">/ <?= (int)$a['max_events'] ?></span>
            <?php endif; ?>
          </td>
          <td class="text-muted text-sm"><?= date('M j, Y', strtotime($a['created_at'])) ?></td>
          <td style="white-space:nowrap">
            <?php if ($a['status'] === 'pending'): ?>
            <form method="POST" style="display:inline">
              <input type="hidden" name="admin_id" value="<?= $a['id'] ?>">
              <button class="btn btn-outline btn-sm" name="resend_activation" type="submit"
                      title="Resend activation email">Resend</button>
            </form>
            <?php endif; ?>
            <a href="?edit=<?= $a['id'] ?>" class="btn btn-outline btn-sm">Edit</a>
            <form method="POST" style="display:inline"
                  onsubmit="return confirm('Delete admin &quot;<?= htmlspecialchars(addslashes($a['name'])) ?>&quot;? Their events and guests will also be deleted.')">
              <input type="hidden" name="admin_id" value="<?= $a['id'] ?>">
              <button class="btn btn-danger btn-sm" name="delete_admin" type="submit">Delete</button>
            </form>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- ── Create Admin Form ───────────────────────────────────── -->
<div class="card" id="create-form" style="max-width:620px">
  <div class="label-ui mb-1">Create New Admin</div>
  <p class="text-muted text-sm" style="margin-bottom:20px">
    An activation email will be sent to the admin so they can set their own password.
  </p>
  <form method="POST">
    <div class="grid-2">
      <div class="form-group">
        <label class="form-label">Full Name *</label>
        <input class="form-control" type="text" name="name"
               value="<?= htmlspecialchars($_POST['name'] ?? '') ?>" required>
      </div>
      <div class="form-group">
        <label class="form-label">Email Address *</label>
        <input class="form-control" type="email" name="email"
               value="<?= htmlspecialchars($_POST['email'] ?? '') ?>" required>
      </div>
    </div>

    <div class="grid-2">
      <div class="form-group">
        <label class="form-label">Max Events</label>
        <input class="form-control" type="number" name="max_events" min="0"
               value="<?= htmlspecialchars($_POST['max_events'] ?? '') ?>"
               placeholder="Leave blank for unlimited">
        <div class="form-hint">Max events this admin can create. Blank = unlimited.</div>
      </div>
      <div class="form-group">
        <label class="form-label">Max Guests Per Event</label>
        <input class="form-control" type="number" name="max_guests" min="0"
               value="<?= htmlspecialchars($_POST['max_guests'] ?? '') ?>"
               placeholder="Leave blank for unlimited">
        <div class="form-hint">Max guests allowed per event. Blank = unlimited.</div>
      </div>
    </div>

    <button class="btn btn-gold" name="create_admin" type="submit">Create Admin &amp; Send Invite</button>
  </form>
</div>

<?php endif; ?>

<?php layout_end(); ?>
