<?php
// ============================================================
// admin-applications.php — RBE Utilities Agent Applications
// ============================================================

require_once __DIR__ . '/core/db_connect.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf_token = $_SESSION['csrf_token'];

$flash_ok = $flash_err = "";

// ------------------------------------------------------------
// Handle Approve / Reject Actions
// ------------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['agent_action'])) {
    $action = $_POST['agent_action'];
    $app_id = (int)($_POST['app_id'] ?? 0);
    $csrf   = $_POST['csrf_token'] ?? '';

    if (!hash_equals($_SESSION['csrf_token'], $csrf)) {
        $flash_err = 'Invalid session token. Please refresh.';
    } elseif (!$app_id) {
        $flash_err = 'Invalid application ID.';
    } else {
        try {
            $conn_rbe->beginTransaction();

            $s = $conn_rbe->prepare("
                SELECT id, user_id, fullname, email, phone, status
                FROM agent_applications
                WHERE id = ? LIMIT 1
            ");
            $s->execute([$app_id]);
            $app = $s->fetch(PDO::FETCH_ASSOC);

            if (!$app) throw new RuntimeException('Application not found.');
            if (!in_array($app['status'], ['pending','review'], true)) throw new RuntimeException('Already processed.');

            if ($action === 'approve') {
                $conn_rbe->prepare("UPDATE agent_applications SET status='approved', updated_at=NOW() WHERE id=?")
                         ->execute([$app_id]);

                // Ensure user exists and has agent role
                $conn_rbe->prepare("
                    INSERT INTO rbe_users (id, fullname, email, phone, is_deleted)
                    VALUES (?, ?, ?, ?, 0)
                    ON DUPLICATE KEY UPDATE fullname=VALUES(fullname), phone=VALUES(phone), is_deleted=0
                ")->execute([(int)$app['user_id'], $app['fullname'], $app['email'], $app['phone']]);

                $exists = $conn_rbe->prepare("SELECT 1 FROM rbe_roles WHERE user_id=? AND role='agent' LIMIT 1");
                $exists->execute([(int)$app['user_id']]);
                if (!$exists->fetchColumn()) {
                    $conn_rbe->prepare("INSERT INTO rbe_roles (user_id, role) VALUES (?, 'agent')")
                             ->execute([(int)$app['user_id']]);
                }

                $flash_ok = '✅ Agent application approved.';
            } elseif ($action === 'reject') {
                $conn_rbe->prepare("UPDATE agent_applications SET status='rejected', updated_at=NOW() WHERE id=?")
                         ->execute([$app_id]);
                $flash_ok = '❌ Agent application rejected.';
            }

            $conn_rbe->commit();
        } catch (Throwable $e) {
            if ($conn_rbe->inTransaction()) $conn_rbe->rollBack();
            $flash_err = 'Error: '.$e->getMessage();
        }
    }
}

// ------------------------------------------------------------
// Pagination & Search
// ------------------------------------------------------------
$limit = 10;
$page  = isset($_GET['page_apps']) ? max(1, (int)$_GET['page_apps']) : 1;
$offset = ($page - 1) * $limit;

$search_email = trim($_GET['search_email'] ?? '');
$where = "status IN ('pending','review')";
$params = [];
if ($search_email !== '') {
    $where .= " AND email LIKE :em";
    $params[':em'] = "%$search_email%";
}

$total = $conn_rbe->prepare("SELECT COUNT(*) FROM agent_applications WHERE $where");
$total->execute($params);
$total_rows = (int)$total->fetchColumn();
$total_pages = max(1, ceil($total_rows / $limit));

$stmt = $conn_rbe->prepare("
    SELECT id, user_id, fullname, email, phone, company, website, notes, status, created_at
    FROM agent_applications
    WHERE $where
    ORDER BY created_at DESC
    LIMIT $limit OFFSET $offset
");
$stmt->execute($params);
?>

<main class="dashboard-content">
<div class="section applications-section">
  <h2>📩 Agent Applications (Pending / Review)</h2>

  <?php if ($flash_ok): ?>
    <div class="alert ok"><?= htmlspecialchars($flash_ok) ?></div>
  <?php elseif ($flash_err): ?>
    <div class="alert err"><?= htmlspecialchars($flash_err) ?></div>
  <?php endif; ?>

  <!-- Search bar -->
  <form method="get" class="search-bar">
    <input type="text" name="search_email" placeholder="Filter by email…" 
           value="<?= htmlspecialchars($search_email) ?>">
    <button type="submit" class="btn-primary">Search</button>
  </form>

  <table>
    <tr>
      <th>Applicant</th>
      <th>Contact</th>
      <th>Company</th>
      <th>Website</th>
      <th>Applied</th>
      <th>Actions</th>
    </tr>
    <?php while ($app = $stmt->fetch(PDO::FETCH_ASSOC)): ?>
    <tr>
      <td>
        <strong><?= htmlspecialchars($app['fullname']) ?></strong><br>
        <span class="mut"><?= htmlspecialchars($app['notes'] ?: '—') ?></span>
      </td>
      <td>
        <?= htmlspecialchars($app['email']) ?><br>
        <?= htmlspecialchars($app['phone']) ?>
      </td>
      <td><?= htmlspecialchars($app['company'] ?: '—') ?></td>
      <td>
        <?php if (!empty($app['website'])): ?>
          <a href="<?= htmlspecialchars($app['website']) ?>" target="_blank" rel="noopener">Visit</a>
        <?php else: ?>
          —
        <?php endif; ?>
      </td>
      <td><?= htmlspecialchars($app['created_at']) ?></td>
      <td class="actions">
        <form method="post">
          <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf_token) ?>">
          <input type="hidden" name="app_id" value="<?= (int)$app['id'] ?>">
          <button type="submit" name="agent_action" value="approve" class="btn-approve">Approve</button>
        </form>
        <form method="post">
          <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf_token) ?>">
          <input type="hidden" name="app_id" value="<?= (int)$app['id'] ?>">
          <button type="submit" name="agent_action" value="reject" class="btn-reject">Reject</button>
        </form>
      </td>
    </tr>
    <?php endwhile; ?>
  </table>

  <!-- Pagination -->
  <div class="pagination">
    <?php if ($page > 1): ?>
      <a href="?page_apps=<?= $page - 1 ?>&search_email=<?= urlencode($search_email) ?>">« Prev</a>
    <?php endif; ?>
    <span>Page <?= $page ?> of <?= $total_pages ?></span>
    <?php if ($page < $total_pages): ?>
      <a href="?page_apps=<?= $page + 1 ?>&search_email=<?= urlencode($search_email) ?>">Next »</a>
    <?php endif; ?>
  </div>
