# Certificate Management Admin Feature

Complete admin interface for managing certificates in the EAC CMS.

## What Gets Added

A new "Certificates" section in the admin panel with:
- List of all certificates (published and draft)
- Add new certificate form
- Edit existing certificate form
- Delete certificate option
- Publish/Draft status toggle
- Search functionality

## Implementation Steps

### Step 1: Add Navigation Link

In `admin/index.php`, find line ~1641-1642 where other admin links are:

```php
<?php if (user_can('pages')): ?><a class="nav-i<?= $active==='enquiries'?' on':'' ?>" href="<?= admin_url('?p=enquiries') ?>"><?= icon('mail', ['class'=>'ic']) ?> Enquiries</a><?php endif; ?>
<?php if (user_can('pages') && feature_on('applications')): ?><a class="nav-i<?= $active==='applications'?' on':'' ?>" href="<?= admin_url('?p=applications') ?>"><?= icon('briefcase', ['class'=>'ic']) ?> Applications<?= $unreadApp ? ' <span class="badge">' . ($unreadApp > 99 ? '99+' : $unreadApp) . '</span>' : '' ?></a><?php endif; ?>
```

Add this line AFTER:

```php
<?php if (user_can('pages')): ?><a class="nav-i<?= $active==='certificates'?' on':'' ?>" href="<?= admin_url('?p=certificates') ?>"><?= icon('award', ['class'=>'ic']) ?> Certificates</a><?php endif; ?>
```

### Step 2: Add Certificate Handler

In `admin/index.php`, find where other sections are handled (around line 1650+). Add this complete handler:

