<?php
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/functions.php';
startSecureSession();
requireAdmin();
$pageTitle = 'Certifications Management';
$success = $error = '';
$action = $_GET['action'] ?? 'list';
$id = (int)($_GET['id'] ?? 0);

if ($action === 'delete' && $id) {
  Database::execute("DELETE FROM certifications WHERE id=?", [$id]);
  header('Location: /admin/certifications.php?deleted=1'); exit;
}
if ($action === 'toggle' && $id) {
  Database::execute("UPDATE certifications SET is_active = NOT is_active WHERE id=?", [$id]);
  header('Location: /admin/certifications.php'); exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $name        = trim($_POST['name'] ?? '');
  $standard    = trim($_POST['standard'] ?? '');
  $issuing     = trim($_POST['issuing_body'] ?? '');
  $desc        = trim($_POST['description'] ?? '');
  $cert_number = trim($_POST['cert_number'] ?? '');
  $validity    = trim($_POST['validity_date'] ?? '') ?: null;
  $sort        = (int)($_POST['sort_order'] ?? 0);
  if (!$name) { $error = 'Certification name is required.'; }
  else {
    $certImage = $_POST['existing_cert_image'] ?? null;
    $certPdf   = $_POST['existing_cert_pdf'] ?? null;
    if (!empty($_FILES['cert_image']['tmp_name'])) {
      $ext = strtolower(pathinfo($_FILES['cert_image']['name'], PATHINFO_EXTENSION));
      if (in_array($ext, ['jpg','jpeg','png','webp'])) {
        $fname = 'cert_img_' . time() . '.' . $ext;
        move_uploaded_file($_FILES['cert_image']['tmp_name'], UPLOAD_PATH . '/' . $fname);
        $certImage = $fname;
      }
    }
    if (!empty($_FILES['cert_pdf']['tmp_name'])) {
      $fname = 'cert_pdf_' . time() . '.pdf';
        move_uploaded_file($_FILES['cert_pdf']['tmp_name'], UPLOAD_PATH . '/' . $fname);
      $certPdf = $fname;
    }
    if ($id) {
      Database::execute("UPDATE certifications SET name=?,standard=?,issuing_body=?,description=?,cert_number=?,validity_date=?,cert_image=?,cert_pdf=?,sort_order=? WHERE id=?",
        [$name,$standard,$issuing,$desc,$cert_number,$validity,$certImage,$certPdf,$sort,$id]);
      $success = 'Certification updated.';
    } else {
      $id = Database::insert("INSERT INTO certifications (name,standard,issuing_body,description,cert_number,validity_date,cert_image,cert_pdf,sort_order,is_active) VALUES (?,?,?,?,?,?,?,?,?,1)",
        [$name,$standard,$issuing,$desc,$cert_number,$validity,$certImage,$certPdf,$sort]);
      $success = 'Certification added.'; $action = 'edit';
    }
  }
}
$cert = ($action==='edit'||$action==='new') && $id ? Database::fetchOne("SELECT * FROM certifications WHERE id=?",[$id]) : null;
$certs = $action==='list' ? Database::fetchAll("SELECT * FROM certifications ORDER BY sort_order,id") : [];
require_once __DIR__ . '/includes/header.php';
?>

