<?php
// admin/reviewer_applications.php
if (session_status() === PHP_SESSION_NONE) session_start();
include __DIR__ . '/config/db.php';
include __DIR__ . '/config/auth.php';
require_page_access();

$admin_name = $_SESSION['admin_name'] ?? 'Admin';
$admin_role = $_SESSION['admin_role'] ?? 'admin';

// ── Helper: sync reviewer to users table ─────────────────────
function syncReviewerToUsers(PDO $pdo, array $app): ?int {
    $instEmail = trim($app['institutional_email'] ?? '');
    $personalEmail = trim($app['personal_email'] ?? '');
    $email = '';
    if (filter_var($instEmail, FILTER_VALIDATE_EMAIL)) $email = $instEmail;
    elseif (filter_var($personalEmail, FILTER_VALIDATE_EMAIL)) $email = $personalEmail;
    if (!$email) return null;

    $parts = explode(' ', trim($app['full_name'] ?? ''), 2);
    $firstName = $parts[0] ?? 'Reviewer';
    $lastName = $parts[1] ?? '';
    $title = $app['salutation'] ?? '';

    // Ensure role column exists
    try {
        $pdo->exec("ALTER TABLE users ADD COLUMN IF NOT EXISTS
            role ENUM('author','reviewer','editor','both','other') NOT NULL DEFAULT 'author'");
    } catch (PDOException $e) {}

    $q = $pdo->prepare("SELECT user_id, role FROM users WHERE email = ? LIMIT 1");
    $q->execute([$email]);
    $existing = $q->fetch();

    $user_id = null;
    if ($existing) {
        $user_id = (int)$existing['user_id'];
        // $currentRole = $existing['role'] ?? 'author';
        // $newRole = ($currentRole === 'author') ? 'both' : $currentRole;
        // if (!in_array($currentRole, ['reviewer', 'editor', 'both'])) $newRole = 'reviewer';
        
        $currentRole = $existing['role'] ?? 'author';

        // If already has reviewer access, don't downgrade
        if (in_array($currentRole, ['reviewer', 'editor', 'both'])) {
            $newRole = $currentRole; // no change needed
        } elseif ($currentRole === 'author') {
            $newRole = 'both'; // author + reviewer = both
        } else {
            $newRole = 'reviewer'; // other/unknown roles become reviewer
        }

        $pdo->prepare("UPDATE users SET role=?, updated_at=NOW() WHERE user_id=?")
            ->execute([$newRole, $user_id]);
    } else {
        // Create new user with reviewer role
        $tempHash = password_hash(bin2hex(random_bytes(8)), PASSWORD_BCRYPT);

        foreach ([
            'is_email_verified TINYINT(1) NOT NULL DEFAULT 0',
            'email_verify_token VARCHAR(100) NULL',
            'email_verify_expires DATETIME NULL',
            'password_reset_token VARCHAR(100) NULL',
            'password_reset_expires DATETIME NULL',
        ] as $col) {
            try { $pdo->exec("ALTER TABLE users ADD COLUMN IF NOT EXISTS $col"); } catch (PDOException $e) {}
        }

        $pdo->prepare(
            "INSERT INTO users
             (email, password_hash, first_name, last_name, title,
              role, is_active, is_email_verified, created_at, updated_at)
             VALUES (?,?,?,?,?,'reviewer',1,1,NOW(),NOW())"
        )->execute([$email, $tempHash, $firstName, $lastName, $title]);

        $user_id = (int)$pdo->lastInsertId();
    }
    return $user_id;
}

// ── Helper: insert user to reviewers table ────────────────────
function createReviewerProfile(PDO $pdo, ?int $user_id, array $app): void {
    if (!$user_id) return;

    // Prevent duplicate reviewer entry
    $check = $pdo->prepare("SELECT id FROM reviewers WHERE user_id = ?");
    $check->execute([$user_id]);
    if ($check->fetch()) return;

    $research_areas = json_encode(parseJson($app['research_areas'] ?? []));

    // FIXED: Statically save "Website Form" for all reviewers coming from website application form
    $reviewer_come_from = 'Website Form';

    $pdo->prepare("
        INSERT INTO reviewers (
            user_id,
            reviewer_come_from,
            reviewing_interests,
            max_reviews_per_period,
            preferred_review_duration_days,
            reviewer_rating,
            total_reviews_completed,
            total_reviews_declined,
            total_reviews_cancelled,
            avg_days_to_complete,
            is_available,
            created_at
        ) VALUES (
            ?, ?, ?, 0, 0, 0.00, 0, 0, 0, 0.00, 1, NOW()
        )
    ")->execute([
        $user_id,
        $reviewer_come_from,     // Static value as requested
        $research_areas,
    ]);
}

