<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_login();

$db = get_db();
// ensure slides table exists
$db->exec("CREATE TABLE IF NOT EXISTS slides (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  title TEXT,
  subtitle TEXT,
  cta_label TEXT,
  image TEXT,
  link TEXT,
  display_order INTEGER DEFAULT 0,
  active INTEGER DEFAULT 1
)");

// Lightweight migration: if columns are missing (older DBs), add them
try {
  $cols = $db->query("PRAGMA table_info(slides)")->fetchAll(PDO::FETCH_ASSOC);
  $names = array_map(function($c){ return $c['name']; }, $cols ?: []);
  if (!in_array('subtitle', $names)) {
    $db->exec("ALTER TABLE slides ADD COLUMN subtitle TEXT");
  }
  if (!in_array('cta_label', $names)) {
    $db->exec("ALTER TABLE slides ADD COLUMN cta_label TEXT");
  }
} catch (Exception $e) {
  // ignore migration errors; page will still work without new columns (we use safe accessors)
}

$uploadsDir = __DIR__ . '/../data/uploads/slides';
if (!is_dir($uploadsDir)) mkdir($uploadsDir, 0755, true);

// helper: resize image using GD (max width/height)
function resize_image_gd($srcPath, $destPath, $maxWidth = 1200, $maxHeight = 800) {
  // Check if GD extension is available
  if (!extension_loaded('gd')) {
    return true; // Skip resize if GD not available, image already uploaded
  }
  
  $info = getimagesize($srcPath);
  if (!$info) return false;
  list($w, $h) = $info;
  $mime = $info['mime'];
  
  // Check if image functions exist
  if (!function_exists('imagecreatefromjpeg')) {
    return true; // Skip resize, GD not properly configured
  }
  
  switch ($mime) {
    case 'image/jpeg': $img = imagecreatefromjpeg($srcPath); break;
    case 'image/png': $img = imagecreatefrompng($srcPath); break;
    case 'image/gif': $img = imagecreatefromgif($srcPath); break;
    default: return false;
  }
  $ratio = min($maxWidth / $w, $maxHeight / $h, 1);
  $newW = (int)($w * $ratio);
  $newH = (int)($h * $ratio);
  $dst = imagecreatetruecolor($newW, $newH);
  // preserve PNG transparency
  if ($mime === 'image/png') {
    imagealphablending($dst, false);
    imagesavealpha($dst, true);
    $transparent = imagecolorallocatealpha($dst, 255, 255, 255, 127);
    imagefilledrectangle($dst, 0, 0, $newW, $newH, $transparent);
  }
  imagecopyresampled($dst, $img, 0,0,0,0, $newW, $newH, $w, $h);
  $ok = false;
  if ($mime === 'image/jpeg') $ok = imagejpeg($dst, $destPath, 85);
  elseif ($mime === 'image/png') $ok = imagepng($dst, $destPath);
  elseif ($mime === 'image/gif') $ok = imagegif($dst, $destPath);
  imagedestroy($img);
  imagedestroy($dst);
  return $ok;
}

