<?php
// ====== BOOTSTRAP (tanpa output HTML) ======
require_once __DIR__ . '/../config/helpers.php';
require_once __DIR__ . '/../config/db.php';
require_login();

$pdo = db();

/* -----------------------
   Buat tabel galeri jika belum ada
------------------------ */
$pdo->exec("
  CREATE TABLE IF NOT EXISTS project_images (
    id INT AUTO_INCREMENT PRIMARY KEY,
    project_id INT NOT NULL,
    image VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX (project_id),
    CONSTRAINT fk_project_images_project
      FOREIGN KEY (project_id) REFERENCES projects(id)
      ON DELETE CASCADE
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

/* -----------------------
   Polyfill utility (PHP 7)
------------------------ */
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);
  }
}

/* -----------------------
   Paths & Public URL base
------------------------ */
// Root folder ke /public (filesystem)
$publicRoot = realpath(__DIR__ . '/../public') ?: (__DIR__ . '/../public');

// Hitung base URL ke folder /public, contoh hasil: "/fortopolio/public"
$docRoot = realpath($_SERVER['DOCUMENT_ROOT'] ?? '');
$publicUrlBase = str_replace('\\', '/', $publicRoot);
$docRootNorm   = str_replace('\\', '/', (string)$docRoot);

if ($docRootNorm && starts_with($publicUrlBase, $docRootNorm)) {
  $publicUrlBase = substr($publicUrlBase, strlen($docRootNorm));
}
$publicUrlBase = '/' . ltrim($publicUrlBase, '/'); // pastikan diawali "/"

// Direktori & URL upload
$uploadDir = $publicRoot . '/uploads/projects';
$uploadUrl = rtrim($publicUrlBase, '/') . '/uploads/projects';

// Pastikan folder upload ada
if (!is_dir($uploadDir)) {
  @mkdir($uploadDir, 0775, true);
}

