<?php
// admin/certification.php
require_once __DIR__ . '/../config/helpers.php';
require_once __DIR__ . '/../config/db.php';
require_login();
$pdo = db();

/* ------------------ Buat tabel jika belum ada ------------------ */
$pdo->exec("
  CREATE TABLE IF NOT EXISTS certification (
    id INT AUTO_INCREMENT PRIMARY KEY,
    org_name VARCHAR(180) NOT NULL,
    issue_year SMALLINT DEFAULT NULL,
    expire_year SMALLINT DEFAULT NULL,
    cert_name VARCHAR(200) NOT NULL,
    cert_url VARCHAR(255) DEFAULT NULL,
    cert_no  VARCHAR(120) DEFAULT NULL,
    cert_photo VARCHAR(255) DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

/* ------------------ Helper Upload ------------------ */
if (!function_exists('is_abs_http')) {
  function is_abs_http($url){ return (bool)preg_match('~^https?://~i',(string)$url); }
}
$publicRoot = realpath(__DIR__ . '/../public') ?: (__DIR__ . '/../public');
$uploadDir  = $publicRoot . '/uploads/certification';
$uploadUrl  = '/uploads/certification';
if (!is_dir($uploadDir)) @mkdir($uploadDir, 0775, true);

function mime_to_ext($tmp){
  $f = new finfo(FILEINFO_MIME_TYPE); $m=$f->file($tmp);
  $map = [
    'image/jpeg'=>'.jpg',
    'image/png' =>'.png',
    'image/webp'=>'.webp',
    'image/gif' =>'.gif'
  ];
  return $map[$m] ?? null;
}
function save_upload($file, $title, $uploadDir, $uploadUrl){
  if (!isset($file) || $file['error'] === UPLOAD_ERR_NO_FILE) return [null, null];
  if ($file['error'] !== UPLOAD_ERR_OK) return [null, 'Upload error '.$file['error']];
  if ($file['size'] > 5*1024*1024) return [null, 'Ukuran maks 5MB'];

  $ext = mime_to_ext($file['tmp_name']);
  if (!$ext) return [null, 'Format wajib JPG/PNG/WEBP/GIF'];

  $slug = preg_replace('~[^a-z0-9]+~i','-', $title ?: 'cert');
  $name = trim($slug,'-').'-'.substr(sha1(uniqid('',true)),0,8).$ext;

  if (!move_uploaded_file($file['tmp_name'], $uploadDir.'/'.$name)) {
    return [null, 'Gagal menyimpan file'];
  }
  return [$uploadUrl.'/'.$name, null];
}
function delete_local_if_any($path){
  if (!$path || is_abs_http($path)) return;
  $full = realpath(__DIR__ . '/../public' . $path);
  if ($full && is_file($full)) @unlink($full);
}

/* ------------------ Handle POST ------------------ */
if (is_post()){
  csrf_check();
  $action = trim($_POST['action'] ?? '');

  // Hapus
  if ($action === 'delete') {
    $id = (int)($_POST['id'] ?? 0);
    if ($id > 0) {
      $row = $pdo->prepare("SELECT cert_photo FROM certification WHERE id=?");
      $row->execute([$id]);
      $old = $row->fetch();
      if ($old) delete_local_if_any($old['cert_photo'] ?? null);

      $pdo->prepare("DELETE FROM certification WHERE id=?")->execute([$id]);
      flash('ok','Sertifikat dihapus.');
    } else {
      flash('err','ID tidak valid.');
    }
    header('Location: certification.php'); exit;
  }

  // Tambah / Update
  if ($action === 'create' || $action === 'update') {
    $id   = (int)($_POST['id'] ?? 0);
    $org  = trim($_POST['org_name'] ?? '');
    $name = trim($_POST['cert_name'] ?? '');
    $iy   = (int)($_POST['issue_year'] ?? 0);
    $ey   = (int)($_POST['expire_year'] ?? 0);
    $url  = trim($_POST['cert_url'] ?? '');
    $no   = trim($_POST['cert_no'] ?? '');

    if ($org === '' || $name === '') {
      flash('err','Nama instansi dan nama sertifikat wajib diisi.');
      header('Location: certification.php' . ($action==='update' && $id? '?edit='.$id : ''));
      exit;
    }
    if ($iy < 1900 || $iy > 2100) $iy = null;
    if ($ey < 1900 || $ey > 2100) $ey = null;

    $finalPhoto = null;

    if ($action === 'update') {
      if ($id <= 0) { flash('err','ID tidak valid.'); header('Location: certification.php'); exit; }
      $st = $pdo->prepare("SELECT cert_photo FROM certification WHERE id=?");
      $st->execute([$id]);
      $cur = $st->fetch();
      $finalPhoto = $cur['cert_photo'] ?? null;
    }

    // Upload baru?
    if (!empty($_FILES['cert_photo'])) {
      [$saved, $uerr] = save_upload($_FILES['cert_photo'], $name ?: $org, $uploadDir, $uploadUrl);
      if ($uerr) { flash('err',$uerr); header('Location: certification.php' . ($action==='update'?'?edit='.$id:'')); exit; }
      if ($saved) {
        // hapus lama jika lokal
        delete_local_if_any($finalPhoto);
        $finalPhoto = $saved;
      }
    }

    if ($action === 'create') {
      $pdo->prepare("
        INSERT INTO certification (org_name, issue_year, expire_year, cert_name, cert_url, cert_no, cert_photo)
        VALUES (?,?,?,?,?,?,?)
      ")->execute([$org, $iy, $ey, $name, $url ?: null, $no ?: null, $finalPhoto]);
      flash('ok','Sertifikat ditambahkan.');
    } else {
      $pdo->prepare("
        UPDATE certification
        SET org_name=?, issue_year=?, expire_year=?, cert_name=?, cert_url=?, cert_no=?, cert_photo=?
        WHERE id=?
      ")->execute([$org, $iy, $ey, $name, $url ?: null, $no ?: null, $finalPhoto, $id]);
      flash('ok','Sertifikat diperbarui.');
    }

    header('Location: certification.php'); exit;
  }
}

/* ------------------ Data untuk tampil ------------------ */
$rows = $pdo->query("
  SELECT * FROM certification
  ORDER BY issue_year DESC, expire_year DESC, cert_name ASC, id DESC
")->fetchAll();

$edit = null;
if (!empty($_GET['edit'])) {
  $eid = (int)$_GET['edit'];
  if ($eid > 0) {
    $st = $pdo->prepare("SELECT * FROM certification WHERE id=?");
    $st->execute([$eid]);
    $edit = $st->fetch();
  }
}

$ok  = flash('ok');
$err = flash('err');

require_once __DIR__ . '/_layout_top.php';
?>
<div class="container py-4">

  <?php if($ok): ?>
    <div class="alert alert-success d-flex align-items-center" role="alert">
      <i class="bi bi-check-circle me-2"></i><div><?php echo e($ok) ?></div>
    </div>
  <?php endif; ?>
  <?php if($err): ?>
    <div class="alert alert-danger d-flex align-items-center" role="alert">
      <i class="bi bi-exclamation-triangle me-2"></i><div><?php echo e($err) ?></div>
    </div>
  <?php endif; ?>

  <div class="card shadow-sm">
    <div class="card-header d-flex justify-content-between align-items-center">
      <h5 class="mb-0"><i class="bi bi-award me-2"></i>Certification</h5>
      <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#createModal">
        <i class="bi bi-plus-circle me-1"></i>Tambah
      </button>
    </div>
    <div class="card-body">
      <?php if (!empty($rows)): ?>
        <div class="table-responsive">
          <table class="table align-middle">
            <thead class="table-light">
              <tr>
                <th style="width:80px">Foto</th>
                <th>Sertifikat</th>
                <th>Instansi</th>
                <th>Periode</th>
                <th>No/URL</th>
                <th style="width:130px">Aksi</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach($rows as $r): ?>
                <tr>
                  <td>
                    <?php if(!empty($r['cert_photo'])): ?>
                      <img src="<?php echo e($r['cert_photo']) ?>" class="rounded border" style="width:70px;height:50px;object-fit:cover" alt="">
                    <?php else: ?>
                      <div class="text-muted small">No photo</div>
                    <?php endif; ?>
                  </td>
                  <td>
                    <div class="fw-semibold"><?php echo e($r['cert_name']) ?></div>
                    <div class="small text-muted"><?php echo e($r['created_at']) ?></div>
                  </td>
                  <td><?php echo e($r['org_name']) ?></td>
                  <td>
                    <span class="badge text-bg-primary-subtle border"><?php echo e($r['issue_year'] ?: '—') ?> – <?php echo e($r['expire_year'] ?: '—') ?></span>
                  </td>
                  <td class="small">
                    <?php if(!empty($r['cert_no'])): ?>
                      <div><i class="bi bi-hash me-1"></i><?php echo e($r['cert_no']) ?></div>
                    <?php endif; ?>
                    <?php if(!empty($r['cert_url'])): ?>
                      <a href="<?php echo e($r['cert_url']) ?>" target="_blank" class="text-decoration-none"><i class="bi bi-box-arrow-up-right me-1"></i>Buka</a>
                    <?php endif; ?>
                  </td>
                  <td>
                    <div class="d-flex gap-2">
                      <a class="btn btn-sm btn-outline-primary" href="certification.php?edit=<?php echo (int)$r['id'] ?>">
                        <i class="bi bi-pencil-square"></i>
                      </a>
                      <form method="post" onsubmit="return confirm('Hapus sertifikat ini?')">
                        <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="id" value="<?php echo (int)$r['id'] ?>">
                        <button class="btn btn-sm btn-outline-danger"><i class="bi bi-trash"></i></button>
                      </form>
                    </div>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php else: ?>
        <div class="text-center text-muted">Belum ada data sertifikat.</div>
      <?php endif; ?>
    </div>
  </div>
</div>

<!-- Modal: Tambah -->
<div class="modal fade" id="createModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <form method="post" enctype="multipart/form-data">
        <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
        <input type="hidden" name="action" value="create">
        <div class="modal-header">
          <h5 class="modal-title"><i class="bi bi-plus-circle me-2"></i>Tambah Sertifikat</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Tutup"></button>
        </div>
        <div class="modal-body">
          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label">Nama Sertifikat</label>
              <input name="cert_name" class="form-control" required>
            </div>
            <div class="col-md-6">
              <label class="form-label">Instansi (contoh: EC-Council)</label>
              <input name="org_name" class="form-control" required>
            </div>
            <div class="col-md-3">
              <label class="form-label">Tahun Terbit</label>
              <input type="number" min="1900" max="2100" name="issue_year" class="form-control">
            </div>
            <div class="col-md-3">
              <label class="form-label">Tahun Expired</label>
              <input type="number" min="1900" max="2100" name="expire_year" class="form-control">
            </div>
            <div class="col-md-6">
              <label class="form-label">Nomor Sertifikat</label>
              <input name="cert_no" class="form-control">
            </div>
            <div class="col-md-8">
              <label class="form-label">URL Sertifikat</label>
              <input name="cert_url" class="form-control" placeholder="https://...">
            </div>
            <div class="col-md-4">
              <label class="form-label">Foto Sertifikat</label>
              <input type="file" name="cert_photo" class="form-control" accept="image/*">
              <div class="form-text">JPG/PNG/WEBP/GIF, maks 5MB</div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-primary"><i class="bi bi-save me-1"></i>Simpan</button>
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Batal</button>
        </div>
      </form>
    </div>
  </div>
</div>

<?php if($edit): ?>
<!-- Modal: Edit (otomatis terbuka jika ?edit=ID) -->
<div class="modal fade show" id="editModal" tabindex="-1" aria-modal="true" style="display:block;background:rgba(0,0,0,.5);">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <form method="post" enctype="multipart/form-data">
        <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
        <input type="hidden" name="action" value="update">
        <input type="hidden" name="id" value="<?php echo (int)$edit['id'] ?>">
        <div class="modal-header">
          <h5 class="modal-title"><i class="bi bi-pencil-square me-2"></i>Edit Sertifikat</h5>
          <a href="certification.php" class="btn-close" aria-label="Tutup"></a>
        </div>
        <div class="modal-body">
          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label">Nama Sertifikat</label>
              <input name="cert_name" class="form-control" required value="<?php echo e($edit['cert_name'] ?? '') ?>">
            </div>
            <div class="col-md-6">
              <label class="form-label">Instansi</label>
              <input name="org_name" class="form-control" required value="<?php echo e($edit['org_name'] ?? '') ?>">
            </div>
            <div class="col-md-3">
              <label class="form-label">Tahun Terbit</label>
              <input type="number" min="1900" max="2100" name="issue_year" class="form-control" value="<?php echo e($edit['issue_year'] ?? '') ?>">
            </div>
            <div class="col-md-3">
              <label class="form-label">Tahun Expired</label>
              <input type="number" min="1900" max="2100" name="expire_year" class="form-control" value="<?php echo e($edit['expire_year'] ?? '') ?>">
            </div>
            <div class="col-md-6">
              <label class="form-label">Nomor Sertifikat</label>
              <input name="cert_no" class="form-control" value="<?php echo e($edit['cert_no'] ?? '') ?>">
            </div>
            <div class="col-md-8">
              <label class="form-label">URL Sertifikat</label>
              <input name="cert_url" class="form-control" value="<?php echo e($edit['cert_url'] ?? '') ?>">
            </div>
            <div class="col-md-4">
              <label class="form-label">Ganti Foto Sertifikat</label>
              <input type="file" name="cert_photo" class="form-control" accept="image/*">
              <div class="form-text">Kosongkan jika tidak diganti</div>
            </div>
            <div class="col-12">
              <label class="form-label">Preview Saat Ini</label><br>
              <?php if(!empty($edit['cert_photo'])): ?>
                <img src="<?php echo e($edit['cert_photo']); ?>" class="img-thumbnail" style="max-height:160px;object-fit:cover" alt="">
              <?php else: ?>
                <div class="border rounded p-2 text-center text-muted bg-light">Belum ada foto</div>
              <?php endif; ?>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <a href="certification.php" class="btn btn-outline-secondary">Batal</a>
          <button class="btn btn-primary"><i class="bi bi-save me-1"></i>Update</button>
        </div>
      </form>
    </div>
  </div>
</div>
<script>document.body.classList.add('modal-open');</script>
<?php endif; ?>

<?php require __DIR__ . '/_layout_bottom.php'; ?>
