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

/* ------------ Utilities: path & URL base ------------ */
if (!function_exists('starts_with')) {
  function starts_with($haystack, $needle) {
    return (string)$needle !== '' && strncmp($haystack, $needle, strlen($needle)) === 0;
  }
}
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'); // filesystem path ke /public
$docRoot    = str_replace('\\','/', realpath($_SERVER['DOCUMENT_ROOT'] ?? ''));
$publicAbs  = str_replace('\\','/', $publicRoot);

/* Hitung base URL ke folder /public, contoh: "/fortopolio/public" */
$publicUrlBase = $publicAbs;
if ($docRoot && starts_with($publicAbs, $docRoot)) {
  $publicUrlBase = substr($publicAbs, strlen($docRoot));
}
$publicUrlBase = '/' . ltrim($publicUrlBase, '/'); // pastikan diawali "/"

/* Direktori & URL upload */
$uploadDir = $publicRoot . '/uploads/profile';                       // filesystem
$uploadUrl = rtrim($publicUrlBase, '/') . '/uploads/profile';        // URL
if (!is_dir($uploadDir)) @mkdir($uploadDir, 0775, true);

/* ------------ Helpers upload ------------ */
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 ($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, '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 ?: 'profile');
  $name = trim($slug,'-') . '-' . substr(sha1(uniqid('',true)),0,8) . $ext;
  $dest = $uploadDir . '/' . $name;
  if (!@move_uploaded_file($file['tmp_name'], $dest)) return [null, 'Gagal simpan file'];
  return [$uploadUrl . '/' . $name, null]; // simpan sebagai URL publik absolut (dengan base)
}

/* Normalisasi URL publik ke path filesystem lalu hapus jika lokal */
function delete_local_if_any($imageUrl, $publicRoot, $publicUrlBase){
  if (!$imageUrl || is_abs_http($imageUrl)) return;

  // Bisa jadi tersimpan "/uploads/..." ATAU "/fortopolio/public/uploads/..."
  $rel = $imageUrl;
  if (!starts_with($rel, $publicUrlBase)) {
    if (starts_with($rel, '/uploads/')) {
      $rel = rtrim($publicUrlBase,'/') . $rel;
    } else {
      $rel = rtrim($publicUrlBase,'/') . '/' . ltrim($rel,'/');
    }
  }
  // Sekarang $rel diawali dengan $publicUrlBase → ubah ke path filesystem
  $fs = $publicRoot . substr($rel, strlen($publicUrlBase));
  if (is_file($fs)) @unlink($fs);
}

/* Pastikan URL publik yang konsisten untuk ditampilkan */
function to_public_url($path, $publicUrlBase){
  if (!$path) return '';
  if (is_abs_http($path)) return $path;
  if (starts_with($path, $publicUrlBase)) return $path;
  if (starts_with($path, '/uploads/')) return rtrim($publicUrlBase,'/') . $path;
  return rtrim($publicUrlBase,'/') . '/' . ltrim($path,'/');
}

/* ------------ Ambil 1 profil ------------ */
$p = $pdo->query("SELECT * FROM profile ORDER BY id DESC LIMIT 1")->fetch();

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

  if ($action === 'delete' && $p){
    delete_local_if_any($p['photo'] ?? null, $publicRoot, $publicUrlBase);
    $pdo->prepare("DELETE FROM profile WHERE id=?")->execute([$p['id']]);
    flash('ok','Profil dihapus.');
    header('Location: profile_edit.php'); exit;
  }

  $full = trim($_POST['full_name'] ?? '');
  $head = trim($_POST['headline'] ?? '');
  $bio  = trim($_POST['bio'] ?? '');
  if ($full === '') { flash('err','Nama lengkap wajib diisi.'); header('Location: profile_edit.php'); exit; }

  $finalPhoto = $p['photo'] ?? null;
  if (!empty($_FILES['photo_file'])) {
    [$saved, $err] = save_upload($_FILES['photo_file'], $full, $uploadDir, $uploadUrl);
    if ($err){ flash('err', $err); header('Location: profile_edit.php'); exit; }
    if ($saved){
      delete_local_if_any($finalPhoto, $publicRoot, $publicUrlBase);
      $finalPhoto = $saved; // sudah mengandung $publicUrlBase
    }
  }

  if ($p){
    $pdo->prepare("UPDATE profile SET full_name=?, headline=?, bio=?, photo=? WHERE id=?")
        ->execute([$full, $head ?: null, $bio ?: null, $finalPhoto, $p['id']]);
  } else {
    $pdo->prepare("INSERT INTO profile (full_name, headline, bio, photo) VALUES (?,?,?,?)")
        ->execute([$full, $head ?: null, $bio ?: null, $finalPhoto]);
  }
  flash('ok','Profil disimpan.');
  header('Location: profile_edit.php'); exit;
}

