<?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'); }
}

/* upload helpers */
function ensure_gallery_dir(): string {
  $base = realpath(__DIR__ . "/../img");
  $dir  = $base . "/gallery";
  if (!is_dir($dir)) @mkdir($dir, 0755, true);
  return $dir;
}

function save_gallery_photo(?string $current): ?string {
  if (empty($_FILES['file']['name'])) return $current;

  $allowed = ['jpg','jpeg','png','webp'];
  $ext = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));
  if (!in_array($ext, $allowed, true)) return $current;

  $name = time() . '_' . bin2hex(random_bytes(4)) . '.' . $ext;

  $dir = ensure_gallery_dir();
  $tmp = $_FILES['file']['tmp_name'] ?? '';
  if (!is_uploaded_file($tmp)) return $current;

  if (!move_uploaded_file($tmp, $dir . "/" . $name)) return $current;
  return $name;
}

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

/* mode */
$isNew  = !empty($_GET['new']);
$isEdit = !empty($_GET['edit']);
$id     = (int)($_GET['id'] ?? 0);

$row = [
  'id'        => 0,
  'type'      => 'photo',
  'title'     => '',
  'file'      => '',
  'video_url' => '',
];

if ($isEdit && $id > 0) {
  $st = $pdo->prepare("SELECT * FROM gallery WHERE id=? LIMIT 1");
  $st->execute([$id]);
  $dbrow = $st->fetch(PDO::FETCH_ASSOC);
  if (!$dbrow) { http_response_code(404); die("Qeyd tapılmadı."); }
  $row = array_merge($row, $dbrow);
}

/* save */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $type  = trim((string)($_POST['type'] ?? ''));
  $title = trim((string)($_POST['title'] ?? ''));
  $video = trim((string)($_POST['video_url'] ?? ''));

  if ($type !== 'photo' && $type !== 'video') $type = 'photo';

  $currentFile = (string)($row['file'] ?? '');
  $newFile = $currentFile;

  if ($type === 'photo') {
    $newFile = save_gallery_photo($currentFile);

    // photo üçün mütləq file olsun (yeni əlavə edəndə)
    if (($isNew || empty($currentFile)) && empty($newFile)) {
      $error = "Foto yükləyin.";
    }
    $video = ''; // photo seçilibsə video_url boşaldırıq
  } else { // video
    // video üçün URL mütləqdir
    if ($video === '') $error = "Video linki (video_url) daxil edin.";

    // video seçilibsə file (thumbnail) istəyə görə ola bilər, istəyirsən saxla:
    // istəyirsən ümumiyyətlə boşaldıb qalsın:
    // $newFile = $currentFile;  // toxunmuruq
  }

  if ($error === '') {
    if ($isEdit && $id > 0) {
      $upd = $pdo->prepare("
        UPDATE gallery
        SET type=?, title=?, file=?, video_url=?
        WHERE id=?
      ");
      $upd->execute([$type, $title, $newFile, $video, $id]);
      $success = "Yadda saxlanıldı.";
      // yenidən oxu
      $st = $pdo->prepare("SELECT * FROM gallery WHERE id=? LIMIT 1");
      $st->execute([$id]);
      $row = $st->fetch(PDO::FETCH_ASSOC) ?: $row;
    } else {
      $ins = $pdo->prepare("
        INSERT INTO gallery (type, title, file, video_url)
        VALUES (?,?,?,?)
      ");
      $ins->execute([$type, $title, $newFile, $video]);
      $newId = (int)$pdo->lastInsertId();
      header("Location: gallery_form.php?edit=1&id=".$newId);
      exit;
    }
  }
}

/* UI vars */
$valType  = (string)($row['type'] ?? 'photo');
$valTitle = (string)($row['title'] ?? '');
$valFile  = (string)($row['file'] ?? '');
$valUrl   = (string)($row['video_url'] ?? '');
?>

<div class="content-header">
  <div style="display:flex; gap:12px; align-items:center; justify-content:space-between;">
    <h1 style="margin:0;"><?= $isEdit ? "Qalereya: Redaktə" : "Qalereya: Yeni" ?></h1>
    <a class="btn btn-light" href="gallery.php">← Siyahıya qayıt</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">
    <form method="post" enctype="multipart/form-data" autocomplete="off">
      <div class="row" style="display:flex; gap:16px; flex-wrap:wrap;">
        <div style="flex:1; min-width:260px;">
          <label style="display:block; margin-bottom:6px;">Tip</label>
          <select name="type" id="type" class="form-control" style="width:100%;">
            <option value="photo" <?= $valType==='photo'?'selected':'' ?>>photo</option>
            <option value="video" <?= $valType==='video'?'selected':'' ?>>video</option>
          </select>
        </div>

        <div style="flex:2; min-width:320px;">
          <label style="display:block; margin-bottom:6px;">Başlıq (title)</label>
          <input type="text" name="title" class="form-control" value="<?= e($valTitle) ?>" placeholder="Məs: Klinikamızdan görüntülər">
        </div>
      </div>

      <div id="photoBox" style="margin-top:16px;">
        <label style="display:block; margin-bottom:6px;">Foto (file)</label>
        <input type="file" name="file" class="form-control" accept=".jpg,.jpeg,.png,.webp">

        <?php if (!empty($valFile)): ?>
          <div style="margin-top:12px; display:flex; gap:12px; align-items:center;">
            <a href="../img/gallery/<?= e(basename($valFile)) ?>" target="_blank">
              <img src="../img/gallery/<?= e(basename($valFile)) ?>" alt=""
                   style="width:160px;height:100px;object-fit:cover;border-radius:14px;border:1px solid rgba(0,0,0,.08);">
            </a>
            <div style="opacity:.75;">Cari fayl: <b><?= e($valFile) ?></b></div>
          </div>
        <?php endif; ?>
      </div>

      <div id="videoBox" style="margin-top:16px;">
        <label style="display:block; margin-bottom:6px;">Video linki (video_url)</label>
        <input type="text" name="video_url" class="form-control" value="<?= e($valUrl) ?>"
               placeholder="Məs: https://www.youtube.com/watch?v=... və ya https://youtu.be/...">
        <div style="margin-top:8px; font-size:13px; opacity:.7;">
          Qeyd: Video üçün “file” tələb olunmur (istəsən thumbnail əlavə edə bilərik).
        </div>
      </div>

      <div style="margin-top:18px; display:flex; gap:10px; align-items:center;">
        <button class="btn btn-primary" type="submit">Yadda saxla</button>
        <a class="btn btn-light" href="gallery.php">Ləğv et</a>
      </div>
    </form>
  </div>
</div>

<script>
(function(){
  const typeEl = document.getElementById('type');
  const photoBox = document.getElementById('photoBox');
  const videoBox = document.getElementById('videoBox');

  function sync(){
    const t = typeEl.value;
    if (t === 'video') {
      photoBox.style.display = 'none';
      videoBox.style.display = 'block';
    } else {
      photoBox.style.display = 'block';
      videoBox.style.display = 'none';
    }
  }
  typeEl.addEventListener('change', sync);
  sync();
})();
</script>

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