</div>
</main>

<!-- ==========================================================
     STYLING
     ========================================================== -->
<style>
.dashboard-content {
  margin-left: 240px;
  padding: 40px 30px;
  color: #e6f5ff;
}

.applications-section {
  background: #0b2333;
  border-radius: 16px;
  padding: 25px;
  margin: 85px auto;
  box-shadow: 0 0 18px rgba(0,0,0,0.4);
  max-width: 1200px;
}

.applications-section h2 {
  color: var(--accent2, #00ccff);
  text-align: center;
  margin-bottom: 20px;
}

/* Alerts */
.alert {
  text-align: center;
  padding: 10px 15px;
  border-radius: 8px;
  margin-bottom: 20px;
  font-weight: 500;
}
.alert.ok { background:#0f3b2a; color:#b6ffcf; border:1px solid #176546; }
.alert.err { background:#3b0f0f; color:#ffd6d6; border:1px solid #6b1a1a; }

/* Search */
.search-bar {
  text-align: center;
  margin-bottom: 20px;
}
.search-bar input {
  padding: 8px 10px;
  width: 240px;
  border-radius: 8px;
  border: none;
  background: #122c4c;
  color: #e6f5ff;
}
.search-bar input::placeholder { color: #9bb5c7; }
.btn-primary {
  background: var(--accent, #7ed957);
  color: #041622;
  font-weight: 600;
  padding: 8px 16px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  margin-left: 8px;
  transition: all 0.25s ease;
}
.btn-primary:hover { background: #00cc77; }

/* Table */
table {
  width: 100%;
  border-collapse: collapse;
  background: #122c4c;
  color: #e6f5ff;
  border-radius: 10px;
  overflow: hidden;
}
table th, table td {
  text-align: center;
  padding: 12px;
  border-bottom: 1px solid #1b3a4d;
}
table th {
  background: #0f2536;
  color: var(--accent2, #00ccff);
  font-weight: 600;
}
table tr:hover { background-color: #1a3e57; }
.mut { font-size: 0.85em; color: #9bb5c7; }

/* Buttons */
.btn-approve, .btn-reject {
  padding: 6px 12px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 600;
  transition: all 0.25s ease;
  width: 90px;
}
.btn-approve {
  background: var(--accent, #7ed957);
  color: #041622;
}
.btn-approve:hover { background: #00cc77; }
.btn-reject {
  background: #b54646;
  color: #fff;
}
.btn-reject:hover { background: #ff5b5b; }

.actions form { display: inline-block; margin: 4px; }

.pagination {
  text-align: center;
  margin-top: 20px;
}
.pagination a {
  color: var(--accent2, #00ccff);
  text-decoration: none;
  margin: 0 8px;
  font-weight: 500;
}
.pagination a:hover {
  text-decoration: underline;
  color: #7ed957;
}

@media (max-width: 768px) {
  .dashboard-content { margin-left: 80px; padding: 25px 15px; }
  table th, table td { font-size: 0.9em; padding: 8px; }
  .btn-approve, .btn-reject { width: 80px; padding: 5px 8px; font-size: 0.85em; }
}
</style>

<!-- ==========================================================
     JS: fade out alerts
     ========================================================== -->
<script>
document.addEventListener("DOMContentLoaded", () => {
  const alert = document.querySelector(".alert");
  if (alert) {
    setTimeout(() => {
      alert.style.transition = "opacity 0.6s ease";
      alert.style.opacity = "0";
      setTimeout(() => alert.remove(), 600);
    }, 4000);
  }
});
</script>