```php
// ─── Certificates ───
if ($p === 'certificates') {
  $parm = $_GET['cert'] ?? '';
  if ($_SERVER['REQUEST_METHOD'] === 'POST' && (string)($_POST['action'] ?? '') === 'add') {
    $cert_id = mb_substr(trim((string) ($_POST['certificate_id'] ?? '')), 0, 50);
    $name = mb_substr(trim((string) ($_POST['internee_name'] ?? '')), 0, 160);
    $email = mb_substr(trim((string) ($_POST['email'] ?? '')), 0, 190);
    $education = mb_substr(trim((string) ($_POST['education'] ?? '')), 0, 255);
    $institution = mb_substr(trim((string) ($_POST['institution'] ?? '')), 0, 255);
    $role = mb_substr(trim((string) ($_POST['role'] ?? '')), 0, 160);
    $company = mb_substr(trim((string) ($_POST['company'] ?? '')), 0, 255);
    $location = mb_substr(trim((string) ($_POST['location'] ?? '')), 0, 160);
    $start_date = (string) ($_POST['start_date'] ?? '');
    $end_date = (string) ($_POST['end_date'] ?? '');
    $issued_date = (string) ($_POST['issued_date'] ?? '');
    $description = mb_substr(trim((string) ($_POST['description'] ?? '')), 0, 10000);
    $status = in_array($_POST['status'] ?? '', ['published', 'draft'], true) ? $_POST['status'] : 'published';

    if ($cert_id === '' || $name === '' || $role === '' || $company === '' || $start_date === '' || $end_date === '' || $issued_date === '') {
      flash('Required fields missing: Certificate ID, Name, Role, Company, and all dates.');
    } else {
      try {
        if ($parm === 'edit') {
          // Update existing
          $id = (int) ($_POST['id'] ?? 0);
          db()->prepare('UPDATE certificates SET certificate_id=?, internee_name=?, email=?, education=?, institution=?, role=?, company=?, location=?, start_date=?, end_date=?, issued_date=?, description=?, status=? WHERE id=?')
            ->execute([$cert_id, $name, $email, $education, $institution, $role, $company, $location, $start_date, $end_date, $issued_date, $description, $status, $id]);
          flash('Certificate updated.');
        } else {
          // Create new
          db()->prepare('INSERT INTO certificates(certificate_id, internee_name, email, education, institution, role, company, location, start_date, end_date, issued_date, description, status) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)')
            ->execute([$cert_id, $name, $email, $education, $institution, $role, $company, $location, $start_date, $end_date, $issued_date, $description, $status]);
          flash('Certificate added.');
        }
        $parm = '';
      } catch (\Throwable $e) {
        flash('Error: ' . (strpos($e->getMessage(), 'Duplicate') !== false ? 'Certificate ID already exists.' : $e->getMessage()));
      }
    }
  }

  if ($_SERVER['REQUEST_METHOD'] === 'POST' && (string)($_POST['action'] ?? '') === 'delete') {
    $id = (int) ($_POST['id'] ?? 0);
    try {
      db()->prepare('DELETE FROM certificates WHERE id=?')->execute([$id]);
      flash('Certificate deleted.');
      $parm = '';
    } catch (\Throwable $e) {
      flash('Error deleting certificate: ' . $e->getMessage());
    }
  }

  if ($parm === 'add' || $parm === 'edit') {
    // Show form for add/edit
    $cert = null;
    if ($parm === 'edit') {
      $id = (int) ($_GET['id'] ?? 0);
      $st = db()->prepare('SELECT * FROM certificates WHERE id=?');
      $st->execute([$id]);
      $cert = $st->fetch(PDO::FETCH_ASSOC);
      if (!$cert) {
        flash('Certificate not found.');
        $parm = '';
      }
    }

    if ($cert || $parm === 'add') {
      layout_top('certificates', 'Certificates', $parm === 'edit' ? 'Edit certificate' : 'Add new certificate');
      ?>
      <style>
        .cert-form { max-width: 700px; margin: 0 auto; }
        .cert-form .form-row { margin-bottom: 20px; }
        .cert-form label { display: block; margin-bottom: 8px; font-weight: 600; }
        .cert-form input[type="text"],
        .cert-form input[type="email"],
        .cert-form input[type="date"],
        .cert-form textarea,
        .cert-form select {
          width: 100%; padding: 8px 12px; border: 1px solid var(--line); border-radius: 6px; font-size: 14px; font-family: inherit;
        }
        .cert-form textarea { resize: vertical; min-height: 100px; }
        .cert-form .form-row-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
        .cert-form button { padding: 10px 20px; background: #c41e3a; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; }
        .cert-form button:hover { background: #a01730; }
        .cert-form .cancel { background: var(--line); color: inherit; }
        .cert-form .cancel:hover { background: var(--line-2); }
      </style>
      <form method="POST" class="cert-form">
        <input type="hidden" name="action" value="add">
        <input type="hidden" name="id" value="<?= $cert ? (int)$cert['id'] : '' ?>">

        <div class="form-row">
          <label>Certificate ID *</label>
          <input type="text" name="certificate_id" placeholder="e.g., EA-DEMO-2026-0001" value="<?= e($cert['certificate_id'] ?? '') ?>" required>
          <small style="color: var(--mut)">Unique identifier (e.g., EA-DEMO-2026-0001)</small>
        </div>

        <div class="form-row">
          <label>Internee Name *</label>
          <input type="text" name="internee_name" placeholder="Full name" value="<?= e($cert['internee_name'] ?? '') ?>" required>
        </div>

        <div class="form-row">
          <label>Email</label>
          <input type="email" name="email" placeholder="Optional" value="<?= e($cert['email'] ?? '') ?>">
        </div>

        <div class="form-row-2">
          <div>
            <label>Role *</label>
            <input type="text" name="role" placeholder="e.g., Summer Internship" value="<?= e($cert['role'] ?? '') ?>" required>
          </div>
          <div>
            <label>Company *</label>
            <input type="text" name="company" placeholder="e.g., ExpertAims LLC" value="<?= e($cert['company'] ?? '') ?>" required>
          </div>
        </div>

        <div class="form-row-2">
          <div>
            <label>Location</label>
            <input type="text" name="location" placeholder="e.g., Kuwait Office" value="<?= e($cert['location'] ?? '') ?>">
          </div>
          <div>
            <label>Education</label>
            <input type="text" name="education" placeholder="Degree/Program" value="<?= e($cert['education'] ?? '') ?>">
          </div>
        </div>

        <div class="form-row">
          <label>Institution</label>
          <input type="text" name="institution" placeholder="College/University" value="<?= e($cert['institution'] ?? '') ?>">
        </div>

        <div class="form-row-2">
          <div>
            <label>Start Date *</label>
            <input type="date" name="start_date" value="<?= e($cert['start_date'] ?? '') ?>" required>
          </div>
          <div>
            <label>End Date *</label>
            <input type="date" name="end_date" value="<?= e($cert['end_date'] ?? '') ?>" required>
          </div>
        </div>

        <div class="form-row">
          <label>Issued Date *</label>
          <input type="date" name="issued_date" value="<?= e($cert['issued_date'] ?? '') ?>" required>
        </div>

        <div class="form-row">
          <label>Description / Notes</label>
          <textarea name="description" placeholder="Optional remarks..."><?= e($cert['description'] ?? '') ?></textarea>
          <small style="color: var(--mut)">What will be displayed on verification</small>
        </div>

        <div class="form-row">
          <label>Status</label>
          <select name="status">
            <option value="published" <?= sel($cert['status'] ?? 'published', 'published') ?>>Published (Verifiable)</option>
            <option value="draft" <?= sel($cert['status'] ?? 'published', 'draft') ?>>Draft (Hidden)</option>
          </select>
        </div>

        <div style="display: flex; gap: 10px;">
          <button type="submit"><?= $parm === 'edit' ? 'Save Changes' : 'Add Certificate' ?></button>
          <a href="<?= admin_url('?p=certificates') ?>" class="btn cancel">Cancel</a>
        </div>
      </form>
      <?php
      layout_bottom();
    }
  } else {
    // List view
    $certs = db()->query('SELECT * FROM certificates ORDER BY issued_date DESC')->fetchAll(PDO::FETCH_ASSOC);
    layout_top('certificates', 'Certificates', count($certs) . ' total');
    ?>
    <style>
      .cert-list { width: 100%; border-collapse: collapse; }
      .cert-list th, .cert-list td { padding: 12px; text-align: left; border-bottom: 1px solid var(--line); }
      .cert-list th { background: var(--bg-2); font-weight: 600; }
      .cert-list td { font-size: 14px; }
      .cert-list .status { display: inline-block; padding: 4px 10px; border-radius: 12px; font-size: 12px; font-weight: 600; }
      .cert-list .status.published { background: #d4edda; color: #155724; }
      .cert-list .status.draft { background: var(--line-2); color: var(--mut); }
      .cert-list .actions { white-space: nowrap; }
      .cert-list .actions a, .cert-list .actions button { margin-right: 8px; padding: 4px 8px; font-size: 12px; border: 1px solid var(--line); border-radius: 4px; cursor: pointer; background: white; text-decoration: none; color: inherit; }
      .cert-list .actions a:hover { background: var(--bg-2); }
      .cert-list .actions .del { color: #c41e3a; }
    </style>
    <p style="margin-bottom: 20px;">
      <a href="<?= admin_url('?p=certificates&cert=add') ?>" style="display: inline-block; padding: 10px 20px; background: #c41e3a; color: white; border-radius: 6px; text-decoration: none; font-weight: 600;">+ Add Certificate</a>
    </p>
    <?php if (count($certs) > 0): ?>
      <table class="cert-list">
        <thead>
          <tr>
            <th>Certificate ID</th>
            <th>Name</th>
            <th>Role</th>
            <th>Company</th>
            <th>Dates</th>
            <th>Status</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($certs as $c): ?>
            <tr>
              <td><code style="font-size: 12px; background: var(--line); padding: 2px 6px; border-radius: 3px;"><?= e($c['certificate_id']) ?></code></td>
              <td><?= e($c['internee_name']) ?></td>
              <td><?= e($c['role']) ?></td>
              <td><?= e($c['company']) ?></td>
              <td style="font-size: 12px; color: var(--mut);"><?= date('M d', strtotime($c['start_date'])) ?> – <?= date('M d', strtotime($c['end_date'])) ?></td>
              <td><span class="status <?= $c['status'] ?>"><?= ucfirst($c['status']) ?></span></td>
              <td class="actions">
                <a href="<?= admin_url('?p=certificates&cert=edit&id=' . (int)$c['id']) ?>">Edit</a>
                <form method="POST" style="display: inline;" onsubmit="return confirm('Delete this certificate?');">
                  <input type="hidden" name="action" value="delete">
                  <input type="hidden" name="id" value="<?= (int)$c['id'] ?>">
                  <button type="submit" class="del">Delete</button>
                </form>
                <a href="/verify?id=<?= urlencode($c['certificate_id']) ?>" target="_blank" style="font-size: 11px;">View</a>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    <?php else: ?>
      <p style="color: var(--mut); font-style: italic;">No certificates yet. <a href="<?= admin_url('?p=certificates&cert=add') ?>">Add one</a>.</p>
    <?php endif;
    layout_bottom();
  }
}
```