// Handle delete
if (isset($_GET['delete'])) {
  $id = (int)$_GET['delete'];
  try {
    // Get image filename before delete
    $stmt = $db->prepare('SELECT image FROM slides WHERE id = :id');
    $stmt->execute([':id'=>$id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Delete from database
    $stmt = $db->prepare('DELETE FROM slides WHERE id = :id');
    $stmt->execute([':id'=>$id]);
    
    // Delete image file
    if ($row && !empty($row['image'])) {
      $imagePath = $uploadsDir . '/' . $row['image'];
      if (file_exists($imagePath)) {
        @unlink($imagePath);
      }
    }
    
    flash_set('success','Slide berhasil dihapus');
  } catch (Exception $e) {
    flash_set('error','Gagal menghapus: ' . $e->getMessage());
  }
  header('Location: slides.php');
  exit;
}

$editing = null;
// handle add
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'add') {
  $title = trim($_POST['title'] ?? '');
  $subtitle = trim($_POST['subtitle'] ?? '');
  $cta_label = trim($_POST['cta_label'] ?? '');
  $link = trim($_POST['link'] ?? '');
  $order = (int)($_POST['display_order'] ?? 0);
  $active = isset($_POST['active']) ? 1 : 0;
  $filename = null;
  if (!empty($_FILES['image']['name'])) {
    $tmp = $_FILES['image']['tmp_name'];
    $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
    $filename = uniqid('sl_') . '.' . $ext;
    $dest = $uploadsDir . '/' . $filename;
    move_uploaded_file($tmp, $dest);
    // resize to reasonable max dimensions
    resize_image_gd($dest, $dest, 1400, 900);
  }
  $stmt = $db->prepare('INSERT INTO slides (title,subtitle,cta_label,image,link,display_order,active) VALUES (:t,:sub,:cta,:i,:l,:o,:a)');
  $stmt->execute([':t'=>$title,':sub'=>$subtitle,':cta'=>$cta_label,':i'=>$filename,':l'=>$link,':o'=>$order,':a'=>$active]);
  flash_set('success','Slide ditambahkan');
  header('Location: slides.php'); exit;
}

// handle edit load
if (isset($_GET['edit'])) {
  $id = (int)$_GET['edit'];
  $stmt = $db->prepare('SELECT * FROM slides WHERE id = :id');
  $stmt->execute([':id'=>$id]);
  $editing = $stmt->fetch(PDO::FETCH_ASSOC);
}

// handle update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'update') {
  $id = (int)($_POST['id'] ?? 0);
  $title = trim($_POST['title'] ?? '');
  $subtitle = trim($_POST['subtitle'] ?? '');
  $cta_label = trim($_POST['cta_label'] ?? '');
  $link = trim($_POST['link'] ?? '');
  $order = (int)($_POST['display_order'] ?? 0);
  $active = isset($_POST['active']) ? 1 : 0;
  $filename = null;
  if (!empty($_FILES['image']['name'])) {
    $tmp = $_FILES['image']['tmp_name'];
    $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
    $filename = uniqid('sl_') . '.' . $ext;
    $dest = $uploadsDir . '/' . $filename;
    move_uploaded_file($tmp, $dest);
    resize_image_gd($dest, $dest, 1400, 900);
    // remove old
    $old = $db->prepare('SELECT image FROM slides WHERE id = :id'); $old->execute([':id'=>$id]); $r = $old->fetch(PDO::FETCH_ASSOC);
    if ($r && !empty($r['image'])) @unlink($uploadsDir . '/' . $r['image']);
  }
  $sql = 'UPDATE slides SET title=:t, subtitle=:sub, cta_label=:cta, link=:l, display_order=:o, active=:a';
  if ($filename) $sql .= ', image=:i';
  $sql .= ' WHERE id=:id';
  $params = [':t'=>$title,':sub'=>$subtitle,':cta'=>$cta_label,':l'=>$link,':o'=>$order,':id'=>$id,':a'=>$active];
  if ($filename) $params[':i'] = $filename;
  $db->prepare($sql)->execute($params);
  flash_set('success','Slide diperbarui');
  header('Location: slides.php'); exit;
}

$slides = $db->query('SELECT * FROM slides ORDER BY display_order ASC, id DESC')->fetchAll(PDO::FETCH_ASSOC);