// ── Helper: revert reviewer role on reject ────────────────────
function revertReviewerRole(PDO $pdo, array $app): void {
    $instEmail = trim($app['institutional_email'] ?? '');
    $personalEmail = trim($app['personal_email'] ?? '');
    $email = '';
    if (filter_var($instEmail, FILTER_VALIDATE_EMAIL)) $email = $instEmail;
    elseif (filter_var($personalEmail, FILTER_VALIDATE_EMAIL)) $email = $personalEmail;
    if (!$email) return;

    try {
        // $pdo->prepare(
        //     "UPDATE users SET role='author', updated_at=NOW()
        //      WHERE email=? AND role IN ('reviewer','both')"
        // )->execute([$email]);
        // If role is 'both' → revert to 'author' (keep author, remove reviewer)
        // If role is 'reviewer' → revert to 'author' (they only had reviewer)
        $pdo->prepare(
            "UPDATE users SET 
                role = CASE 
                    WHEN role = 'both' THEN 'author'
                    WHEN role = 'reviewer' THEN 'author'
                    ELSE role 
                END,
                updated_at = NOW()
             WHERE email = ? AND role IN ('reviewer', 'both')"
        )->execute([$email]);
    } catch (PDOException $e) {}
}

// ── Status update action ──────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'], $_POST['id'])) {
    $id = (int)$_POST['id'];
    $action = $_POST['action'];
    $statusMap = ['approve' => 1, 'reject' => 2, 'pending' => 0];

    if (isset($statusMap[$action])) {
        $pdo->prepare("UPDATE review_application SET status = ?, updated_at = NOW() WHERE id = ?")
            ->execute([$statusMap[$action], $id]);

        $appRow = $pdo->prepare("SELECT * FROM review_application WHERE id = ?");
        $appRow->execute([$id]);
        $appData = $appRow->fetch(PDO::FETCH_ASSOC);

        // if ($appData) {
        //     if ($action === 'approve') {
        //         $user_id = syncReviewerToUsers($pdo, $appData);
        //         createReviewerProfile($pdo, $user_id, $appData);
        //     } elseif ($action === 'reject') {
        //         revertReviewerRole($pdo, $appData);

        //         $instEmail = trim($appData['institutional_email'] ?? '');
        //         $personalEmail = trim($appData['personal_email'] ?? '');
        //         $email = '';
        //         if (filter_var($instEmail, FILTER_VALIDATE_EMAIL)) $email = $instEmail;
        //         elseif (filter_var($personalEmail, FILTER_VALIDATE_EMAIL)) $email = $personalEmail;

        //         if ($email) {
        //             $q = $pdo->prepare("SELECT user_id FROM users WHERE email=? LIMIT 1");
        //             $q->execute([$email]);
        //             $u = $q->fetch();
        //             // if ($u) {
        //             //     $pdo->prepare("DELETE FROM reviewers WHERE user_id=?")->execute([$u['user_id']]);
        //             // }
        //             if ($u) {
        //                 $pdo->prepare("DELETE FROM reviewers WHERE user_id=?")
        //                     ->execute([$u['user_id']]);
                        
        //                 // Also ensure role is correct after reviewers row deletion
        //                 // 'both' → 'author', 'reviewer' → 'author'
        //                 $pdo->prepare(
        //                     "UPDATE users SET role = 'author', updated_at = NOW()
        //                      WHERE user_id = ? AND role IN ('reviewer', 'both')"
        //                 )->execute([$u['user_id']]);
        //             }
        //         }
        //     }
        // }
        
        if ($appData) {
                if ($action === 'approve') {
                    $user_id = syncReviewerToUsers($pdo, $appData);
                    createReviewerProfile($pdo, $user_id, $appData);
            
                } elseif ($action === 'reject') {
            
                    // ── Resolve email from application ──────────────────
                    $instEmail     = trim($appData['institutional_email'] ?? '');
                    $personalEmail = trim($appData['personal_email'] ?? '');
                    $email = '';
                    if (filter_var($instEmail,     FILTER_VALIDATE_EMAIL)) $email = $instEmail;
                    elseif (filter_var($personalEmail, FILTER_VALIDATE_EMAIL)) $email = $personalEmail;
            
                    // ── Safety: only revert if NO OTHER approved application exists for this email ──
                    $otherApproved = false;
                    if ($email) {
                        $oa = $pdo->prepare(
                            "SELECT COUNT(*) FROM review_application
                             WHERE (institutional_email = ? OR personal_email = ?)
                             AND status = 1
                             AND id != ?"
                        );
                        $oa->execute([$email, $email, $id]);
                        $otherApproved = (int)$oa->fetchColumn() > 0;
                    }
            
                    if (!$otherApproved) {
                        // Safe to revert — no other approved application for this person
                        revertReviewerRole($pdo, $appData);
            
                        if ($email) {
                            $q = $pdo->prepare("SELECT user_id FROM users WHERE email = ? LIMIT 1");
                            $q->execute([$email]);
                            $u = $q->fetch();
            
                            if ($u) {
                                // Remove reviewer record
                                $pdo->prepare("DELETE FROM reviewers WHERE user_id = ?")
                                    ->execute([$u['user_id']]);
            
                                // Ensure role is correctly reverted
                                // 'both' → 'author', 'reviewer' → 'author', editor untouched
                                $pdo->prepare(
                                    "UPDATE users SET role = 'author', updated_at = NOW()
                                     WHERE user_id = ? AND role IN ('reviewer', 'both')"
                                )->execute([$u['user_id']]);
                            }
                        }
                    }
                    // If $otherApproved = true, skip everything — user keeps their reviewer access
                }
            }
    }

    header("Location: " . $_SERVER['PHP_SELF'] . "?" . http_build_query(array_diff_key($_GET, ['msg' => ''])) . "&msg=" . $action);
    exit;
}