/* -----------------------
   Helpers gambar
------------------------ */
function safe_ext_from_mime($tmpFile) {
  $finfo = new finfo(FILEINFO_MIME_TYPE);
  $mime  = $finfo->file($tmpFile);
  $map = ['image/jpeg'=>'.jpg','image/png'=>'.png','image/webp'=>'.webp','image/gif'=>'.gif'];
  return $map[$mime] ?? null;
}
function save_uploaded_image($file, $title, $uploadDir, $uploadUrl) {
  if (!isset($file['error']) || $file['error'] === UPLOAD_ERR_NO_FILE) return [null, null]; // tidak ada file
  if ($file['error'] !== UPLOAD_ERR_OK) return [null, 'Gagal upload (error code '.$file['error'].')'];
  if (($file['size'] ?? 0) > 5*1024*1024) return [null, 'Ukuran gambar maksimal 5MB.'];
  $ext = safe_ext_from_mime($file['tmp_name']);
  if (!$ext) return [null, 'Tipe file tidak didukung. Gunakan JPG/PNG/WEBP/GIF.'];
  $slug = preg_replace('~[^a-z0-9]+~i', '-', $title);
  $slug = trim($slug, '-');
  $name = $slug . '-' . substr(sha1(uniqid('', true)), 0, 10) . $ext;
  $target = $uploadDir . '/' . $name;
  if (!@move_uploaded_file($file['tmp_name'], $target)) return [null, 'Gagal menyimpan file upload.'];
  return [$uploadUrl . '/' . $name, null];
}
function unlink_if_local($publicRoot, $publicUrlBase, $imagePath) {
  if (!$imagePath) return;
  if (is_abs_http($imagePath)) return;
  $rel = $imagePath;
  if (!starts_with($rel, $publicUrlBase)) {
    if (starts_with($rel, '/uploads/')) {
      $rel = rtrim($publicUrlBase, '/') . $rel;
    } else {
      $rel = rtrim($publicUrlBase, '/') . '/' . ltrim($rel, '/');
    }
  }
  $full = $publicRoot . $rel;
  if (is_file($full)) @unlink($full);
}
function to_public_url($path, $publicUrlBase) {
  if (empty($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, '/');
}

/* -----------------------
   DELETE PROJECT (GET)
------------------------ */
if (isset($_GET['del'])) {
  $id = (int)$_GET['del'];

  // ambil image utama
  $st = $pdo->prepare("SELECT image FROM projects WHERE id=?");
  $st->execute([$id]);
  $pr = $st->fetch();

  // hapus galeri (hapus file manual)
  $gs = $pdo->prepare("SELECT image FROM project_images WHERE project_id=?");
  $gs->execute([$id]);
  foreach ($gs->fetchAll() as $g) {
    unlink_if_local($publicRoot, $publicUrlBase, $g['image'] ?? null);
  }

  // hapus record project_images (jaga-jaga jika FK tidak aktif)
  $pdo->prepare("DELETE FROM project_images WHERE project_id=?")->execute([$id]);

  // hapus record project
  $pdo->prepare("DELETE FROM projects WHERE id=?")->execute([$id]);

  // hapus file utama
  if ($pr && !empty($pr['image'])) {
    unlink_if_local($publicRoot, $publicUrlBase, $pr['image']);
  }

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

/* -----------------------
   DELETE SINGLE IMAGE (POST)
------------------------ */
if (is_post() && ($_POST['action'] ?? '') === 'delimg') {
  csrf_check();
  $imgId = (int)($_POST['img_id'] ?? 0);
  $pid   = (int)($_POST['project_id'] ?? 0);
  if ($imgId > 0 && $pid > 0) {
    $st = $pdo->prepare("SELECT image FROM project_images WHERE id=? AND project_id=?");
    $st->execute([$imgId, $pid]);
    if ($row = $st->fetch()) {
      unlink_if_local($publicRoot, $publicUrlBase, $row['image'] ?? null);
      $pdo->prepare("DELETE FROM project_images WHERE id=?")->execute([$imgId]);
      flash('ok','Gambar dihapus.');
    }
  }
  header('Location: projects.php?id='.$pid); exit;
}

/* -----------------------
   LOAD EDIT TARGET
------------------------ */
$edit = null; $gallery = [];
if (isset($_GET['id'])) {
  $st = $pdo->prepare("SELECT * FROM projects WHERE id=?");
  $st->execute([(int)$_GET['id']]);
  $edit = $st->fetch();
  if ($edit) {
    $gq = $pdo->prepare("SELECT * FROM project_images WHERE project_id=? ORDER BY created_at DESC, id DESC");
    $gq->execute([(int)$edit['id']]);
    $gallery = $gq->fetchAll();
  }
}

/* -----------------------
   CREATE/UPDATE (POST)
------------------------ */
if (is_post() && (!isset($_POST['action']) || $_POST['action'] !== 'delimg')) {
  csrf_check();

  $id    = (int)($_POST['id'] ?? 0);
  $title = trim($_POST['title'] ?? '');
  $desc  = trim($_POST['description'] ?? '');
  $link  = trim($_POST['link'] ?? '');
  $imgUrlInput = trim($_POST['image_url'] ?? '');

  if ($title === '') { flash('err','Judul wajib diisi.'); header('Location: projects.php'.($id?'?id='.$id:'')); exit; }

  // Gambar utama: prioritaskan upload
  $finalImage = $imgUrlInput;

  if (!empty($_FILES['image_file']) && $_FILES['image_file']['error'] !== UPLOAD_ERR_NO_FILE) {
    [$saved, $err] = save_uploaded_image($_FILES['image_file'], $title, $uploadDir, $uploadUrl);
    if ($err) { flash('err', $err); header('Location: projects.php'.($id?'?id='.$id:'')); exit; }
    $finalImage = $saved;

    // Jika update → hapus foto lama yang lokal
    if ($id) {
      $st = $pdo->prepare("SELECT image FROM projects WHERE id=?");
      $st->execute([$id]);
      $old = $st->fetch();
      if ($old && !empty($old['image'])) {
        unlink_if_local($publicRoot, $publicUrlBase, $old['image']);
      }
    }
  }

  if ($id) {
    $pdo->prepare("UPDATE projects SET title=?, description=?, image=?, link=? WHERE id=?")
        ->execute([$title, $desc, $finalImage, $link, $id]);
  } else {
    $pdo->prepare("INSERT INTO projects (title, description, image, link) VALUES (?,?,?,?)")
        ->execute([$title, $desc, $finalImage, $link]);
    $id = (int)$pdo->lastInsertId();
  }

  // Galeri multiple (simpan semua file yang valid; jika ada file gagal, lainnya tetap lanjut)
  if (!empty($_FILES['gallery']) && is_array($_FILES['gallery']['name'])) {
    $cnt = count($_FILES['gallery']['name']);
    for ($i=0; $i<$cnt; $i++) {
      // Lewati slot kosong
      if (!isset($_FILES['gallery']['error'][$i]) || $_FILES['gallery']['error'][$i] === UPLOAD_ERR_NO_FILE) continue;

      $file = [
        'name'     => $_FILES['gallery']['name'][$i] ?? '',
        'type'     => $_FILES['gallery']['type'][$i] ?? '',
        'tmp_name' => $_FILES['gallery']['tmp_name'][$i] ?? '',
        'error'    => $_FILES['gallery']['error'][$i] ?? UPLOAD_ERR_NO_FILE,
        'size'     => $_FILES['gallery']['size'][$i] ?? 0,
      ];

      [$saved, $err] = save_uploaded_image($file, $title.'-galeri', $uploadDir, $uploadUrl);
      if ($saved) {
        $pdo->prepare("INSERT INTO project_images (project_id, image) VALUES (?, ?)")
            ->execute([$id, $saved]);
      }
      // Jika $err ada, kita skip saja agar file lain tetap tersimpan
    }
  }

  flash('ok', 'Proyek disimpan.');
  header('Location: projects.php?id='.$id); exit;
}

/* -----------------------
   LOAD TABLE DATA
------------------------ */
$rows = $pdo->query("SELECT p.*, (SELECT COUNT(*) FROM project_images pi WHERE pi.project_id=p.id) AS img_count FROM projects p ORDER BY created_at DESC, id DESC")->fetchAll();

/* -----------------------
   VIEW DETAIL (GET ?view=ID)
------------------------ */
$view = null; $viewGallery = [];
if (isset($_GET['view'])) {
  $vid = (int)$_GET['view'];
  $st = $pdo->prepare("SELECT * FROM projects WHERE id=?");
  $st->execute([$vid]);
  $view = $st->fetch();
  if ($view) {
    $gq = $pdo->prepare("SELECT * FROM project_images WHERE project_id=? ORDER BY created_at DESC, id DESC");
    $gq->execute([$vid]);
    $viewGallery = $gq->fetchAll();
  }
}

/* -----------------------
   OUTPUT
------------------------ */
require_once __DIR__ . '/_layout_top.php';
$ok  = flash('ok'); $err = flash('err');
?>
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">

  <!-- FORM -->
  <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"><?php echo $edit ? 'Edit' : 'Tambah' ?> Proyek</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" enctype="multipart/form-data" class="grid grid-cols-1 gap-4" id="project-form">
        <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
        <input type="hidden" name="id" value="<?php echo e($edit['id'] ?? '') ?>">

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

        <div class="grid md:grid-cols-2 gap-4">
          <div>
            <label class="text-sm">Gambar Utama (Upload)</label>
            <input type="file" name="image_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.</p>
          </div>
          <div>
            <label class="text-sm">Gambar Utama (URL alternatif)</label>
            <input class="mt-1 w-full border rounded-lg px-3 py-2" name="image_url"
                   value="<?php echo e($edit['image'] ?? '') ?>" placeholder="https://...">
            <p class="text-xs text-gray-500 mt-1">Jika upload & URL diisi, yang dipakai adalah hasil upload.</p>
          </div>
        </div>

        <div>
          <label class="text-sm">Galeri Proyek (Multiple)</label>
          <div id="dropzone"
               class="mt-1 border-2 border-dashed rounded-lg p-4 text-center text-gray-600 hover:bg-gray-50 cursor-pointer">
            <div class="mb-2">Tarik & lepas gambar ke sini atau klik untuk memilih</div>
            <input type="file" name="gallery[]" id="gallery-input" accept="image/*" multiple class="hidden">
            <div id="preview" class="mt-2 grid grid-cols-3 md:grid-cols-4 gap-2"></div>
          </div>
          <p class="text-xs text-gray-500 mt-1">Bisa pilih banyak file sekaligus. Setiap file maks 5MB.</p>
        </div>

        <div>
          <label class="text-sm">Link Proyek</label>
          <input class="mt-1 w-full border rounded-lg px-3 py-2" name="link"
                 value="<?php echo e($edit['link'] ?? '') ?>" placeholder="https://github.com/...">
        </div>

        <div>
          <label class="text-sm">Deskripsi</label>
          <textarea class="mt-1 w-full border rounded-lg px-3 py-2" rows="5" name="description"><?php
            echo e($edit['description'] ?? '');
          ?></textarea>
        </div>

        <?php if(!empty($edit['image'])): ?>
        <div>
          <label class="text-sm block mb-1">Preview Gambar Utama</label>
          <?php $imgUrl = to_public_url($edit['image'], $publicUrlBase); ?>
          <img src="<?php echo e($imgUrl) ?>" alt="preview" class="max-h-40 rounded-lg border">
        </div>
        <?php endif; ?>

        <?php if(!empty($gallery)): ?>
        <div>
          <label class="text-sm block mb-2">Galeri Tersimpan</label>
          <div class="grid grid-cols-3 md:grid-cols-4 gap-3">
            <?php foreach ($gallery as $g): ?>
              <?php $gUrl = to_public_url($g['image'], $publicUrlBase); ?>
              <div class="relative group">
                <img src="<?php echo e($gUrl) ?>" class="h-24 w-full object-cover rounded border" alt="">
                <form method="post" class="absolute top-1 right-1 opacity-0 group-hover:opacity-100 transition"
                      onsubmit="return confirm('Hapus gambar ini?')">
                  <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
                  <input type="hidden" name="action" value="delimg">
                  <input type="hidden" name="img_id" value="<?php echo (int)$g['id'] ?>">
                  <input type="hidden" name="project_id" value="<?php echo (int)$edit['id'] ?>">
                  <button class="px-2 py-1 text-xs rounded bg-red-600 text-white">Hapus</button>
                </form>
              </div>
            <?php endforeach; ?>
          </div>
        </div>
        <?php endif; ?>

        <div>
          <button class="bg-blue-600 hover:bg-blue-700 text-white rounded-lg px-4 py-2">Simpan</button>
          <?php if($edit): ?><a href="projects.php" class="ml-2 px-4 py-2 rounded-lg border hover:bg-gray-50">Batal</a><?php endif; ?>
        </div>
      </form>
    </div>
  </div>

  <!-- TABLE -->
  <div class="bg-white rounded-xl border border-gray-200 overflow-x-auto">
    <div class="p-5 border-b flex items-center justify-between">
      <h2 class="font-semibold">Daftar Proyek</h2>
      <a href="projects.php" class="text-sm text-primary hover:underline">Refresh</a>
    </div>
    <table class="min-w-full text-sm">
      <thead class="bg-gray-50 text-gray-600">
        <tr>
          <th class="px-4 py-2 text-left">#</th>
          <th class="px-4 py-2 text-left">Thumbnail</th>
          <th class="px-4 py-2 text-left">Judul</th>
          <th class="px-4 py-2 text-left">Link</th>
          <th class="px-4 py-2 text-left">Dibuat</th>
          <th class="px-4 py-2 text-left">Aksi</th>
        </tr>
      </thead>
      <tbody>
      <?php foreach($rows as $r): ?>
        <tr class="border-t align-top">
          <td class="px-4 py-2"><?php echo (int)$r['id'] ?></td>
          <td class="px-4 py-2">
            <?php if(!empty($r['image'])): ?>
              <?php $thumb = to_public_url($r['image'], $publicUrlBase); ?>
              <img src="<?php echo e($thumb) ?>" alt="" class="h-14 w-20 object-cover rounded border">
            <?php else: ?>
              <span class="text-gray-400">—</span>
            <?php endif; ?>
          </td>
          <td class="px-4 py-2">
            <div class="font-medium"><?php echo e($r['title']) ?></div>
            <?php if(!empty($r['description'])): ?>
              <div class="text-gray-500 line-clamp-2 max-w-xs"><?php echo e($r['description']) ?></div>
            <?php endif; ?>
            <?php if((int)($r['img_count'] ?? 0) > 0): ?>
              <div class="text-xs text-gray-500 mt-1"><?php echo (int)$r['img_count']; ?> foto galeri</div>
            <?php endif; ?>
          </td>
          <td class="px-4 py-2">
            <?php if(!empty($r['link'])): ?>
              <a class="text-primary hover:underline" href="<?php echo e($r['link']) ?>" target="_blank" rel="noopener">Buka</a>
            <?php else: ?>
              <span class="text-gray-400">—</span>
            <?php endif; ?>
          </td>
          <td class="px-4 py-2"><?php echo e($r['created_at'] ?? ''); ?></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="?view=<?php echo (int)$r['id'] ?>">Lihat</a>
              <a class="px-2 py-1 rounded border text-sm" href="?id=<?php echo (int)$r['id'] ?>">Edit</a>
              <a class="px-2 py-1 rounded border border-red-300 text-red-700 text-sm"
                 href="?del=<?php echo (int)$r['id'] ?>"
                 onclick="return confirm('Hapus proyek ini?')">Hapus</a>
            </div>
          </td>
        </tr>
      <?php endforeach; if(empty($rows)): ?>
        <tr><td colspan="6" class="px-4 py-6 text-center text-gray-500">Belum ada data.</td></tr>
      <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- MODAL VIEW DETAIL -->
<?php if($view): ?>
  <?php
    $vImg = to_public_url($view['image'] ?? '', $publicUrlBase);
    $vLink = trim($view['link'] ?? '');
  ?>
  <div id="project-viewer" class="fixed inset-0 z-[100] flex items-start justify-center bg-black/50 p-4">
    <div class="bg-white w-full max-w-4xl rounded-xl shadow-2xl overflow-hidden">
      <div class="flex items-center justify-between border-b px-5 py-3">
        <h3 class="font-semibold text-lg">Detail Proyek: <?php echo e($view['title'] ?? ''); ?></h3>
        <div class="flex items-center gap-2">
          <?php if($vLink): ?>
            <a href="<?php echo e($vLink) ?>" target="_blank" rel="noopener"
               class="px-3 py-1.5 rounded border text-sm hover:bg-gray-50">Buka Link</a>
          <?php endif; ?>
          <button class="px-3 py-1.5 rounded border text-sm hover:bg-gray-50" onclick="closeViewer()">Tutup</button>
        </div>
      </div>

      <div class="p-5 grid md:grid-cols-2 gap-5">
        <div class="space-y-3">
          <div class="text-sm text-gray-500">Dibuat: <?php echo e($view['created_at'] ?? ''); ?></div>
          <?php if($vImg): ?>
            <img src="<?php echo e($vImg) ?>" class="w-full max-h-72 object-cover rounded border" alt="">
          <?php else: ?>
            <div class="w-full h-48 bg-gray-100 rounded border flex items-center justify-center text-gray-400">Tidak ada gambar utama</div>
          <?php endif; ?>
        </div>
        <div>
          <div class="font-medium mb-2">Deskripsi</div>
          <div class="text-gray-700 whitespace-pre-line"><?php echo e($view['description'] ?? ''); ?></div>
        </div>
      </div>

      <div class="px-5 pb-5">
        <div class="font-medium mb-2">Galeri</div>
        <?php if(!empty($viewGallery)): ?>
          <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
            <?php foreach ($viewGallery as $g): ?>
              <?php $gUrl = to_public_url($g['image'], $publicUrlBase); ?>
              <a href="<?php echo e($gUrl) ?>" target="_blank" class="block">
                <img src="<?php echo e($gUrl) ?>" class="h-28 w-full object-cover rounded border hover:opacity-90" alt="">
              </a>
            <?php endforeach; ?>
          </div>
        <?php else: ?>
          <div class="text-gray-500">Belum ada foto galeri.</div>
        <?php endif; ?>
      </div>
    </div>
  </div>
  <script>
    function closeViewer(){
      const url = new URL(window.location.href);
      url.searchParams.delete('view');
      window.location.href = url.toString();
    }
    document.getElementById('project-viewer')?.addEventListener('click', function(e){
      if(e.target === this){ closeViewer(); }
    });
    document.addEventListener('keydown', function(e){
      if(e.key === 'Escape') closeViewer();
    });
  </script>
<?php endif; ?>

<!-- Drag & Drop JS (vanilla) -->
<script>
(function(){
  const dz = document.getElementById('dropzone');
  const input = document.getElementById('gallery-input');
  const preview = document.getElementById('preview');
  if(!dz || !input || !preview) return;

  function renderThumb(file){
    const url = URL.createObjectURL(file);
    const img = document.createElement('img');
    img.src = url;
    img.className = 'h-24 w-full object-cover rounded border';
    const wrap = document.createElement('div');
    wrap.appendChild(img);
    preview.appendChild(wrap);
  }
  function addFiles(files){
    const dt = new DataTransfer();
    for (const f of input.files) dt.items.add(f);  // keep existing
    Array.from(files).forEach(f => { renderThumb(f); dt.items.add(f); });
    input.files = dt.files;
  }
  dz.addEventListener('click', () => input.click());
  dz.addEventListener('dragover', e => { e.preventDefault(); dz.classList.add('bg-gray-50'); });
  dz.addEventListener('dragleave', () => dz.classList.remove('bg-gray-50'));
  dz.addEventListener('drop', e => {
    e.preventDefault(); dz.classList.remove('bg-gray-50');
    if (e.dataTransfer && e.dataTransfer.files) addFiles(e.dataTransfer.files);
  });
  input.addEventListener('change', e => Array.from(e.target.files).forEach(renderThumb));
})();
</script>

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