$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; 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-person-badge me-2"></i>Profil</h5>
      <div class="d-flex gap-2">
        <?php if($p): ?>
          <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#profileModal">
            <i class="bi bi-pencil-square me-1"></i>Edit
          </button>
          <form method="post" onsubmit="return confirm('Hapus profil ini?')">
            <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
            <input type="hidden" name="action" value="delete">
            <button class="btn btn-outline-danger btn-sm"><i class="bi bi-trash me-1"></i>Hapus</button>
          </form>
        <?php else: ?>
          <button class="btn btn-success btn-sm" data-bs-toggle="modal" data-bs-target="#profileModal">
            <i class="bi bi-plus-circle me-1"></i>Buat Profil
          </button>
        <?php endif; ?>
      </div>
    </div>

    <div class="card-body">
      <?php if($p): ?>
        <?php $imgUrl = to_public_url($p['photo'] ?? '', $publicUrlBase); ?>
        <div class="row g-4 align-items-start">
          <div class="col-md-3 text-center">
            <?php if(!empty($imgUrl)): ?>
              <img src="<?php echo e($imgUrl); ?>" class="img-fluid rounded border" style="max-height:220px;object-fit:cover" alt="Foto Profil">
            <?php else: ?>
              <div class="border rounded p-4 bg-light text-muted">Tidak ada foto</div>
            <?php endif; ?>
          </div>
          <div class="col-md-9">
            <h4 class="mb-1"><?php echo e($p['full_name'] ?? '—'); ?></h4>
            <div class="text-muted mb-3"><?php echo e($p['headline'] ?? '—'); ?></div>
            <p class="mb-0" style="white-space:pre-line"><?php echo e($p['bio'] ?? '—'); ?></p>
            <?php if(!empty($p['created_at'])): ?>
              <div class="text-muted small mt-3"><i class="bi bi-clock-history me-1"></i>Dibuat: <?php echo e($p['created_at']); ?></div>
            <?php endif; ?>
          </div>
        </div>
      <?php else: ?>
        <div class="text-center py-4">
          <p class="mb-3">Belum ada data profil.</p>
          <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#profileModal">
            <i class="bi bi-plus-lg me-1"></i>Buat Profil
          </button>
        </div>
      <?php endif; ?>
    </div>
  </div>
</div>

<!-- Modal: Buat/Edit Profil -->
<div class="modal fade" id="profileModal" 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="save">

        <div class="modal-header">
          <h5 class="modal-title"><?php echo $p ? 'Edit Profil' : 'Buat Profil'; ?></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 Lengkap</label>
              <input type="text" name="full_name" class="form-control" required value="<?php echo e($p['full_name'] ?? '') ?>">
            </div>
            <div class="col-md-6">
              <label class="form-label">Headline</label>
              <input type="text" name="headline" class="form-control" value="<?php echo e($p['headline'] ?? '') ?>">
            </div>

            <div class="col-md-6">
              <label class="form-label">Foto (Upload)</label>
              <input type="file" name="photo_file" accept="image/*" class="form-control">
              <div class="form-text">JPG/PNG/WEBP/GIF • maks 5MB. Jika diisi, akan menggantikan foto lama.</div>
            </div>
            <div class="col-md-6">
              <label class="form-label">Preview Saat Ini</label><br>
              <?php $pv = to_public_url($p['photo'] ?? '', $publicUrlBase); ?>
              <?php if(!empty($pv)): ?>
                <img src="<?php echo e($pv); ?>" class="img-thumbnail" style="max-height:120px;object-fit:cover" alt="">
              <?php else: ?>
                <div class="border rounded p-2 text-center text-muted bg-light">Belum ada</div>
              <?php endif; ?>
            </div>

            <div class="col-12">
              <label class="form-label">Bio</label>
              <textarea name="bio" class="form-control" rows="4" placeholder="Tuliskan ringkasan profil singkat Anda..."><?php echo e($p['bio'] ?? '') ?></textarea>
            </div>
          </div>
        </div>

        <div class="modal-footer">
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Batal</button>
          <button class="btn btn-primary"><i class="bi bi-save me-1"></i>Simpan</button>
        </div>
      </form>
    </div>
  </div>
</div>

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