<div class="max-w-5xl">
  <?php if ($action === 'list'): ?>
  <div class="flex items-center justify-between mb-6">
    <h1 class="text-xl font-bold">🏅 Certifications</h1>
    <div class="flex gap-3">
      <a href="/certifications.php" target="_blank" class="btn-outline text-sm px-3 py-2">View Public Page ↗</a>
      <a href="?action=new" class="btn-primary text-sm px-4 py-2">+ Add Certification</a>
    </div>
  </div>
  <?php if (isset($_GET['deleted'])): ?><div class="bg-green-600/10 border border-green-600/30 text-green-400 text-sm px-4 py-3 rounded-lg mb-4">Deleted.</div><?php endif; ?>
  <div class="card-dark overflow-hidden">
    <table class="data-table">
      <thead class="bg-navy-700 text-xs text-gray-400 uppercase">
        <tr><th class="px-4 py-3 text-left">#</th><th class="px-4 py-3 text-left">Certification</th><th class="px-4 py-3 text-left">Standard</th><th class="px-4 py-3 text-left">Issuing Body</th><th class="px-4 py-3 text-left">Files</th><th class="px-4 py-3 text-left">Status</th><th class="px-4 py-3"></th></tr>
      </thead>
      <tbody>
        <?php if (!$certs): ?><tr><td colspan="7" class="px-4 py-8 text-center text-gray-500">No certifications yet. <a href="?action=new" class="text-orange-400">Add first →</a></td></tr><?php endif; ?>
        <?php foreach ($certs as $c): ?>
        <tr class="border-t border-navy-600 hover:bg-navy-800">
          <td class="px-4 py-3 text-gray-500"><?= $c['sort_order'] ?></td>
          <td class="px-4 py-3 font-medium"><?= e($c['name']) ?></td>
          <td class="px-4 py-3 text-orange-400 font-semibold"><?= e($c['standard']) ?></td>
          <td class="px-4 py-3 text-gray-400"><?= e($c['issuing_body']) ?></td>
          <td class="px-4 py-3 text-xs text-gray-500"><?= ($c['cert_pdf'] ? '📄 PDF ' : '') . ($c['cert_image'] ? '🖼️ Img' : '') ?: '—' ?></td>
          <td class="px-4 py-3"><a href="?action=toggle&id=<?= $c['id'] ?>" class="text-xs px-2 py-1 rounded-full font-semibold <?= $c['is_active'] ? 'bg-green-600/10 text-green-400' : 'bg-gray-600/10 text-gray-400' ?>"><?= $c['is_active'] ? 'Active' : 'Hidden' ?></a></td>
          <td class="px-4 py-3 flex gap-2">
            <a href="?action=edit&id=<?= $c['id'] ?>" class="text-xs text-orange-400 hover:underline">Edit</a>
            <a href="?action=delete&id=<?= $c['id'] ?>" class="text-xs text-red-400 hover:underline" onclick="return confirm('Delete?')">Delete</a>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>

  <?php else: ?>
  <div class="flex items-center gap-3 mb-6">
    <a href="/admin/certifications.php" class="text-gray-400 hover:text-white text-sm">← All Certifications</a>
    <h1 class="text-xl font-bold"><?= $id ? 'Edit Certification' : 'New Certification' ?></h1>
  </div>
  <?php if ($success): ?><div class="bg-green-600/10 border border-green-600/30 text-green-400 text-sm px-4 py-3 rounded-lg mb-4"><?= e($success) ?></div><?php endif; ?>
  <?php if ($error): ?><div class="bg-red-600/10 border border-red-600/30 text-red-400 text-sm px-4 py-3 rounded-lg mb-4"><?= e($error) ?></div><?php endif; ?>
  <form method="POST" enctype="multipart/form-data" class="card-dark p-6 max-w-2xl">
    <div class="grid grid-cols-2 gap-4 mb-4">
      <div>
        <label class="block text-xs text-gray-400 mb-1">Certification Name *</label>
        <input type="text" name="name" value="<?= e($cert['name'] ?? '') ?>" class="input-field" required placeholder="e.g. API Specification 6A">
      </div>
      <div>
        <label class="block text-xs text-gray-400 mb-1">Standard Code</label>
        <input type="text" name="standard" value="<?= e($cert['standard'] ?? '') ?>" class="input-field" placeholder="API 6A">
      </div>
    </div>
    <div class="grid grid-cols-2 gap-4 mb-4">
      <div>
        <label class="block text-xs text-gray-400 mb-1">Issuing Body</label>
        <input type="text" name="issuing_body" value="<?= e($cert['issuing_body'] ?? '') ?>" class="input-field" placeholder="American Petroleum Institute">
      </div>
      <div>
        <label class="block text-xs text-gray-400 mb-1">Certificate Number</label>
        <input type="text" name="cert_number" value="<?= e($cert['cert_number'] ?? '') ?>" class="input-field" placeholder="Optional">
      </div>
    </div>
    <div class="mb-4">
      <label class="block text-xs text-gray-400 mb-1">Description</label>
      <textarea name="description" rows="4" class="input-field" placeholder="Brief description of what this certification covers..."><?= e($cert['description'] ?? '') ?></textarea>
    </div>
    <div class="grid grid-cols-2 gap-4 mb-4">
      <div>
        <label class="block text-xs text-gray-400 mb-1">Validity Date</label>
        <input type="date" name="validity_date" value="<?= e($cert['validity_date'] ?? '') ?>" class="input-field">
      </div>
      <div>
        <label class="block text-xs text-gray-400 mb-1">Sort Order</label>
        <input type="number" name="sort_order" value="<?= e($cert['sort_order'] ?? 0) ?>" class="input-field" min="0">
      </div>
    </div>
    <div class="grid grid-cols-2 gap-4 mb-5">
      <div>
        <label class="block text-xs text-gray-400 mb-1">Certificate Image (JPG/PNG)</label>
        <?php if (!empty($cert['cert_image'])): ?><img src="/uploads/<?= e($cert['cert_image']) ?>" class="h-16 mb-1 rounded object-contain"><input type="hidden" name="existing_cert_image" value="<?= e($cert['cert_image']) ?>"><?php endif; ?>
        <input type="file" name="cert_image" accept="image/*" class="text-xs text-gray-400">
      </div>
      <div>
        <label class="block text-xs text-gray-400 mb-1">Certificate PDF</label>
        <?php if (!empty($cert['cert_pdf'])): ?><div class="text-xs text-green-400 mb-1">📄 PDF uploaded</div><input type="hidden" name="existing_cert_pdf" value="<?= e($cert['cert_pdf']) ?>"><?php endif; ?>
        <input type="file" name="cert_pdf" accept="application/pdf" class="text-xs text-gray-400">
      </div>
    </div>
    <div class="flex gap-3">
      <button type="submit" class="btn-primary px-6 py-2.5">Save</button>
      <a href="/admin/certifications.php" class="btn-outline px-6 py-2.5">Cancel</a>
    </div>
  </form>
  <?php endif; ?>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
