<?php
// admin/about_edit.php
// ============================================================
// Fortopolio — Admin About (Edit)
// - Profile (email, address, whatsapp, dll)
// - CRUD Skills, Experiences, Certification (upload foto)
// - NEW: CRUD Studies (Riwayat Studi)
// - NEW: CRUD Trainings (Lembaga Pelatihan)
// ============================================================

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

/* -----------------------------------------
   Tabel skills (existing + category)
------------------------------------------ */
$pdo->exec("
  CREATE TABLE IF NOT EXISTS skills (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(120) NOT NULL,
    category VARCHAR(50) DEFAULT 'General',
    level TINYINT UNSIGNED DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

/* -----------------------------------------
   Tabel about (konten panjang)
------------------------------------------ */
$pdo->exec("
  CREATE TABLE IF NOT EXISTS about (
    id INT AUTO_INCREMENT PRIMARY KEY,
    content MEDIUMTEXT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");
$a = $pdo->query("SELECT * FROM about ORDER BY id DESC LIMIT 1")->fetch();

/* -----------------------------------------
   Tabel profile (single row) + email/address
------------------------------------------ */
$pdo->exec("
  CREATE TABLE IF NOT EXISTS profile (
    id INT AUTO_INCREMENT PRIMARY KEY,
    full_name VARCHAR(120) DEFAULT NULL,
    headline VARCHAR(180) DEFAULT NULL,
    bio TEXT DEFAULT NULL,
    photo VARCHAR(255) DEFAULT NULL,
    whatsapp VARCHAR(30) DEFAULT NULL,
    email VARCHAR(150) DEFAULT NULL,
    address TEXT DEFAULT NULL,
    alumni VARCHAR(180) DEFAULT NULL,
    linkedin_url VARCHAR(255) DEFAULT NULL,
    facebook_url VARCHAR(255) DEFAULT NULL,
    experience TEXT DEFAULT NULL,
    year_start SMALLINT DEFAULT NULL,
    year_end SMALLINT DEFAULT NULL,
    hobbies TEXT DEFAULT NULL,
    awards TEXT DEFAULT NULL,
    cert_name VARCHAR(180) DEFAULT NULL,
    cert_issuer VARCHAR(180) DEFAULT NULL,
    cert_valid_until DATE DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");
try { $pdo->exec("ALTER TABLE profile ADD COLUMN email VARCHAR(150) NULL AFTER whatsapp"); } catch (Throwable $e) {}
try { $pdo->exec("ALTER TABLE profile ADD COLUMN address TEXT NULL AFTER email"); } catch (Throwable $e) {}
$profile = $pdo->query("SELECT * FROM profile ORDER BY id ASC LIMIT 1")->fetch();

/* -----------------------------------------
   Tabel experiences (existing)
------------------------------------------ */
$pdo->exec("
  CREATE TABLE IF NOT EXISTS experiences (
    id INT AUTO_INCREMENT PRIMARY KEY,
    company VARCHAR(180) NOT NULL,
    position VARCHAR(140) DEFAULT NULL,
    start_year SMALLINT DEFAULT NULL,
    end_year SMALLINT DEFAULT NULL,
    responsibilities TEXT DEFAULT NULL,
    achievements TEXT DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

/* -----------------------------------------
   Helper upload foto sertifikat
------------------------------------------ */
if (!function_exists('is_abs_http')) {
  function is_abs_http($url){ return (bool)preg_match('~^https?://~i',(string)$url); }
}
$publicFs = realpath(__DIR__ . '/../public') ?: (__DIR__ . '/../public');
$docRootFs = rtrim(str_replace('\\','/', $_SERVER['DOCUMENT_ROOT'] ?? ''), '/');
$publicFsN = rtrim(str_replace('\\','/', $publicFs), '/');
$publicUrlBase = '';
if ($docRootFs && str_starts_with($publicFsN, $docRootFs)) {
  $tail = substr($publicFsN, strlen($docRootFs));
  $publicUrlBase = $tail ? ('/' . ltrim($tail,'/')) : '';
} else {
  $scriptBase = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? ''), '/');
  $publicUrlBase = $scriptBase ? preg_replace('~/admin$~','/public', $scriptBase) : '/public';
}
$certUploadDir = $publicFsN . '/uploads/certifications';
$certUploadUrl = rtrim($publicUrlBase, '/') . '/uploads/certifications';
if (!is_dir($certUploadDir)) { @mkdir($certUploadDir, 0775, true); }

function cert_ext_from_mime($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 cert_save_upload($file, $title, $dir, $url){
  if (empty($file) || $file['error'] === UPLOAD_ERR_NO_FILE) return [null, null];
  if ($file['error'] !== UPLOAD_ERR_OK)  return [null, 'Gagal upload (kode '.$file['error'].')'];
  if ($file['size'] > 5*1024*1024)       return [null, 'Maksimal 5MB'];
  $ext = cert_ext_from_mime($file['tmp_name']);
  if (!$ext) return [null, 'Format harus JPG/PNG/WEBP/GIF'];
  $slug = preg_replace('~[^a-z0-9]+~i','-', $title ?: 'cert');
  $name = trim($slug, '-') . '-' . substr(sha1(uniqid('', true)),0,10) . $ext;
  $dest = rtrim($dir,'/') . '/' . $name;
  if (!@move_uploaded_file($file['tmp_name'], $dest)) return [null, 'Gagal menyimpan file'];
  @chmod($dest, 0644);
  return [ rtrim($url,'/') . '/' . $name, null ];
}
function cert_unlink_if_local($path){
  if (!$path || is_abs_http($path)) return;
  $full = realpath(__DIR__ . '/../public' . $path);
  if ($full && is_file($full)) @unlink($full);
}

/* -----------------------------------------
   Tabel sertification (existing)
------------------------------------------ */
$pdo->exec("
  CREATE TABLE IF NOT EXISTS sertification (
    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;
");

/* -----------------------------------------
   NEW: Tabel studies (riwayat studi)
------------------------------------------ */
$pdo->exec("
  CREATE TABLE IF NOT EXISTS studies (
    id INT AUTO_INCREMENT PRIMARY KEY,
    institution   VARCHAR(180) NOT NULL,
    program       VARCHAR(180) DEFAULT NULL,
    start_year    SMALLINT DEFAULT NULL,
    end_year      SMALLINT DEFAULT NULL,
    grade         VARCHAR(50) DEFAULT NULL,
    result_status VARCHAR(20) DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

/* -----------------------------------------
   NEW: Tabel trainings (lembaga pelatihan)
------------------------------------------ */
$pdo->exec("
  CREATE TABLE IF NOT EXISTS trainings (
    id INT AUTO_INCREMENT PRIMARY KEY,
    org_name    VARCHAR(180) NOT NULL,   -- nama lembaga pelatihan
    course_name VARCHAR(180) NOT NULL,   -- pelatihan yang diikuti
    cert_no     VARCHAR(120) DEFAULT NULL, -- nomor sertifikat pelatihan
    year        SMALLINT DEFAULT NULL,   -- tahun pelatihan (opsional)
    created_at  TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

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

  // About
  if ($action === 'save_about') {
    $content = trim($_POST['content'] ?? '');
    if ($a) {
      $pdo->prepare("UPDATE about SET content=? WHERE id=?")->execute([$content, $a['id']]);
    } else {
      $pdo->prepare("INSERT INTO about(content) VALUES (?)")->execute([$content]);
    }
    flash('ok','Konten Tentang Saya disimpan.'); header('Location: about_edit.php'); exit;
  }

  // Skills
  if ($action === 'create_skill') {
    $name=trim($_POST['name']??''); $level=(int)($_POST['level']??0); $cat=trim($_POST['category']??'General');
    if ($name===''){ flash('err','Nama keahlian wajib diisi.'); header('Location: about_edit.php'); exit; }
    if ($level<0) $level=0; if($level>100) $level=100; if($cat==='') $cat='General'; $cat=mb_substr($cat,0,50,'UTF-8');
    $pdo->prepare("INSERT INTO skills(name,category,level)VALUES(?,?,?)")->execute([$name,$cat,$level]);
    flash('ok','Keahlian ditambahkan.'); header('Location: about_edit.php'); exit;
  }
  if ($action === 'update_skill') {
    $id=(int)($_POST['id']??0); $name=trim($_POST['name']??''); $level=(int)($_POST['level']??0); $cat=trim($_POST['category']??'General');
    if ($id<=0){ flash('err','ID keahlian tidak valid.'); header('Location: about_edit.php'); exit; }
    if ($name===''){ flash('err','Nama keahlian wajib diisi.'); header('Location: about_edit.php?sid='.$id); exit; }
    if ($level<0) $level=0; if($level>100) $level=100; if($cat==='') $cat='General'; $cat=mb_substr($cat,0,50,'UTF-8');
    $pdo->prepare("UPDATE skills SET name=?,category=?,level=? WHERE id=?")->execute([$name,$cat,$level,$id]);
    flash('ok','Keahlian diperbarui.'); header('Location: about_edit.php'); exit;
  }
  if ($action === 'delete_skill') {
    $id=(int)($_POST['id']??0);
    if($id>0){ $pdo->prepare("DELETE FROM skills WHERE id=?")->execute([$id]); flash('ok','Keahlian dihapus.'); }
    else { flash('err','ID keahlian tidak valid.'); }
    header('Location: about_edit.php'); exit;
  }

  // Profile extra
  if ($action === 'save_profile_extra') {
    $whatsapp = trim($_POST['whatsapp'] ?? '');
    $email    = trim($_POST['email'] ?? '');
    $address  = trim($_POST['address'] ?? '');
    $alumni   = trim($_POST['alumni'] ?? '');
    $linkedin = trim($_POST['linkedin_url'] ?? '');
    $facebook = trim($_POST['facebook_url'] ?? '');
    $experience = trim($_POST['experience'] ?? '');
    $year_start = (int)($_POST['year_start'] ?? 0);
    $year_end   = (int)($_POST['year_end'] ?? 0);
    $hobbies = trim($_POST['hobbies'] ?? '');
    $awards  = trim($_POST['awards'] ?? '');
    $cert_name  = trim($_POST['cert_name'] ?? '');
    $cert_issuer= trim($_POST['cert_issuer'] ?? '');
    $cert_valid_until = trim($_POST['cert_valid_until'] ?? '');

    if ($year_start <= 0) $year_start = null;
    if ($year_end   <= 0) $year_end   = null;
    if ($cert_valid_until === '') $cert_valid_until = null;

    if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
      flash('err','Format email tidak valid.'); header('Location: about_edit.php'); exit;
    }

    if ($profile) {
      $pdo->prepare("
        UPDATE profile
           SET whatsapp=?, email=?, address=?, alumni=?, linkedin_url=?, facebook_url=?, experience=?,
               year_start=?, year_end=?, hobbies=?, awards=?, cert_name=?, cert_issuer=?, cert_valid_until=?
         WHERE id=?
      ")->execute([
        $whatsapp ?: null, $email ?: null, $address ?: null, $alumni ?: null,
        $linkedin ?: null, $facebook ?: null, $experience ?: null,
        $year_start, $year_end, $hobbies ?: null, $awards ?: null,
        $cert_name ?: null, $cert_issuer ?: null, $cert_valid_until, (int)$profile['id']
      ]);
    } else {
      $pdo->prepare("
        INSERT INTO profile
          (whatsapp, email, address, alumni, linkedin_url, facebook_url, experience, year_start, year_end, hobbies, awards, cert_name, cert_issuer, cert_valid_until)
        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)
      ")->execute([
        $whatsapp ?: null, $email ?: null, $address ?: null, $alumni ?: null,
        $linkedin ?: null, $facebook ?: null, $experience ?: null,
        $year_start, $year_end, $hobbies ?: null, $awards ?: null,
        $cert_name ?: null, $cert_issuer ?: null, $cert_valid_until
      ]);
    }
    flash('ok','Informasi tambahan disimpan.');
    header('Location: about_edit.php'); exit;
  }

  // Experiences
  if ($action==='create_exp' || $action==='update_exp') {
    $eid=(int)($_POST['id']??0); $company=trim($_POST['company']??''); $position=trim($_POST['position']??'');
    $start=(int)($_POST['start_year']??0); $end=(int)($_POST['end_year']??0);
    $resp=trim($_POST['responsibilities']??''); $ach=trim($_POST['achievements']??'');
    if($company===''){ flash('err','Nama Perusahaan/Instansi wajib diisi.'); header('Location: about_edit.php'.($eid?'?eid='.$eid:'')); exit; }
    if($start<1900||$start>2100) $start=null; if($end<1900||$end>2100) $end=null;

    if($action==='update_exp'){
      if($eid<=0){ flash('err','ID pengalaman tidak valid.'); header('Location: about_edit.php'); exit; }
      $pdo->prepare("UPDATE experiences SET company=?,position=?,start_year=?,end_year=?,responsibilities=?,achievements=? WHERE id=?")
          ->execute([$company,$position?:null,$start,$end,$resp?:null,$ach?:null,$eid]);
      flash('ok','Pengalaman kerja diperbarui.');
    }else{
      $pdo->prepare("INSERT INTO experiences(company,position,start_year,end_year,responsibilities,achievements) VALUES (?,?,?,?,?,?)")
          ->execute([$company,$position?:null,$start,$end,$resp?:null,$ach?:null]);
      flash('ok','Pengalaman kerja ditambahkan.');
    }
    header('Location: about_edit.php'); exit;
  }
  if ($action==='delete_exp'){
    $eid=(int)($_POST['id']??0);
    if($eid>0){ $pdo->prepare("DELETE FROM experiences WHERE id=?")->execute([$eid]); flash('ok','Pengalaman kerja dihapus.'); }
    else { flash('err','ID pengalaman tidak valid.'); }
    header('Location: about_edit.php'); exit;
  }

  // Certification (CRUD + upload foto)
  if (in_array($action, ['create_cert','update_cert','delete_cert'], true)) {

    if ($action==='delete_cert'){
      $cid=(int)($_POST['id']??0);
      if($cid>0){
        $st=$pdo->prepare("SELECT cert_photo FROM sertification WHERE id=?"); $st->execute([$cid]);
        if($row=$st->fetch()){ cert_unlink_if_local($row['cert_photo']??null); }
        $pdo->prepare("DELETE FROM sertification WHERE id=?")->execute([$cid]);
        flash('ok','Sertifikat dihapus.');
      } else {
        flash('err','ID sertifikat tidak valid.');
      }
      header('Location: about_edit.php'); exit;
    }

    $cid=(int)($_POST['id']??0);
    $org_name=trim($_POST['org_name']??'');
    $cert_name=trim($_POST['cert_name']??'');
    $issue_year=(int)($_POST['issue_year']??0);
    $expire_year=(int)($_POST['expire_year']??0);
    $cert_url=trim($_POST['cert_url']??'');
    $cert_no=trim($_POST['cert_no']??'');

    if($org_name===''||$cert_name===''){ flash('err','Nama Instansi dan Nama Sertifikat wajib diisi.'); header('Location: about_edit.php'.($cid?('?cid='.$cid):'')); exit; }
    if($issue_year<1900||$issue_year>2100) $issue_year=null;
    if($expire_year<1900||$expire_year>2100) $expire_year=null;

    $photoFinal = null;
    if ($action==='update_cert'){
      if($cid<=0){ flash('err','ID sertifikat tidak valid.'); header('Location: about_edit.php'); exit; }
      $st=$pdo->prepare("SELECT cert_photo FROM sertification WHERE id=?"); $st->execute([$cid]);
      $old=$st->fetch(); $photoFinal=$old['cert_photo'] ?? null;
    }

    if (!empty($_FILES['cert_photo_file'])) {
      [$saved,$uerr] = cert_save_upload($_FILES['cert_photo_file'], $cert_name ?: $org_name, $certUploadDir, $certUploadUrl);
      if ($uerr){ flash('err',$uerr); header('Location: about_edit.php'.($cid?('?cid='.$cid):'')); exit; }
      if ($saved){ cert_unlink_if_local($photoFinal); $photoFinal=$saved; }
    }

    if ($action==='update_cert'){
      $pdo->prepare("
        UPDATE sertification
        SET org_name=?, issue_year=?, expire_year=?, cert_name=?, cert_url=?, cert_no=?, cert_photo=?
        WHERE id=?
      ")->execute([$org_name,$issue_year,$expire_year,$cert_name,$cert_url?:null,$cert_no?:null,$photoFinal,$cid]);
      flash('ok','Sertifikat diperbarui.');
    } else {
      $pdo->prepare("
        INSERT INTO sertification (org_name,issue_year,expire_year,cert_name,cert_url,cert_no,cert_photo)
        VALUES (?,?,?,?,?,?,?)
      ")->execute([$org_name,$issue_year,$expire_year,$cert_name,$cert_url?:null,$cert_no?:null,$photoFinal]);
      flash('ok','Sertifikat ditambahkan.');
    }
    header('Location: about_edit.php'); exit;
  }

  /* -------------------------------
     NEW: STUDIES (Riwayat Studi) CRUD
  -------------------------------- */
  if (in_array($action, ['create_study','update_study','delete_study'], true)) {
    if ($action === 'delete_study') {
      $sid = (int)($_POST['id'] ?? 0);
      if ($sid > 0) {
        $pdo->prepare("DELETE FROM studies WHERE id=?")->execute([$sid]);
        flash('ok','Data studi dihapus.');
      } else {
        flash('err','ID studi tidak valid.');
      }
      header('Location: about_edit.php'); exit;
    }

    $sid          = (int)($_POST['id'] ?? 0);
    $institution  = trim($_POST['institution'] ?? '');
    $program      = trim($_POST['program'] ?? '');
    $start_year   = (int)($_POST['start_year'] ?? 0);
    $end_year     = (int)($_POST['end_year'] ?? 0);
    $grade        = trim($_POST['grade'] ?? '');
    $result_status= trim($_POST['result_status'] ?? '');

    if ($institution === '') {
      flash('err','Nama sekolah/instansi pendidikan wajib diisi.');
      header('Location: about_edit.php'.($sid?'?sid2='.$sid:'')); exit;
    }
    if ($start_year < 1900 || $start_year > 2100) $start_year = null;
    if ($end_year   < 1900 || $end_year   > 2100) $end_year   = null;

    if (!in_array($result_status, ['Lulus','Memuaskan','Cumlaude'], true)) $result_status = null;

    if ($action === 'update_study') {
      if ($sid <= 0) { flash('err','ID studi tidak valid.'); header('Location: about_edit.php'); exit; }
      $pdo->prepare("UPDATE studies SET institution=?, program=?, start_year=?, end_year=?, grade=?, result_status=? WHERE id=?")
          ->execute([$institution, $program?:null, $start_year, $end_year, $grade?:null, $result_status?:null, $sid]);
      flash('ok','Riwayat studi diperbarui.');
    } else {
      $pdo->prepare("INSERT INTO studies(institution,program,start_year,end_year,grade,result_status) VALUES (?,?,?,?,?,?)")
          ->execute([$institution, $program?:null, $start_year, $end_year, $grade?:null, $result_status?:null]);
      flash('ok','Riwayat studi ditambahkan.');
    }
    header('Location: about_edit.php'); exit;
  }

  /* ----------------------------------
     NEW: TRAININGS (Pelatihan) CRUD
  ----------------------------------- */
  if (in_array($action, ['create_training','update_training','delete_training'], true)) {
    if ($action === 'delete_training') {
      $tid = (int)($_POST['id'] ?? 0);
      if ($tid > 0) {
        $pdo->prepare("DELETE FROM trainings WHERE id=?")->execute([$tid]);
        flash('ok','Data pelatihan dihapus.');
      } else {
        flash('err','ID pelatihan tidak valid.');
      }
      header('Location: about_edit.php'); exit;
    }

    $tid         = (int)($_POST['id'] ?? 0);
    $org_name    = trim($_POST['org_name'] ?? '');
    $course_name = trim($_POST['course_name'] ?? '');
    $cert_no     = trim($_POST['cert_no'] ?? '');
    $year        = (int)($_POST['year'] ?? 0);

    if ($org_name === '' || $course_name === '') {
      flash('err','Nama lembaga dan nama pelatihan wajib diisi.');
      header('Location: about_edit.php'.($tid?'?tid='.$tid:'')); exit;
    }
    if ($year < 1900 || $year > 2100) $year = null;

    if ($action === 'update_training') {
      if ($tid <= 0) { flash('err','ID pelatihan tidak valid.'); header('Location: about_edit.php'); exit; }
      $pdo->prepare("UPDATE trainings SET org_name=?, course_name=?, cert_no=?, year=? WHERE id=?")
          ->execute([$org_name, $course_name, $cert_no?:null, $year, $tid]);
      flash('ok','Pelatihan diperbarui.');
    } else {
      $pdo->prepare("INSERT INTO trainings(org_name,course_name,cert_no,year) VALUES (?,?,?,?)")
          ->execute([$org_name, $course_name, $cert_no?:null, $year]);
      flash('ok','Pelatihan ditambahkan.');
    }
    header('Location: about_edit.php'); exit;
  }
}

/* -----------------------------------------
   LOAD DATA UNTUK RENDER
------------------------------------------ */
$skills = $pdo->query("SELECT * FROM skills ORDER BY category ASC, created_at DESC, id DESC")->fetchAll();
$experiences = $pdo->query("SELECT * FROM experiences ORDER BY (CASE WHEN end_year IS NULL THEN 1 ELSE 0 END) DESC, end_year DESC, start_year DESC, id DESC")->fetchAll();
$certs = $pdo->query("SELECT * FROM sertification ORDER BY (expire_year IS NULL) DESC, expire_year DESC, issue_year DESC, id DESC")->fetchAll();

$studies   = $pdo->query("SELECT * FROM studies   ORDER BY end_year IS NULL DESC, end_year DESC, start_year DESC, id DESC")->fetchAll();
$trainings = $pdo->query("SELECT * FROM trainings ORDER BY year DESC, id DESC")->fetchAll();

$editSkill = null;
if (!empty($_GET['sid'])) { $st=$pdo->prepare("SELECT * FROM skills WHERE id=?"); $st->execute([(int)$_GET['sid']]); $editSkill=$st->fetch(); }
$editExp = null;
if (!empty($_GET['eid'])) { $st=$pdo->prepare("SELECT * FROM experiences WHERE id=?"); $st->execute([(int)$_GET['eid']]); $editExp=$st->fetch(); }
$editCert = null;
if (!empty($_GET['cid'])) { $st=$pdo->prepare("SELECT * FROM sertification WHERE id=?"); $st->execute([(int)$_GET['cid']]); $editCert=$st->fetch(); }
$editStudy = null;
if (!empty($_GET['sid2'])) { $st=$pdo->prepare("SELECT * FROM studies WHERE id=?"); $st->execute([(int)$_GET['sid2']]); $editStudy=$st->fetch(); }
$editTraining = null;
if (!empty($_GET['tid'])) { $st=$pdo->prepare("SELECT * FROM trainings WHERE id=?"); $st->execute([(int)$_GET['tid']]); $editTraining=$st->fetch(); }

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

/* -----------------------------------------
   UTIL: Badge warna kategori (Tailwind)
------------------------------------------ */
function badge_classes_for_category(?string $category): string {
  $cat = strtolower(trim((string)$category));
  $known = [
    'frontend' => ['bg' => 'blue-100',   'text' => 'blue-800'],
    'backend'  => ['bg' => 'green-100',  'text' => 'green-800'],
    'tools'    => ['bg' => 'amber-100',  'text' => 'amber-800'],
    'design'   => ['bg' => 'cyan-100',   'text' => 'cyan-800'],
    'devops'   => ['bg' => 'indigo-100', 'text' => 'indigo-800'],
    'mobile'   => ['bg' => 'violet-100', 'text' => 'violet-800'],
    'data'     => ['bg' => 'rose-100',   'text' => 'rose-800'],
    'security' => ['bg' => 'fuchsia-100','text' => 'fuchsia-800'],
    'ai'       => ['bg' => 'teal-100',   'text' => 'teal-800'],
    'general'  => ['bg' => 'slate-100',  'text' => 'slate-800'],
    'lainnya'  => ['bg' => 'slate-100',  'text' => 'slate-800'],
  ];
  if (isset($known[$cat])) return "bg-{$known[$cat]['bg']} text-{$known[$cat]['text']}";
  $palette = ['blue','green','amber','violet','rose','cyan','teal','fuchsia','lime','indigo','orange','pink','slate'];
  $hash = abs(crc32($cat ?: 'general'));
  $color = $palette[$hash % count($palette)];
  return "bg-{$color}-100 text-{$color}-800";
}

/* -----------------------------------------
   OUTPUT
------------------------------------------ */
require_once __DIR__ . '/_layout_top.php';
?>
<!-- ABOUT CONTENT CARD -->
<div class="bg-white rounded-xl border border-gray-200 mb-6">
  <div class="p-5 border-b flex items-center justify-between">
    <h2 class="font-semibold">Edit Tentang Saya</h2>
    <div class="flex items-center gap-2">
      <?php if($ok): ?><span class="text-sm text-emerald-700 bg-emerald-50 border border-emerald-100 rounded px-2 py-1"><?php echo e($ok) ?></span><?php endif; ?>
      <?php if($err): ?><span class="text-sm text-red-700 bg-red-50 border border-red-100 rounded px-2 py-1"><?php echo e($err) ?></span><?php endif; ?>
    </div>
  </div>
  <div class="p-5">
    <form method="post" class="grid gap-4">
      <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
      <input type="hidden" name="action" value="save_about">
      <label class="text-sm text-gray-700">Konten</label>
      <textarea class="w-full border rounded-lg px-3 py-2" rows="8" name="content"><?php echo e($a['content'] ?? '') ?></textarea>
      <div class="flex items-center gap-2">
        <button class="bg-blue-600 hover:bg-blue-700 text-white rounded-lg px-4 py-2">Simpan</button>
        <?php if($a): ?>
        <button type="submit" formaction="about_edit.php" formmethod="post"
                name="content" value=""
                class="bg-gray-100 hover:bg-gray-200 text-gray-800 rounded-lg px-4 py-2 border"
                onclick="this.form.action.value='save_about';return confirm('Kosongkan konten Tentang Saya?')">
          Kosongkan
        </button>
        <?php endif; ?>
      </div>
    </form>
  </div>
</div>

<!-- ABOUT EXTRA INFO CARD -->
<div class="bg-white rounded-xl border border-gray-200 mb-6">
  <div class="p-5 border-b">
    <h2 class="font-semibold">Informasi Tambahan (About)</h2>
  </div>
  <div class="p-5 grid grid-cols-1 lg:grid-cols-2 gap-6">
    <!-- Form -->
    <div>
      <form method="post" class="grid gap-3">
        <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
        <input type="hidden" name="action" value="save_profile_extra'">
        <input type="hidden" name="action" value="save_profile_extra">

        <div class="grid md:grid-cols-2 gap-3">
          <div>
            <label class="text-sm text-gray-700">No. WhatsApp</label>
            <input class="mt-1 w-full border rounded-lg px-3 py-2" name="whatsapp" placeholder="62xxxxxxxxxxx" value="<?php echo e($profile['whatsapp'] ?? '') ?>">
          </div>
          <div>
            <label class="text-sm text-gray-700">Email</label>
            <input type="email" class="mt-1 w-full border rounded-lg px-3 py-2" name="email" placeholder="nama@domain.com" value="<?php echo e($profile['email'] ?? '') ?>">
          </div>
        </div>

        <div class="grid md:grid-cols-2 gap-3">
          <div>
            <label class="text-sm text-gray-700">Alumni Kampus</label>
            <input class="mt-1 w-full border rounded-lg px-3 py-2" name="alumni" value="<?php echo e($profile['alumni'] ?? '') ?>">
          </div>
          <div>
            <label class="text-sm text-gray-700">LinkedIn URL</label>
            <input class="mt-1 w-full border rounded-lg px-3 py-2" name="linkedin_url" placeholder="https://www.linkedin.com/in/username" value="<?php echo e($profile['linkedin_url'] ?? '') ?>">
          </div>
        </div>

        <div class="grid md:grid-cols-2 gap-3">
          <div>
            <label class="text-sm text-gray-700">Facebook URL</label>
            <input class="mt-1 w-full border rounded-lg px-3 py-2" name="facebook_url" placeholder="https://facebook.com/username" value="<?php echo e($profile['facebook_url'] ?? '') ?>">
          </div>
          <div class="grid grid-cols-2 gap-3">
            <div>
              <label class="text-sm text-gray-700">Tahun Masuk</label>
              <input type="number" min="1900" max="2100" class="mt-1 w-full border rounded-lg px-3 py-2" name="year_start" value="<?php echo e($profile['year_start'] ?? '') ?>">
            </div>
            <div>
              <label class="text-sm text-gray-700">Tahun Keluar</label>
              <input type="number" min="1900" max="2100" class="mt-1 w-full border rounded-lg px-3 py-2" name="year_end" value="<?php echo e($profile['year_end'] ?? '') ?>" placeholder="Kosongkan jika masih aktif">
            </div>
          </div>
        </div>

        <div>
          <label class="text-sm text-gray-700">Alamat</label>
          <textarea class="mt-1 w-full border rounded-lg px-3 py-2" rows="2" name="address" placeholder="Nama jalan, RT/RW, Kel/Desa, Kec, Kota/Kab"><?php echo e($profile['address'] ?? '') ?></textarea>
        </div>

        <div>
          <label class="text-sm text-gray-700">Hobi</label>
          <textarea class="mt-1 w-full border rounded-lg px-3 py-2" rows="2" name="hobbies"><?php echo e($profile['hobbies'] ?? '') ?></textarea>
        </div>

        <div>
          <label class="text-sm text-gray-700">Penghargaan / Apresiasi</label>
          <textarea class="mt-1 w-full border rounded-lg px-3 py-2" rows="2" name="awards"><?php echo e($profile['awards'] ?? '') ?></textarea>
        </div>

        <div class="grid md:grid-cols-3 gap-3">
          <div>
            <label class="text-sm text-gray-700">Sertifikat Kompetensi</label>
            <input class="mt-1 w-full border rounded-lg px-3 py-2" name="cert_name" value="<?php echo e($profile['cert_name'] ?? '') ?>">
          </div>
          <div>
            <label class="text-sm text-gray-700">Penerbit Sertifikat</label>
            <input class="mt-1 w-full border rounded-lg px-3 py-2" name="cert_issuer" value="<?php echo e($profile['cert_issuer'] ?? '') ?>">
          </div>
          <div>
            <label class="text-sm text-gray-700">Masa Aktif Sertifikat</label>
            <input type="date" class="mt-1 w-full border rounded-lg px-3 py-2" name="cert_valid_until" value="<?php echo e($profile['cert_valid_until'] ?? '') ?>">
          </div>
        </div>

        <div>
          <button class="bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg px-4 py-2">Simpan Info</button>
        </div>
      </form>
    </div>

    <!-- Ringkasan -->
    <div>
      <div class="border rounded-lg overflow-hidden">
        <div class="px-4 py-2 bg-gray-50 border-b font-medium">Ringkasan Data</div>
        <table class="min-w-full text-sm">
          <tbody class="divide-y">
            <tr><td class="px-4 py-2 text-gray-500">WhatsApp</td><td class="px-4 py-2"><?php echo e($profile['whatsapp'] ?? '—') ?></td></tr>
            <tr>
              <td class="px-4 py-2 text-gray-500">Email</td>
              <td class="px-4 py-2">
                <?php $em = $profile['email'] ?? ''; echo $em ? '<a class="text-primary hover:underline" href="mailto:'.e($em).'">'.e($em).'</a>' : '—'; ?>
              </td>
            </tr>
            <tr><td class="px-4 py-2 text-gray-500">Alamat</td><td class="px-4 py-2 whitespace-pre-line"><?php echo e($profile['address'] ?? '—') ?></td></tr>
            <tr><td class="px-4 py-2 text-gray-500">Alumni</td><td class="px-4 py-2"><?php echo e($profile['alumni'] ?? '—') ?></td></tr>
            <tr><td class="px-4 py-2 text-gray-500">LinkedIn</td><td class="px-4 py-2"><?php echo !empty($profile['linkedin_url']) ? '<a class="text-primary hover:underline" target="_blank" href="'.e($profile['linkedin_url']).'">Buka</a>' : '—'; ?></td></tr>
            <tr><td class="px-4 py-2 text-gray-500">Facebook</td><td class="px-4 py-2"><?php echo !empty($profile['facebook_url']) ? '<a class="text-primary hover:underline" target="_blank" href="'.e($profile['facebook_url']).'">Buka</a>' : '—'; ?></td></tr>
            <tr><td class="px-4 py-2 text-gray-500">Periode</td><td class="px-4 py-2"><?php $ys=$profile['year_start']??null; $ye=$profile['year_end']??null; echo ($ys?:'—').' - '.($ye?:'Sekarang'); ?></td></tr>
            <tr><td class="px-4 py-2 text-gray-500">Hobi</td><td class="px-4 py-2"><?php echo e($profile['hobbies'] ?? '—') ?></td></tr>
            <tr><td class="px-4 py-2 text-gray-500">Penghargaan</td><td class="px-4 py-2 whitespace-pre-line"><?php echo e($profile['awards'] ?? '—') ?></td></tr>
            <tr><td class="px-4 py-2 text-gray-500">Sertifikat</td><td class="px-4 py-2"><?php echo e($profile['cert_name'] ?? '—') ?></td></tr>
            <tr><td class="px-4 py-2 text-gray-500">Penerbit</td><td class="px-4 py-2"><?php echo e($profile['cert_issuer'] ?? '—') ?></td></tr>
            <tr><td class="px-4 py-2 text-gray-500">Masa Aktif</td><td class="px-4 py-2"><?php echo !empty($profile['cert_valid_until']) ? e($profile['cert_valid_until']) : '—'; ?></td></tr>
          </tbody>
        </table>
      </div>
      <p class="text-xs text-gray-500 mt-2">Catatan: data tersimpan di tabel <code>profile</code>.</p>
    </div>
  </div>
</div>

<!-- RIWAYAT STUDI CARD -->
<div class="bg-white rounded-xl border border-gray-200 mb-6">
  <div class="p-5 border-b flex items-center justify-between">
    <h2 class="font-semibold">Riwayat Studi</h2>
    <?php if($editStudy): ?><a href="about_edit.php" class="text-sm text-primary hover:underline">Batal Edit</a><?php endif; ?>
  </div>

  <div class="p-5 grid grid-cols-1 lg:grid-cols-2 gap-6">
    <!-- Form -->
    <div>
      <h3 class="font-medium mb-3"><?php echo $editStudy ? 'Edit Studi' : 'Tambah Studi'; ?></h3>
      <form method="post" class="grid gap-3">
        <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
        <input type="hidden" name="action" value="<?php echo $editStudy ? 'update_study' : 'create_study'; ?>">
        <?php if($editStudy): ?><input type="hidden" name="id" value="<?php echo (int)$editStudy['id'] ?>"><?php endif; ?>

        <div>
          <label class="text-sm text-gray-700">Nama Sekolah / Institusi</label>
          <input class="mt-1 w-full border rounded-lg px-3 py-2" name="institution" required
                 value="<?php echo e($editStudy['institution'] ?? '') ?>" placeholder="Contoh: Universitas X / SMK Y">
        </div>

        <div class="grid md:grid-cols-2 gap-3">
          <div>
            <label class="text-sm text-gray-700">Program / Jurusan</label>
            <input class="mt-1 w-full border rounded-lg px-3 py-2" name="program"
                   value="<?php echo e($editStudy['program'] ?? '') ?>" placeholder="Contoh: S1 Informatika / RPL">
          </div>
          <div class="grid grid-cols-2 gap-3">
            <div>
              <label class="text-sm text-gray-700">Tahun Masuk</label>
              <input type="number" min="1900" max="2100" class="mt-1 w-full border rounded-lg px-3 py-2"
                     name="start_year" value="<?php echo e($editStudy['start_year'] ?? '') ?>">
            </div>
            <div>
              <label class="text-sm text-gray-700">Tahun Selesai</label>
              <input type="number" min="1900" max="2100" class="mt-1 w-full border rounded-lg px-3 py-2"
                     name="end_year" value="<?php echo e($editStudy['end_year'] ?? '') ?>" placeholder="Kosongkan jika masih aktif">
            </div>
          </div>
        </div>

        <div class="grid md:grid-cols-2 gap-3">
          <div>
            <label class="text-sm text-gray-700">Nilai / IPK</label>
            <input class="mt-1 w-full border rounded-lg px-3 py-2" name="grade"
                   value="<?php echo e($editStudy['grade'] ?? '') ?>" placeholder="Contoh: 3.65 / 92">
          </div>
          <div>
            <label class="text-sm text-gray-700">Hasil</label>
            <?php $rs = $editStudy['result_status'] ?? ''; ?>
            <select name="result_status" class="mt-1 w-full border rounded-lg px-3 py-2">
              <option value="">— Pilih —</option>
              <option value="Lulus" <?php echo $rs==='Lulus'?'selected':''; ?>>Lulus</option>
              <option value="Memuaskan" <?php echo $rs==='Memuaskan'?'selected':''; ?>>Lulus (Nilai Memuaskan)</option>
              <option value="Cumlaude" <?php echo $rs==='Cumlaude'?'selected':''; ?>>Lulus (Cumlaude)</option>
            </select>
          </div>
        </div>

        <div class="flex items-center gap-2">
          <button class="bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg px-4 py-2"><?php echo $editStudy ? 'Update' : 'Tambah'; ?></button>
          <?php if($editStudy): ?><a href="about_edit.php" class="px-4 py-2 rounded-lg border hover:bg-gray-50">Batal</a><?php else: ?><button type="reset" class="px-4 py-2 rounded-lg border hover:bg-gray-50">Reset</button><?php endif; ?>
        </div>
      </form>
    </div>

    <!-- Tabel -->
    <div>
      <div class="flex items-center justify-between mb-3">
        <h3 class="font-medium">Daftar Studi</h3>
        <a href="about_edit.php" class="text-sm text-primary hover:underline">Refresh</a>
      </div>
      <div class="overflow-x-auto border rounded-lg">
        <table class="min-w-full text-sm">
          <thead class="bg-gray-50 text-gray-600">
            <tr class="text-left">
              <th class="px-4 py-2">#</th>
              <th class="px-4 py-2">Institusi</th>
              <th class="px-4 py-2">Program</th>
              <th class="px-4 py-2">Periode</th>
              <th class="px-4 py-2">Nilai/Hasil</th>
              <th class="px-4 py-2">Aksi</th>
            </tr>
          </thead>
          <tbody>
          <?php foreach($studies as $s): ?>
            <tr class="border-t align-top">
              <td class="px-4 py-2"><?php echo (int)$s['id'] ?></td>
              <td class="px-4 py-2"><div class="font-medium"><?php echo e($s['institution']) ?></div></td>
              <td class="px-4 py-2"><?php echo e($s['program'] ?? '—') ?></td>
              <td class="px-4 py-2"><?php $sy=$s['start_year']??null; $ey=$s['end_year']??null; echo ($sy?:'—').' - '.($ey?:'Sekarang'); ?></td>
              <td class="px-4 py-2">
                <div><?php echo !empty($s['grade']) ? e($s['grade']) : '—'; ?></div>
                <div class="text-gray-500 text-xs"><?php echo !empty($s['result_status']) ? e($s['result_status']) : ''; ?></div>
              </td>
              <td class="px-4 py-2">
                <div class="flex items-center gap-2">
                  <a class="px-2 py-1 rounded border text-sm" href="about_edit.php?sid2=<?php echo (int)$s['id'] ?>">Edit</a>
                  <form method="post" onsubmit="return confirm('Hapus data studi ini?')">
                    <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
                    <input type="hidden" name="action" value="delete_study">
                    <input type="hidden" name="id" value="<?php echo (int)$s['id'] ?>">
                    <button class="px-2 py-1 rounded border border-red-300 text-red-700 text-sm">Hapus</button>
                  </form>
                </div>
              </td>
            </tr>
          <?php endforeach; if(empty($studies)): ?>
            <tr><td colspan="6" class="px-4 py-6 text-center text-gray-500">Belum ada riwayat studi.</td></tr>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<!-- LEMBAGA PELATIHAN CARD (BARU) -->
<div class="bg-white rounded-xl border border-gray-200 mb-6">
  <div class="p-5 border-b flex items-center justify-between">
    <h2 class="font-semibold">Lembaga Pelatihan</h2>
    <?php if($editTraining): ?><a href="about_edit.php" class="text-sm text-primary hover:underline">Batal Edit</a><?php endif; ?>
  </div>

  <div class="p-5 grid grid-cols-1 lg:grid-cols-2 gap-6">
    <!-- Form -->
    <div>
      <h3 class="font-medium mb-3"><?php echo $editTraining ? 'Edit Pelatihan' : 'Tambah Pelatihan'; ?></h3>
      <form method="post" class="grid gap-3">
        <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
        <input type="hidden" name="action" value="<?php echo $editTraining ? 'update_training' : 'create_training'; ?>">
        <?php if($editTraining): ?><input type="hidden" name="id" value="<?php echo (int)$editTraining['id'] ?>"><?php endif; ?>

        <div class="grid md:grid-cols-2 gap-3">
          <div>
            <label class="text-sm text-gray-700">Nama Lembaga Pelatihan</label>
            <input class="mt-1 w-full border rounded-lg px-3 py-2" name="org_name" required
                   value="<?php echo e($editTraining['org_name'] ?? '') ?>" placeholder="Contoh: Dicoding / Coursera / BNSP">
          </div>
          <div>
            <label class="text-sm text-gray-700">Pelatihan yang Diikuti</label>
            <input class="mt-1 w-full border rounded-lg px-3 py-2" name="course_name" required
                   value="<?php echo e($editTraining['course_name'] ?? '') ?>" placeholder="Contoh: Machine Learning A-Z">
          </div>
        </div>

        <div class="grid md:grid-cols-2 gap-3">
          <div>
            <label class="text-sm text-gray-700">No. Sertifikat Pelatihan</label>
            <input class="mt-1 w-full border rounded-lg px-3 py-2" name="cert_no"
                   value="<?php echo e($editTraining['cert_no'] ?? '') ?>" placeholder="Contoh: ABCD-1234-XYZ">
          </div>
          <div>
            <label class="text-sm text-gray-700">Tahun</label>
            <input type="number" min="1900" max="2100" class="mt-1 w-full border rounded-lg px-3 py-2"
                   name="year" value="<?php echo e($editTraining['year'] ?? '') ?>">
          </div>
        </div>

        <div class="flex items-center gap-2">
          <button class="bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg px-4 py-2"><?php echo $editTraining ? 'Update' : 'Tambah'; ?></button>
          <?php if($editTraining): ?>
            <a href="about_edit.php" class="px-4 py-2 rounded-lg border hover:bg-gray-50">Batal</a>
          <?php else: ?>
            <button type="reset" class="px-4 py-2 rounded-lg border hover:bg-gray-50">Reset</button>
          <?php endif; ?>
        </div>
      </form>
    </div>

    <!-- Tabel -->
    <div>
      <div class="flex items-center justify-between mb-3">
        <h3 class="font-medium">Daftar Pelatihan</h3>
        <a href="about_edit.php" class="text-sm text-primary hover:underline">Refresh</a>
      </div>
      <div class="overflow-x-auto border rounded-lg">
        <table class="min-w-full text-sm">
          <thead class="bg-gray-50 text-gray-600">
            <tr class="text-left">
              <th class="px-4 py-2">#</th>
              <th class="px-4 py-2">Lembaga</th>
              <th class="px-4 py-2">Pelatihan</th>
              <th class="px-4 py-2">No. Sertifikat</th>
              <th class="px-4 py-2">Tahun</th>
              <th class="px-4 py-2">Aksi</th>
            </tr>
          </thead>
          <tbody>
          <?php foreach($trainings as $t): ?>
            <tr class="border-t align-top">
              <td class="px-4 py-2"><?php echo (int)$t['id'] ?></td>
              <td class="px-4 py-2"><?php echo e($t['org_name']) ?></td>
              <td class="px-4 py-2"><?php echo e($t['course_name']) ?></td>
              <td class="px-4 py-2"><?php echo !empty($t['cert_no']) ? e($t['cert_no']) : '—'; ?></td>
              <td class="px-4 py-2"><?php echo !empty($t['year']) ? (int)$t['year'] : '—'; ?></td>
              <td class="px-4 py-2">
                <div class="flex items-center gap-2">
                  <a class="px-2 py-1 rounded border text-sm" href="about_edit.php?tid=<?php echo (int)$t['id'] ?>">Edit</a>
                  <form method="post" onsubmit="return confirm('Hapus data pelatihan ini?')">
                    <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
                    <input type="hidden" name="action" value="delete_training">
                    <input type="hidden" name="id" value="<?php echo (int)$t['id'] ?>">
                    <button class="px-2 py-1 rounded border border-red-300 text-red-700 text-sm">Hapus</button>
                  </form>
                </div>
              </td>
            </tr>
          <?php endforeach; if(empty($trainings)): ?>
            <tr><td colspan="6" class="px-4 py-6 text-center text-gray-500">Belum ada data pelatihan.</td></tr>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<!-- PENGALAMAN KERJA CARD -->
<div class="bg-white rounded-xl border border-gray-200 mb-6">
  <div class="p-5 border-b flex items-center justify-between">
    <h2 class="font-semibold">Pengalaman Kerja</h2>
    <?php if($editExp): ?><a href="about_edit.php" class="text-sm text-primary hover:underline">Batal Edit</a><?php endif; ?>
  </div>

  <div class="p-5 grid grid-cols-1 lg:grid-cols-2 gap-6">
    <!-- Form -->
    <div>
      <h3 class="font-medium mb-3"><?php echo $editExp ? 'Edit Pengalaman' : 'Tambah Pengalaman'; ?></h3>
      <form method="post" class="grid gap-3">
        <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
        <input type="hidden" name="action" value="<?php echo $editExp ? 'update_exp' : 'create_exp'; ?>">
        <?php if($editExp): ?><input type="hidden" name="id" value="<?php echo (int)$editExp['id'] ?>"><?php endif; ?>

        <div>
          <label class="text-sm text-gray-700">Perusahaan / Instansi</label>
          <input class="mt-1 w-full border rounded-lg px-3 py-2" name="company" value="<?php echo e($editExp['company'] ?? '') ?>" required>
        </div>

        <div class="grid md:grid-cols-2 gap-3">
          <div>
            <label class="text-sm text-gray-700">Jabatan</label>
            <input class="mt-1 w-full border rounded-lg px-3 py-2" name="position" value="<?php echo e($editExp['position'] ?? '') ?>">
          </div>
          <div class="grid grid-cols-2 gap-3">
            <div>
              <label class="text-sm text-gray-700">Tahun Masuk</label>
              <input type="number" min="1900" max="2100" class="mt-1 w-full border rounded-lg px-3 py-2" name="start_year" value="<?php echo e($editExp['start_year'] ?? '') ?>">
            </div>
            <div>
              <label class="text-sm text-gray-700">Tahun Selesai</label>
              <input type="number" min="1900" max="2100" class="mt-1 w-full border rounded-lg px-3 py-2" name="end_year" value="<?php echo e($editExp['end_year'] ?? '') ?>" placeholder="Kosongkan jika masih aktif">
            </div>
          </div>
        </div>

        <div>
          <label class="text-sm text-gray-700">Deskripsi Tanggung Jawab</label>
          <textarea class="mt-1 w-full border rounded-lg px-3 py-2" rows="4" name="responsibilities"><?php echo e($editExp['responsibilities'] ?? '') ?></textarea>
        </div>

        <div>
          <label class="text-sm text-gray-700">Pencapaian Kerja</label>
          <textarea class="mt-1 w-full border rounded-lg px-3 py-2" rows="3" name="achievements"><?php echo e($editExp['achievements'] ?? '') ?></textarea>
        </div>

        <div class="flex items-center gap-2">
          <button class="bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg px-4 py-2"><?php echo $editExp ? 'Update' : 'Tambah'; ?></button>
          <?php if($editExp): ?><a href="about_edit.php" class="px-4 py-2 rounded-lg border hover:bg-gray-50">Batal</a><?php else: ?><button type="reset" class="px-4 py-2 rounded-lg border hover:bg-gray-50">Reset</button><?php endif; ?>
        </div>
      </form>
    </div>

    <!-- Tabel -->
    <div>
      <div class="flex items-center justify-between mb-3">
        <h3 class="font-medium">Daftar Pengalaman</h3>
        <a href="about_edit.php" class="text-sm text-primary hover:underline">Refresh</a>
      </div>
      <div class="overflow-x-auto border rounded-lg">
        <table class="min-w-full text-sm">
          <thead class="bg-gray-50 text-gray-600">
            <tr class="text-left">
              <th class="px-4 py-2">#</th>
              <th class="px-4 py-2">Perusahaan</th>
              <th class="px-4 py-2">Jabatan</th>
              <th class="px-4 py-2">Periode</th>
              <th class="px-4 py-2">Aksi</th>
            </tr>
          </thead>
          <tbody>
          <?php foreach($experiences as $e): ?>
            <tr class="border-t align-top">
              <td class="px-4 py-2"><?php echo (int)$e['id'] ?></td>
              <td class="px-4 py-2">
                <div class="font-medium"><?php echo e($e['company']) ?></div>
                <?php if(!empty($e['responsibilities'])): ?><div class="text-gray-600 mt-1 whitespace-pre-line"><span class="text-xs text-gray-500">Tanggung jawab:</span> <?php echo e($e['responsibilities']) ?></div><?php endif; ?>
                <?php if(!empty($e['achievements'])): ?><div class="text-gray-600 mt-1 whitespace-pre-line"><span class="text-xs text-gray-500">Pencapaian:</span> <?php echo e($e['achievements']) ?></div><?php endif; ?>
              </td>
              <td class="px-4 py-2"><?php echo e($e['position'] ?? '—') ?></td>
              <td class="px-4 py-2"><?php $sy=$e['start_year']??null; $ey=$e['end_year']??null; echo ($sy?:'—').' - '.($ey?:'Sekarang'); ?></td>
              <td class="px-4 py-2">
                <div class="flex items-center gap-2">
                  <a class="px-2 py-1 rounded border text-sm" href="about_edit.php?eid=<?php echo (int)$e['id'] ?>">Edit</a>
                  <form method="post" onsubmit="return confirm('Hapus pengalaman ini?')">
                    <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
                    <input type="hidden" name="action" value="delete_exp">
                    <input type="hidden" name="id" value="<?php echo (int)$e['id'] ?>">
                    <button class="px-2 py-1 rounded border border-red-300 text-red-700 text-sm">Hapus</button>
                  </form>
                </div>
              </td>
            </tr>
          <?php endforeach; if(empty($experiences)): ?>
            <tr><td colspan="5" class="px-4 py-6 text-center text-gray-500">Belum ada pengalaman.</td></tr>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<!-- SERTIFICATION CARD -->
<div class="bg-white rounded-xl border border-gray-200 mb-6">
  <div class="p-5 border-b flex items-center justify-between">
    <h2 class="font-semibold">Sertification</h2>
    <?php if($editCert): ?><a href="about_edit.php" class="text-sm text-primary hover:underline">Batal Edit</a><?php endif; ?>
  </div>

  <div class="p-5 grid grid-cols-1 lg:grid-cols-2 gap-6">
    <!-- Form -->
    <div>
      <h3 class="font-medium mb-3"><?php echo $editCert ? 'Edit Sertifikat' : 'Tambah Sertifikat'; ?></h3>
      <form method="post" enctype="multipart/form-data" class="grid gap-3">
        <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
        <input type="hidden" name="action" value="<?php echo $editCert ? 'update_cert' : 'create_cert'; ?>">
        <?php if($editCert): ?><input type="hidden" name="id" value="<?php echo (int)$editCert['id'] ?>"><?php endif; ?>

        <div class="grid md:grid-cols-2 gap-3">
          <div>
            <label class="text-sm text-gray-700">Nama Instansi</label>
            <input class="mt-1 w-full border rounded-lg px-3 py-2" name="org_name" value="<?php echo e($editCert['org_name'] ?? '') ?>" placeholder="Contoh: EC-Council" required>
          </div>
          <div>
            <label class="text-sm text-gray-700">Nama Sertifikat</label>
            <input class="mt-1 w-full border rounded-lg px-3 py-2" name="cert_name" value="<?php echo e($editCert['cert_name'] ?? '') ?>" placeholder="Contoh: CEH" required>
          </div>
        </div>

        <div class="grid md:grid-cols-3 gap-3">
          <div>
            <label class="text-sm text-gray-700">Tahun Terbit</label>
            <input type="number" min="1900" max="2100" class="mt-1 w-full border rounded-lg px-3 py-2" name="issue_year" value="<?php echo e($editCert['issue_year'] ?? '') ?>">
          </div>
          <div>
            <label class="text-sm text-gray-700">Tahun Expired</label>
            <input type="number" min="1900" max="2100" class="mt-1 w-full border rounded-lg px-3 py-2" name="expire_year" value="<?php echo e($editCert['expire_year'] ?? '') ?>">
          </div>
          <div>
            <label class="text-sm text-gray-700">No. Sertifikat</label>
            <input class="mt-1 w-full border rounded-lg px-3 py-2" name="cert_no" value="<?php echo e($editCert['cert_no'] ?? '') ?>">
          </div>
        </div>

        <div class="grid md:grid-cols-2 gap-3">
          <div>
            <label class="text-sm text-gray-700">URL Sertifikat</label>
            <input class="mt-1 w-full border rounded-lg px-3 py-2" name="cert_url" value="<?php echo e($editCert['cert_url'] ?? '') ?>" placeholder="https://verify.example/...">
          </div>
          <div>
            <label class="text-sm text-gray-700">Foto Sertifikat (Upload)</label>
            <input type="file" name="cert_photo_file" accept="image/*" class="mt-1 w-full border rounded-lg px-3 py-2 bg-white">
            <p class="text-xs text-gray-500 mt-1">JPG/PNG/WEBP/GIF • Maks 5MB. Jika diisi, menggantikan foto lama.</p>
          </div>
        </div>

        <?php if(!empty($editCert['cert_photo'])): ?>
          <div>
            <label class="text-sm block mb-1">Preview Saat Ini</label>
            <img src="<?php echo e($editCert['cert_photo']); ?>" loading="lazy" class="max-h-36 rounded border" style="object-fit:cover" alt="Sertifikat">
          </div>
        <?php endif; ?>

        <div class="flex items-center gap-2">
          <button class="bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg px-4 py-2"><?php echo $editCert ? 'Update' : 'Tambah'; ?></button>
          <?php if($editCert): ?><a href="about_edit.php" class="px-4 py-2 rounded-lg border hover:bg-gray-50">Batal</a><?php else: ?><button type="reset" class="px-4 py-2 rounded-lg border hover:bg-gray-50">Reset</button><?php endif; ?>
        </div>
      </form>
    </div>

    <!-- Tabel Sertifikat -->
    <div>
      <div class="flex items-center justify-between mb-3">
        <h3 class="font-medium">Daftar Sertifikat</h3>
        <a href="about_edit.php" class="text-sm text-primary hover:underline">Refresh</a>
      </div>
      <div class="overflow-x-auto border rounded-lg">
        <table class="min-w-full text-sm">
          <thead class="bg-gray-50 text-gray-600">
            <tr class="text-left">
              <th class="px-4 py-2">#</th>
              <th class="px-4 py-2">Sertifikat</th>
              <th class="px-4 py-2">Periode</th>
              <th class="px-4 py-2">Aksi</th>
            </tr>
          </thead>
          <tbody>
          <?php foreach($certs as $c): ?>
            <tr class="border-t align-top">
              <td class="px-4 py-2"><?php echo (int)$c['id'] ?></td>
              <td class="px-4 py-2">
                <div class="font-medium"><?php echo e($c['cert_name']) ?> <span class="text-gray-500">• <?php echo e($c['org_name']) ?></span></div>
                <div class="text-gray-600 mt-1">
                  <?php if(!empty($c['cert_no'])): ?><div class="text-xs">No: <?php echo e($c['cert_no']); ?></div><?php endif; ?>
                  <?php if(!empty($c['cert_url'])): ?><a class="text-primary text-sm hover:underline" target="_blank" href="<?php echo e($c['cert_url']); ?>">Lihat / Verifikasi</a><?php endif; ?>
                </div>
                <?php if(!empty($c['cert_photo'])): ?>
                  <div class="mt-2">
                    <img src="<?php echo e($c['cert_photo']); ?>" loading="lazy" class="h-20 rounded border" style="object-fit:cover" alt="Foto sertifikat">
                  </div>
                <?php endif; ?>
              </td>
              <td class="px-4 py-2"><?php $iy=$c['issue_year']??null; $ey=$c['expire_year']??null; echo ($iy?:'—').' - '.($ey?:'—'); ?></td>
              <td class="px-4 py-2">
                <div class="flex items-center gap-2">
                  <a class="px-2 py-1 rounded border text-sm" href="about_edit.php?cid=<?php echo (int)$c['id'] ?>">Edit</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_cert">
                    <input type="hidden" name="id" value="<?php echo (int)$c['id'] ?>">
                    <button class="px-2 py-1 rounded border border-red-300 text-red-700 text-sm">Hapus</button>
                  </form>
                </div>
              </td>
            </tr>
          <?php endforeach; if(empty($certs)): ?>
            <tr><td colspan="4" class="px-4 py-6 text-center text-gray-500">Belum ada sertifikat.</td></tr>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<!-- SKILLS CARD -->
<div class="bg-white rounded-xl border border-gray-200">
  <div class="p-5 border-b flex items-center justify-between">
    <h2 class="font-semibold">Keahlian</h2>
    <?php if($editSkill): ?><a href="about_edit.php" class="text-sm text-primary hover:underline">Batal Edit</a><?php endif; ?>
  </div>

  <div class="p-5 grid grid-cols-1 lg:grid-cols-2 gap-6">
    <!-- Form -->
    <div>
      <h3 class="font-medium mb-3"><?php echo $editSkill ? 'Edit Keahlian' : 'Tambah Keahlian'; ?></h3>
      <form method="post" class="grid gap-3">
        <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
        <input type="hidden" name="action" value="<?php echo $editSkill ? 'update_skill' : 'create_skill'; ?>">
        <?php if($editSkill): ?><input type="hidden" name="id" value="<?php echo (int)$editSkill['id'] ?>"><?php endif; ?>
        <div>
          <label class="text-sm text-gray-700">Nama Keahlian</label>
          <input class="mt-1 w-full border rounded-lg px-3 py-2" name="name" value="<?php echo e($editSkill['name'] ?? '') ?>" required>
        </div>
        <div>
          <label class="text-sm text-gray-700">Kategori (manual)</label>
          <input class="mt-1 w-full border rounded-lg px-3 py-2" name="category" value="<?php echo e($editSkill['category'] ?? 'General') ?>" maxlength="50">
        </div>
        <div>
          <label class="text-sm text-gray-700">Level (0–100)</label>
          <input type="number" min="0" max="100" class="mt-1 w-full border rounded-lg px-3 py-2" name="level" value="<?php echo e($editSkill['level'] ?? '70') ?>" required>
        </div>
        <div class="flex items-center gap-2">
          <button class="bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg px-4 py-2"><?php echo $editSkill ? 'Update' : 'Tambah'; ?></button>
          <?php if($editSkill): ?><a href="about_edit.php" class="px-4 py-2 rounded-lg border hover:bg-gray-50">Batal</a><?php else: ?><button type="reset" class="px-4 py-2 rounded-lg border hover:bg-gray-50">Reset</button><?php endif; ?>
        </div>
      </form>
    </div>

    <!-- Tabel -->
    <div>
      <div class="flex items-center justify-between mb-3">
        <h3 class="font-medium">Daftar Keahlian</h3>
        <a href="about_edit.php" class="text-sm text-primary hover:underline">Refresh</a>
      </div>
      <div class="overflow-x-auto border rounded-lg">
        <table class="min-w-full text-sm">
          <thead class="bg-gray-50 text-gray-600">
            <tr class="text-left">
              <th class="px-4 py-2">#</th>
              <th class="px-4 py-2">Keahlian</th>
              <th class="px-4 py-2">Kategori</th>
              <th class="px-4 py-2">Level</th>
              <th class="px-4 py-2">Aksi</th>
            </tr>
          </thead>
          <tbody>
          <?php foreach($skills as $s): ?>
            <tr class="border-t">
              <td class="px-4 py-2"><?php echo (int)$s['id'] ?></td>
              <td class="px-4 py-2"><?php echo e($s['name']) ?></td>
              <td class="px-4 py-2">
                <?php $cat=$s['category'] ?? 'General'; $badgeClasses=badge_classes_for_category($cat); ?>
                <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium <?php echo e($badgeClasses); ?>"><?php echo e($cat) ?></span>
              </td>
              <td class="px-4 py-2">
                <div class="flex items-center gap-2">
                  <div class="w-40 h-2 rounded-full bg-gray-200 overflow-hidden">
                    <div class="h-2 bg-blue-600" style="width:<?php echo max(0,min(100,(int)$s['level'])) ?>%"></div>
                  </div>
                  <span class="text-gray-700"><?php echo (int)$s['level'] ?>%</span>
                </div>
              </td>
              <td class="px-4 py-2">
                <div class="flex items-center gap-2">
                  <a class="px-2 py-1 rounded border text-sm" href="about_edit.php?sid=<?php echo (int)$s['id'] ?>">Edit</a>
                  <form method="post" onsubmit="return confirm('Hapus keahlian ini?')">
                    <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
                    <input type="hidden" name="action" value="delete_skill">
                    <input type="hidden" name="id" value="<?php echo (int)$s['id'] ?>">
                    <button class="px-2 py-1 rounded border border-red-300 text-red-700 text-sm">Hapus</button>
                  </form>
                </div>
              </td>
            </tr>
          <?php endforeach; if(empty($skills)): ?>
            <tr><td colspan="5" class="px-4 py-6 text-center text-gray-500">Belum ada keahlian.</td></tr>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

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