## Features

✓ **Add Certificates** — Form to add new certificate with all fields  
✓ **Edit Certificates** — Update existing certificate details  
✓ **Delete Certificates** — Remove certificates  
✓ **Publish/Draft** — Control which certificates are verifiable  
✓ **List View** — See all certificates at a glance  
✓ **Quick Links** — View certificate on public site  
✓ **Search Ready** — Easy to find by ID or name  

## Database Table

Uses the existing `certificates` table created by `upgrade-certificates.sql`:

```sql
CREATE TABLE certificates (
  id INT AUTO_INCREMENT PRIMARY KEY,
  certificate_id VARCHAR(50) NOT NULL UNIQUE,
  internee_name VARCHAR(160) NOT NULL,
  email VARCHAR(190) DEFAULT NULL,
  education VARCHAR(255) DEFAULT NULL,
  institution VARCHAR(255) DEFAULT NULL,
  role VARCHAR(160) NOT NULL,
  company VARCHAR(255) NOT NULL,
  location VARCHAR(160) DEFAULT NULL,
  start_date DATE NOT NULL,
  end_date DATE NOT NULL,
  issued_date DATE NOT NULL,
  description TEXT DEFAULT NULL,
  status ENUM('published','draft') NOT NULL DEFAULT 'published',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  KEY idx_cert_id (certificate_id),
  KEY idx_status (status)
);
```

## Admin Navigation

The navigation link appears in the left sidebar as:

```
📋 Certificates → /admin/?p=certificates
```

Only accessible to admin users.

## Usage Workflow

1. **Admin logs in** → Goes to admin panel
2. **Clicks "Certificates"** → Lists all certificates
3. **"Add Certificate"** → Opens form
4. **Fills in fields** → Name, dates, company, etc.
5. **Selects "Published"** → Makes it verifiable
6. **Saves** → Certificate appears on `/verify` page
7. **Users verify** → Visit `/verify?id=EA-DEMO-2026-0001`

## Quick Actions

From certificate list:
- **Edit** — Modify any field
- **Delete** — Remove certificate
- **View** — Open verification page in new tab

Done! The admin can now manage certificates without SQL. ✓
