<?php
require_once __DIR__ . "/../config/db.php";
require_once __DIR__ . "/../lib/auth.php";
require_once __DIR__ . "/../lib/helpers.php";
require_once __DIR__ . "/../admin/admin_menu.php";
require_admin();

if (!function_exists('e')) {
  function e($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
}

$success = '';
$error   = '';

/* Delete */
if (isset($_GET['del'])) {
  $id = (int)$_GET['del'];
  if ($id > 0) {
    // əvvəl cari faylı tap
    $st = $pdo->prepare("SELECT id, type, file FROM gallery WHERE id=? LIMIT 1");
    $st->execute([$id]);
    $row = $st->fetch(PDO::FETCH_ASSOC);

    if ($row) {
      // DB-dən sil
      $del = $pdo->prepare("DELETE FROM gallery WHERE id=?");
      $del->execute([$id]);

      // əgər photo idisə və fayl var idisə diskte də sil
      if (($row['type'] ?? '') === 'photo' && !empty($row['file'])) {
        $path = realpath(__DIR__ . "/../img") . "/gallery/" . basename((string)$row['file']);
        if (is_file($path)) @unlink($path);
      }

      $success = "Silindi.";
    } else {
      $error = "Silmək üçün qeyd tapılmadı.";
    }
  }
}

/* Filter */
$type = trim((string)($_GET['type'] ?? ''));
$where = "";
$params = [];

if ($type === 'photo' || $type === 'video') {
  $where = "WHERE type = ?";
  $params[] = $type;
}

/* List */
$q = "SELECT id, type, title, file, video_url, created_at
      FROM gallery
      $where
      ORDER BY id DESC";
$st = $pdo->prepare($q);
$st->execute($params);
$items = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];
?>

<div class="content-header">
  <div style="display:flex; gap:12px; align-items:center; justify-content:space-between;">
    <h1 style="margin:0;">Qalereya</h1>
    <a class="btn btn-primary" href="gallery_form.php?new=1">+ Yeni əlavə et</a>
  </div>

  <div style="margin-top:12px; display:flex; gap:10px; align-items:center; flex-wrap:wrap;">
    <a class="btn btn-light" href="gallery.php">Hamısı</a>
    <a class="btn btn-light" href="gallery.php?type=photo">Fotolar</a>
    <a class="btn btn-light" href="gallery.php?type=video">Videolar</a>
  </div>

  <?php if ($success): ?>
    <div class="alert alert-success" style="margin-top:12px;"><?= e($success) ?></div>
  <?php endif; ?>
  <?php if ($error): ?>
    <div class="alert alert-danger" style="margin-top:12px;"><?= e($error) ?></div>
  <?php endif; ?>
</div>

<div class="card">
  <div class="card-body" style="overflow:auto;">
    <table class="table" style="min-width:900px;">
      <thead>
        <tr>
          <th>#</th>
          <th>Tip</th>
          <th>Başlıq</th>
          <th>Preview</th>
          <th>Tarix</th>
          <th style="width:170px;">Əməliyyat</th>
        </tr>
      </thead>
      <tbody>
        <?php if (!$items): ?>
          <tr><td colspan="6" style="padding:18px;">Heç nə tapılmadı.</td></tr>
        <?php else: ?>
          <?php foreach ($items as $it): ?>
            <?php
              $id   = (int)($it['id'] ?? 0);
              $t    = (string)($it['type'] ?? '');
              $ttl  = (string)($it['title'] ?? '');
              $file = (string)($it['file'] ?? '');
              $url  = (string)($it['video_url'] ?? '');
            ?>
            <tr>
              <td><?= $id ?></td>
              <td><?= e($t) ?></td>
              <td><?= e($ttl) ?></td>

              <td>
                <?php if ($t === 'photo' && $file): ?>
                  <a href="../img/gallery/<?= e(basename($file)) ?>" target="_blank" style="display:inline-block;">
                    <img src="../img/gallery/<?= e(basename($file)) ?>" alt="" style="width:92px;height:60px;object-fit:cover;border-radius:10px;border:1px solid rgba(0,0,0,.08);">
                  </a>
                <?php elseif ($t === 'video' && $url): ?>
                  <a href="<?= e($url) ?>" target="_blank"><?= e($url) ?></a>
                <?php else: ?>
                  <span style="opacity:.6;">—</span>
                <?php endif; ?>
              </td>

              <td><?= e((string)($it['created_at'] ?? '')) ?></td>

              <td>
                <a class="btn btn-sm btn-warning" href="gallery_form.php?edit=1&id=<?= $id ?>">Redaktə</a>
                <a class="btn btn-sm btn-danger"
                   href="gallery.php?del=<?= $id ?>"
                   onclick="return confirm('Silmək istədiyinizə əminsiniz?');">
                   Sil
                </a>
              </td>
            </tr>
          <?php endforeach; ?>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<?php require_once __DIR__ . "/_layout_bottom.php"; ?>