require __DIR__ . '/_header.php';
?>
  <h1>Kelola Slides</h1>
  <?php if ($m = flash_get('success')): ?><div class="alert alert-success"><?php echo e($m); ?></div><?php endif; ?>

  <div class="card mb-3">
    <div class="card-body">
      <form method="post" enctype="multipart/form-data" class="row g-2 align-items-end">
        <input type="hidden" name="action" value="<?php echo $editing ? 'update' : 'add'; ?>">
        <?php if ($editing): ?><input type="hidden" name="id" value="<?php echo e($editing['id']); ?>"><?php endif; ?>
  <div class="col-md-4"><label>Judul</label><input name="title" value="<?php echo e($editing['title'] ?? ''); ?>" class="form-control"></div>
  <div class="col-md-4"><label>Subjudul</label><input name="subtitle" value="<?php echo e($editing['subtitle'] ?? ''); ?>" class="form-control"></div>
  <div class="col-md-3"><label>Label CTA (opsional)</label><input name="cta_label" value="<?php echo e($editing['cta_label'] ?? ''); ?>" class="form-control"></div>
  <div class="col-md-3"><label>Tautan (opsional)</label><input name="link" value="<?php echo e($editing['link'] ?? ''); ?>" class="form-control"></div>
        <div class="col-md-1"><label>Order</label><input name="display_order" value="<?php echo e($editing['display_order'] ?? 0); ?>" class="form-control" type="number"></div>
        <div class="col-md-2"><label>Aktif</label><div class="form-check"><input class="form-check-input" type="checkbox" name="active" <?php echo (!isset($editing) || ($editing && $editing['active'])) ? 'checked' : ''; ?>></div></div>
        <div class="col-md-6"><label>Gambar</label><input type="file" name="image" class="form-control-file"></div>
        <div class="col-md-2"><button class="btn btn-primary"><?php echo $editing ? 'Simpan Perubahan' : 'Tambah Slide'; ?></button></div>
      </form>
    </div>
  </div>

  <div class="card">
    <div class="card-body">
      <p>Seret baris untuk mengurutkan slide secara visual. Perubahan akan disimpan otomatis.</p>
      <table class="table table-bordered" id="slidesTable">
        <thead><tr><th style="width:40px"></th><th>#</th><th>Judul</th><th>Subjudul</th><th>Gambar</th><th>Order</th><th>Aktif</th><th>Aksi</th></tr></thead>
        <tbody id="slidesBody">
          <?php foreach ($slides as $i=>$s): ?>
            <tr data-id="<?php echo e($s['id']); ?>">
              <td class="drag-handle" style="cursor:move;text-align:center;"><i class="fa fa-bars"></i></td>
              <td><?php echo e($i+1); ?></td>
              <td><?php echo e($s['title'] ?? ''); ?></td>
              <td><?php echo e($s['subtitle'] ?? ''); ?></td>
              <td><?php if (!empty($s['image'])): ?><img src="<?php echo e(base_url()); ?>/data/uploads/slides/<?php echo e($s['image'] ?? ''); ?>" class="slide-thumb" style="height:48px;width:96px;object-fit:cover;border-radius:4px;cursor:pointer" data-full="<?php echo e(base_url()); ?>/data/uploads/slides/<?php echo e($s['image'] ?? ''); ?>" /><?php endif; ?></td>
              <td><?php echo e($s['display_order']); ?></td>
              <td><?php echo $s['active'] ? 'Ya' : 'Tidak'; ?></td>
              <td>
                <a href="slides.php?edit=<?php echo e($s['id']); ?>" class="btn btn-sm btn-primary">Edit</a>
                <a href="slides.php?delete=<?php echo e($s['id']); ?>" class="btn btn-sm btn-danger" onclick="return confirm('Hapus slide?')">Hapus</a>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
  
  <!-- Lightbox modal for preview -->
  <div class="modal fade" id="slidePreviewModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg">
      <div class="modal-content bg-transparent border-0">
        <div class="modal-body p-0 text-center">
          <img id="slidePreviewImage" src="" style="width:100%;height:auto;border-radius:.5rem;" />
        </div>
      </div>
    </div>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
  <script>
    (function(){
      var el = document.getElementById('slidesBody');
      if (!el) return;
      var sortable = Sortable.create(el, {
        handle: '.drag-handle',
        animation: 150,
        onEnd: function(evt){
          // gather new order
          var ids = Array.from(el.querySelectorAll('tr')).map(function(r){ return r.getAttribute('data-id'); });
          // send to server
          fetch('slides_reorder.php', {
            method: 'POST', headers: {'Content-Type':'application/json'},
            body: JSON.stringify({order: ids})
          }).then(function(r){ return r.json(); }).then(function(j){
            if (!j.success) alert('Gagal menyimpan urutan');
            else location.reload();
          }).catch(function(){ alert('Network error'); });
        }
      });

      // thumbnail click -> show modal preview
      document.querySelectorAll('.slide-thumb').forEach(function(img){
        img.addEventListener('click', function(){
          var src = img.getAttribute('data-full');
          document.getElementById('slidePreviewImage').src = src;
          var m = new bootstrap.Modal(document.getElementById('slidePreviewModal'));
          m.show();
        });
      });
    })();
  </script>

<?php require __DIR__ . '/_footer.php';