// ── Filters ───────────────────────────────────────────────────
$status_filter = $_GET['status'] ?? '';
$journal_filter = $_GET['journal'] ?? '';
$search = trim($_GET['search'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));
$per_page = 15;
$offset = ($page - 1) * $per_page;

$where = ['1=1'];
$params = [];

if ($status_filter !== '') {
    $where[] = 'ra.status = ?';
    $params[] = (int)$status_filter;
}
if ($journal_filter !== '') {
    $where[] = 'ra.journal_id = ?';
    $params[] = (int)$journal_filter;
}
if ($search !== '') {
    $where[] = '(ra.full_name LIKE ? OR ra.institutional_email LIKE ? OR ra.application_id LIKE ? OR ra.country LIKE ?)';
    $s = "%$search%";
    $params = array_merge($params, [$s, $s, $s, $s]);
}

$whereSQL = implode(' AND ', $where);

$countStmt = $pdo->prepare("SELECT COUNT(*) FROM review_application ra WHERE $whereSQL");
$countStmt->execute($params);
$total_rows = (int)$countStmt->fetchColumn();
$total_pages = (int)ceil($total_rows / $per_page);

$stmt = $pdo->prepare("
    SELECT ra.*
    FROM review_application ra
    WHERE $whereSQL
    ORDER BY ra.created_at DESC
    LIMIT $per_page OFFSET $offset
");
$stmt->execute($params);
$applications = $stmt->fetchAll(PDO::FETCH_ASSOC);

$counts = $pdo->query("
    SELECT
        COUNT(*) AS total,
        SUM(status = 0) AS pending,
        SUM(status = 1) AS approved,
        SUM(status = 2) AS rejected
    FROM review_application
")->fetch(PDO::FETCH_ASSOC);

$journals = $pdo->query("SELECT DISTINCT journal_id FROM review_application ORDER BY journal_id")
                ->fetchAll(PDO::FETCH_COLUMN);

// ── View helpers ──────────────────────────────────────────────
function statusBadge(int $s): string {
    return match ($s) {
        1 => '<span class="badge badge-approved">✓ Approved</span>',
        2 => '<span class="badge badge-rejected">✗ Rejected</span>',
        default => '<span class="badge badge-pending">● Pending</span>',
    };
}

function parseJson(mixed $val): array {
    if (is_array($val)) return $val;
    $d = json_decode($val ?? '[]', true);
    return is_array($d) ? $d : [];
}

function buildQuery(array $override = []): string {
    $q = array_merge($_GET, $override);
    unset($q['msg']);
    return http_build_query(array_filter($q, fn($v) => $v !== ''));
}

function collect_initials(string $name): string {
    $parts = array_filter(explode(' ', trim($name)));
    return strtoupper(substr($parts[0] ?? '', 0, 1) . substr($parts[1] ?? '', 0, 1));
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Reviewer Applications — RSIS Admin</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
  <style>
    :root{--brand:#1d4ed8;--brand-light:#eff6ff;--success:#16a34a;--danger:#dc2626;--warning:#d97706;--page-bg:#f4f7fc;--card-bg:#ffffff;--border:#e2e8f0;--text:#1e293b;--muted:#64748b;--radius:10px;}
    body{font-family:'Plus Jakarta Sans',sans-serif;background:var(--page-bg);color:var(--text);}
    .stat-card{background:var(--card-bg);border-radius:var(--radius);padding:20px 24px;border:1.5px solid var(--border);display:flex;align-items:center;gap:16px;transition:box-shadow .2s;}
    .stat-card:hover{box-shadow:0 4px 18px rgba(0,0,0,.07);}
    .stat-icon{width:48px;height:48px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:1.2rem;flex-shrink:0;}
    .stat-val{font-size:1.6rem;font-weight:800;line-height:1;}
    .stat-lbl{font-size:.78rem;color:var(--muted);font-weight:500;margin-top:2px;}
    .table-card{background:var(--card-bg);border-radius:var(--radius);border:1.5px solid var(--border);overflow:hidden;}
    .table-card-header{padding:16px 20px;border-bottom:1.5px solid var(--border);display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px;}
    .table-card-header h5{margin:0;font-size:.95rem;font-weight:700;}
    .filter-bar{padding:14px 20px;border-bottom:1.5px solid var(--border);background:#fafbff;}
    .filter-bar .form-control,.filter-bar .form-select{font-size:.83rem;border-color:var(--border);border-radius:8px;}
    .filter-bar .form-control:focus,.filter-bar .form-select:focus{border-color:var(--brand);box-shadow:0 0 0 3px rgba(29,78,216,.1);}
    .ra-table th{font-size:.71rem;font-weight:700;text-transform:uppercase;letter-spacing:.6px;color:var(--muted);background:#f8fafc;border-bottom:1.5px solid var(--border);padding:11px 14px;white-space:nowrap;}
    .ra-table td{font-size:.83rem;padding:12px 14px;vertical-align:middle;border-bottom:1px solid #f1f5f9;}
    .ra-table tbody tr:hover{background:#f8fbff;}
    .ra-table tbody tr:last-child td{border-bottom:none;}
    .badge{font-size:.7rem;font-weight:600;padding:4px 10px;border-radius:20px;}
    .badge-pending{background:#fef3c7;color:#92400e;}
    .badge-approved{background:#dcfce7;color:#15803d;}
    .badge-rejected{background:#fee2e2;color:#b91c1c;}
    .av{width:36px;height:36px;border-radius:10px;background:linear-gradient(135deg,#1d4ed8,#60a5fa);display:inline-flex;align-items:center;justify-content:center;font-size:.75rem;font-weight:700;color:#fff;flex-shrink:0;}
    .btn-xs{padding:4px 10px;font-size:.72rem;font-weight:600;border-radius:6px;}
    .detail-row{display:flex;gap:8px;margin-bottom:10px;}
    .detail-lbl{min-width:145px;font-size:.78rem;font-weight:600;color:var(--muted);flex-shrink:0;}
    .detail-val{font-size:.83rem;color:var(--text);}
    .page-link{font-size:.82rem;color:var(--brand);border-color:var(--border);}
    .page-item.active .page-link{background:var(--brand);border-color:var(--brand);}
    .toast-container{position:fixed;top:16px;right:16px;z-index:9999;}
  </style>
</head>
<body>
<?php include __DIR__ . '/include/sidebar.php'; ?>

<div class="rsis-page">
<div class="p-4">

  <!-- Toast -->
  <?php if (isset($_GET['msg'])): ?>
  <div class="toast-container">
    <div class="toast show align-items-center border-0
      <?= $_GET['msg'] === 'approve' ? 'bg-success' : ($_GET['msg'] === 'reject' ? 'bg-danger' : 'bg-secondary') ?>
      text-white" role="alert">
      <div class="d-flex">
        <div class="toast-body fw-600">
          <?= match ($_GET['msg']) {
            'approve' => '✓ Approved! Reviewer added to users table with "Website Form" source.',
            'reject' => '✗ Rejected. User role reverted.',
            'pending' => '↩ Reset to pending.',
            default => ''
          } ?>
        </div>
        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
      </div>
    </div>
  </div>
  <?php endif; ?>

  <!-- Page heading -->
  <div class="d-flex align-items-center justify-content-between mb-4">
    <div>
      <h4 class="mb-0 fw-800">Reviewer Applications</h4>
      <p class="text-muted mb-0" style="font-size:.83rem">
        Approve karne par reviewer automatically users table mein add ho jaata hai
      </p>
    </div>
    <a href="export_reviewers.php" class="btn btn-outline-primary btn-sm">
      <i class="fas fa-download me-1"></i> Export CSV
    </a>
  </div>

  <!-- Stat cards -->
  <div class="row g-3 mb-4">
    <div class="col-6 col-md-3">
      <div class="stat-card">
        <div class="stat-icon" style="background:#eff6ff;color:#1d4ed8"><i class="fas fa-users"></i></div>
        <div><div class="stat-val"><?= number_format((int)$counts['total']) ?></div><div class="stat-lbl">Total Applications</div></div>
      </div>
    </div>
    <div class="col-6 col-md-3">
      <div class="stat-card">
        <div class="stat-icon" style="background:#fef3c7;color:#d97706"><i class="fas fa-clock"></i></div>
        <div><div class="stat-val" style="color:#d97706"><?= number_format((int)$counts['pending']) ?></div><div class="stat-lbl">Pending Review</div></div>
      </div>
    </div>
    <div class="col-6 col-md-3">
      <div class="stat-card">
        <div class="stat-icon" style="background:#dcfce7;color:#16a34a"><i class="fas fa-check-circle"></i></div>
        <div><div class="stat-val" style="color:#16a34a"><?= number_format((int)$counts['approved']) ?></div><div class="stat-lbl">Approved</div></div>
      </div>
    </div>
    <div class="col-6 col-md-3">
      <div class="stat-card">
        <div class="stat-icon" style="background:#fee2e2;color:#dc2626"><i class="fas fa-times-circle"></i></div>
        <div><div class="stat-val" style="color:#dc2626"><?= number_format((int)$counts['rejected']) ?></div><div class="stat-lbl">Rejected</div></div>
      </div>
    </div>
  </div>

  <!-- Table card -->
  <div class="table-card">
    <div class="table-card-header">
      <h5><i class="fas fa-id-card me-2 text-primary"></i>All Applications
        <span class="badge bg-primary ms-2"><?= $total_rows ?></span>
      </h5>
      <div class="d-flex gap-2 flex-wrap">
        <?php
        $qAll = buildQuery(['status' => '', 'page' => 1]);
        $qPending = buildQuery(['status' => '0', 'page' => 1]);
        $qApproved = buildQuery(['status' => '1', 'page' => 1]);
        $qRejected = buildQuery(['status' => '2', 'page' => 1]);
        ?>
        <a href="?<?= $qAll ?>" class="btn btn-sm <?= $status_filter === '' ? 'btn-primary' : 'btn-outline-secondary' ?>">All</a>
        <a href="?<?= $qPending ?>" class="btn btn-sm <?= $status_filter === '0' ? 'btn-warning text-dark' : 'btn-outline-warning' ?>">Pending</a>
        <a href="?<?= $qApproved ?>" class="btn btn-sm <?= $status_filter === '1' ? 'btn-success' : 'btn-outline-success' ?>">Approved</a>
        <a href="?<?= $qRejected ?>" class="btn btn-sm <?= $status_filter === '2' ? 'btn-danger' : 'btn-outline-danger' ?>">Rejected</a>
      </div>
    </div>

    <div class="filter-bar">
      <form method="GET" class="row g-2 align-items-end">
        <input type="hidden" name="status" value="<?= htmlspecialchars($status_filter) ?>">
        <div class="col-12 col-md-5">
          <input type="search" name="search" class="form-control"
                 placeholder="Search name, email, country, application ID…"
                 value="<?= htmlspecialchars($search) ?>">
        </div>
        <div class="col-6 col-md-3">
          <select name="journal" class="form-select">
            <option value="">All Journals</option>
            <?php foreach ($journals as $jid): ?>
            <option value="<?= $jid ?>" <?= $journal_filter == (string)$jid ? 'selected' : '' ?>>Journal <?= $jid ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-6 col-md-2">
          <button type="submit" class="btn btn-primary w-100"><i class="fas fa-search me-1"></i>Search</button>
        </div>
        <div class="col-12 col-md-2">
          <a href="<?= $_SERVER['PHP_SELF'] ?>" class="btn btn-outline-secondary w-100"><i class="fas fa-redo me-1"></i>Reset</a>
        </div>
      </form>
    </div>

    <div class="table-responsive">
      <table class="table ra-table mb-0">
        <thead>
          <tr>
            <th>#</th>
            <th>Applicant</th>
            <th>Application ID</th>
            <th>Research Areas</th>
            <th>Country</th>
            <th>Experience</th>
            <th>Publications</th>
            <th>Status</th>
            <th>Applied</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
        <?php if (empty($applications)): ?>
        <tr>
          <td colspan="10" class="text-center text-muted py-5">
            <i class="fas fa-inbox fa-2x mb-2 d-block opacity-25"></i>No applications found.
          </td>
        </tr>
        <?php endif; ?>

        <?php foreach ($applications as $i => $app):
          $initials = collect_initials($app['full_name']);
          $areas = parseJson($app['research_areas']);
          $status = (int)$app['status'];
        ?>
        <tr>
          <td class="text-muted"><?= $offset + $i + 1 ?></td>
          <td>
            <div class="d-flex align-items-center gap-2">
              <div class="av"><?= htmlspecialchars($initials) ?></div>
              <div>
                <div class="fw-600 lh-1" style="font-size:.85rem">
                  <?= htmlspecialchars(($app['salutation'] ?? '') . ' ' . $app['full_name']) ?>
                </div>
                <div style="font-size:.72rem;color:var(--muted)"><?= htmlspecialchars($app['institutional_email']) ?></div>
              </div>
            </div>
          </td>
          <td><code style="font-size:.75rem;background:#f1f5f9;padding:2px 6px;border-radius:5px"><?= htmlspecialchars($app['application_id']) ?></code></td>
          <td>
            <?php foreach (array_slice($areas, 0, 2) as $area): ?>
            <span class="badge bg-light text-dark border mb-1" style="font-size:.68rem;font-weight:500"><?= htmlspecialchars($area) ?></span>
            <?php endforeach; ?>
            <?php if (count($areas) > 2): ?><span class="text-muted" style="font-size:.7rem">+<?= count($areas) - 2 ?> more</span><?php endif; ?>
          </td>
          <td style="font-size:.82rem"><?= htmlspecialchars($app['country'] ?? '') ?></td>
          <td style="font-size:.82rem;text-align:center"><span class="fw-700"><?= (int)($app['total_experience'] ?? 0) ?></span> <span class="text-muted" style="font-size:.7rem">yrs</span></td>
          <td style="text-align:center;font-size:.82rem"><span class="fw-700"><?= (int)($app['international_publications'] ?? 0) ?></span></td>
          <td><?= statusBadge($status) ?></td>
          <td style="font-size:.75rem;color:var(--muted);white-space:nowrap"><?= date('d M Y', strtotime($app['created_at'])) ?></td>
          <td>
            <div class="d-flex gap-1 flex-nowrap">
              <button class="btn btn-xs btn-outline-primary"
                      onclick="openDetail(<?= htmlspecialchars(json_encode($app), ENT_QUOTES) ?>)"
                      title="View Details">
                <i class="fas fa-eye"></i>
              </button>
              <?php if (!empty($app['cv_url'])): ?>
              <a href="/<?= htmlspecialchars($app['cv_url']) ?>" target="_blank"
                 class="btn btn-xs btn-outline-secondary" title="View CV">
                <i class="fas fa-file-pdf"></i>
              </a>
              <?php endif; ?>

              <?php if ($status !== 1): ?>
              <form method="POST" class="d-inline">
                <input type="hidden" name="id" value="<?= $app['id'] ?>">
                <input type="hidden" name="action" value="approve">
                <button class="btn btn-xs btn-success" title="Approve — reviewer will be added"
                        onclick="return confirm('Approve this application?\n\nThis will automatically add the reviewer to the users table.')">
                  <i class="fas fa-check"></i>
                </button>
              </form>
              <?php endif; ?>

              <?php if ($status !== 2): ?>
              <form method="POST" class="d-inline">
                <input type="hidden" name="id" value="<?= $app['id'] ?>">
                <input type="hidden" name="action" value="reject">
                <button class="btn btn-xs btn-danger" title="Reject"
                        onclick="return confirm('Reject this application?')">
                  <i class="fas fa-times"></i>
                </button>
              </form>
              <?php endif; ?>

              <?php if ($status !== 0): ?>
              <form method="POST" class="d-inline">
                <input type="hidden" name="id" value="<?= $app['id'] ?>">
                <input type="hidden" name="action" value="pending">
                <button class="btn btn-xs btn-outline-warning" title="Reset to Pending"
                        onclick="return confirm('Reset to pending?')">
                  <i class="fas fa-undo"></i>
                </button>
              </form>
              <?php endif; ?>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>

    <?php if ($total_pages > 1): ?>
    <div class="d-flex justify-content-between align-items-center px-4 py-3 border-top">
      <small class="text-muted">Showing <?= $offset + 1 ?>–<?= min($offset + $per_page, $total_rows) ?> of <?= $total_rows ?> results</small>
      <nav>
        <ul class="pagination pagination-sm mb-0 gap-1">
          <?php for ($p = 1; $p <= $total_pages; $p++): ?>
            <?php if ($p === 1 || $p === $total_pages || abs($p - $page) <= 2): ?>
            <li class="page-item <?= $p === $page ? 'active' : '' ?>">
              <a class="page-link rounded" href="?<?= buildQuery(['page' => $p]) ?>"><?= $p ?></a>
            </li>
            <?php elseif (abs($p - $page) === 3): ?>
            <li class="page-item disabled"><span class="page-link">…</span></li>
            <?php endif; ?>
          <?php endfor; ?>
        </ul>
      </nav>
    </div>
    <?php endif; ?>
  </div>
</div>
</div>

<!-- DETAIL MODAL -->
<div class="modal fade" id="detailModal" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content border-0 shadow">
      <div class="modal-header" style="background:#1d4ed8;color:#fff;border-radius:10px 10px 0 0">
        <div>
          <h5 class="modal-title fw-700 mb-0" id="modalTitle">Application Details</h5>
          <small class="opacity-75" id="modalAppId"></small>
        </div>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body p-4" id="modalBody"></div>
      <div class="modal-footer border-0 pt-0" id="modalFooter"></div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.querySelectorAll('.toast').forEach(t => {
  setTimeout(() => bootstrap.Toast.getOrCreateInstance(t).hide(), 4000);
});

function openDetail(app) {
  const areas = parseJsonSafe(app.research_areas);
  const refs = parseJsonSafe(app.reviewer_references);

  document.getElementById('modalTitle').textContent = (app.salutation || '') + ' ' + app.full_name;
  document.getElementById('modalAppId').textContent = app.application_id;

  const statusHtml = {
    0: '<span class="badge badge-pending">● Pending</span>',
    1: '<span class="badge badge-approved">✓ Approved</span>',
    2: '<span class="badge badge-rejected">✗ Rejected</span>'
  }[app.status] ?? '';

  let refsHtml = '<em class="text-muted">None provided</em>';
  if (typeof refs === 'object' && refs !== null) {
    const ri = Object.values(refs).filter(r => r && r.name);
    if (ri.length) refsHtml = ri.map(r =>
      `<div class="mb-1"><span class="fw-600">${esc(r.name)}</span>
       <span class="text-muted ms-2" style="font-size:.78rem">${esc(r.email || '')}</span>
       ${r.phone ? `<span class="text-muted ms-2" style="font-size:.78rem">${esc(r.phone)}</span>` : ''}</div>`
    ).join('');
  }

  const areasHtml = Array.isArray(areas) && areas.length
    ? areas.map(a => `<span class="badge bg-light text-dark border me-1 mb-1">${esc(a)}</span>`).join('')
    : '<em class="text-muted">—</em>';

  document.getElementById('modalBody').innerHTML = `
    <div class="row g-4">
      <div class="col-md-6">
        <h6 class="fw-700 text-primary mb-3"><i class="fas fa-user me-2"></i>Personal Info</h6>
        ${row('Full Name', (app.salutation || '') + ' ' + app.full_name)}
        ${row('Gender', app.gender)}
        ${row('Mobile', app.mobile_no)}
        ${row('WhatsApp', app.whatsapp_no)}
        ${row('City', app.city)}
        ${row('Country', app.country)}
        ${row('Status', statusHtml, true)}
        ${row('Applied', app.created_at?.split(' ')[0] ?? '—')}
      </div>
      <div class="col-md-6">
        <h6 class="fw-700 text-primary mb-3"><i class="fas fa-briefcase me-2"></i>Professional</h6>
        ${row('Current Employment', app.current_employment)}
        ${row('Total Experience', (app.total_experience || '0') + ' years')}
        ${row('Qualifications', app.educational_qualifications)}
        ${row('Publications', app.international_publications)}
        ${row('How Found Us', app.how_find_us)}
      </div>
      <div class="col-12">
        <h6 class="fw-700 text-primary mb-2"><i class="fas fa-flask me-2"></i>Research Areas</h6>
        <div>${areasHtml}</div>
      </div>
      <div class="col-md-6">
        <h6 class="fw-700 text-primary mb-3"><i class="fas fa-envelope me-2"></i>Contact</h6>
        ${row('Institutional Email', app.institutional_email ? '<a href="mailto:' + esc(app.institutional_email) + '">' + esc(app.institutional_email) + '</a>' : '—', true)}
        ${row('Personal Email', app.personal_email ? '<a href="mailto:' + esc(app.personal_email) + '">' + esc(app.personal_email) + '</a>' : '—', true)}
      </div>
      <div class="col-md-6">
        <h6 class="fw-700 text-primary mb-3"><i class="fas fa-file-alt me-2"></i>Documents</h6>
        ${app.cv_url ? `<a href="/${esc(app.cv_url)}" target="_blank" class="btn btn-sm btn-outline-primary"><i class="fas fa-file-pdf me-1"></i>View CV</a>` : '<em class="text-muted">No CV uploaded</em>'}
      </div>
      <div class="col-12">
        <h6 class="fw-700 text-primary mb-2"><i class="fas fa-address-book me-2"></i>References</h6>
        ${refsHtml}
      </div>
    </div>`;

  let footerBtns = `<button class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Close</button>`;
  if (app.status != 1) footerBtns += `<form method="POST" class="d-inline"><input type="hidden" name="id" value="${app.id}"><input type="hidden" name="action" value="approve"><button class="btn btn-success btn-sm" onclick="return confirm('Approve? This will add reviewer to users table.')"><i class="fas fa-check me-1"></i>Approve</button></form>`;
  if (app.status != 2) footerBtns += `<form method="POST" class="d-inline"><input type="hidden" name="id" value="${app.id}"><input type="hidden" name="action" value="reject"><button class="btn btn-danger btn-sm" onclick="return confirm('Reject?')"><i class="fas fa-times me-1"></i>Reject</button></form>`;

  document.getElementById('modalFooter').innerHTML = footerBtns;
  new bootstrap.Modal(document.getElementById('detailModal')).show();
}

function row(label, val, raw = false) {
  const v = raw ? (val || '—') : esc(val || '—');
  return `<div class="detail-row"><div class="detail-lbl">${label}</div><div class="detail-val">${v}</div></div>`;
}

function esc(s) { 
  const d = document.createElement('div'); 
  d.textContent = s; 
  return d.innerHTML; 
}

function parseJsonSafe(v) { 
  try { return JSON.parse(v); } catch (e) { return v; } 
}
</script>
</body>
</html>