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

$db = get_db();

// Create media table if not exists
$db->exec("CREATE TABLE IF NOT EXISTS media (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  title TEXT NOT NULL,
  description TEXT,
  type TEXT NOT NULL, -- 'photo' or 'video'
  file_path TEXT, -- for photos
  video_url TEXT, -- for YouTube/Vimeo embed
  thumbnail TEXT,
  category TEXT,
  date_uploaded TEXT DEFAULT CURRENT_TIMESTAMP,
  active INTEGER DEFAULT 1
)");

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

// Handle delete
if (isset($_GET['delete'])) {
  $id = (int)$_GET['delete'];
  try {
    $stmt = $db->prepare('SELECT file_path, thumbnail FROM media WHERE id = :id');
    $stmt->execute([':id'=>$id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    
    $db->prepare('DELETE FROM media WHERE id = :id')->execute([':id'=>$id]);
    
    if ($row && !empty($row['file_path'])) {
      @unlink($uploadsDir . '/' . $row['file_path']);
    }
    if ($row && !empty($row['thumbnail'])) {
      @unlink($uploadsDir . '/' . $row['thumbnail']);
    }
    
    flash_set('success','Media berhasil dihapus');
  } catch (Exception $e) {
    flash_set('error','Gagal menghapus: ' . $e->getMessage());
  }
  header('Location: media.php');
  exit;
}

$editing = null;

// Helper function to convert YouTube URL to embed
function convert_to_embed_url($url) {
  if (empty($url)) return '';
  
  // Already embed URL
  if (strpos($url, '/embed/') !== false || strpos($url, 'player.vimeo.com') !== false) {
    return $url;
  }
  
  // YouTube watch URL
  if (preg_match('/youtube\.com\/watch\?v=([a-zA-Z0-9_-]+)/', $url, $matches)) {
    return 'https://www.youtube.com/embed/' . $matches[1];
  }
  
  // YouTube short URL
  if (preg_match('/youtu\.be\/([a-zA-Z0-9_-]+)/', $url, $matches)) {
    return 'https://www.youtube.com/embed/' . $matches[1];
  }
  
  // Vimeo URL
  if (preg_match('/vimeo\.com\/(\d+)/', $url, $matches)) {
    return 'https://player.vimeo.com/video/' . $matches[1];
  }
  
  return $url;
}

// Handle add
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'add') {
  $title = trim($_POST['title'] ?? '');
  $description = trim($_POST['description'] ?? '');
  $type = $_POST['type'] ?? 'photo';
  $category = trim($_POST['category'] ?? '');
  $video_url = convert_to_embed_url(trim($_POST['video_url'] ?? ''));
  $active = isset($_POST['active']) ? 1 : 0;
  
  $file_path = null;
  $thumbnail = null;
  
  if ($type === 'photo' && !empty($_FILES['file']['name'])) {
    $tmp = $_FILES['file']['tmp_name'];
    $ext = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));
    $file_path = uniqid('media_') . '.' . $ext;
    $dest = $uploadsDir . '/' . $file_path;
    move_uploaded_file($tmp, $dest);
    
    // Create thumbnail
    $thumbnail = 'thumb_' . $file_path;
    $thumb_dest = $uploadsDir . '/' . $thumbnail;
    if (function_exists('imagecreatefromjpeg')) {
      copy($dest, $thumb_dest);
      // Resize thumbnail to 400x300
      resize_image_gd($thumb_dest, $thumb_dest, 400, 300);
    }
  }
  
  $stmt = $db->prepare('INSERT INTO media (title, description, type, file_path, video_url, thumbnail, category, active) VALUES (:t, :d, :ty, :f, :v, :th, :c, :a)');
  $stmt->execute([
    ':t'=>$title, ':d'=>$description, ':ty'=>$type, ':f'=>$file_path, 
    ':v'=>$video_url, ':th'=>$thumbnail, ':c'=>$category, ':a'=>$active
  ]);
  
  flash_set('success','Media berhasil ditambahkan');
  header('Location: media.php');
  exit;
}

// Handle edit load
if (isset($_GET['edit'])) {
  $id = (int)$_GET['edit'];
  $stmt = $db->prepare('SELECT * FROM media 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'] ?? '');
  $description = trim($_POST['description'] ?? '');
  $type = $_POST['type'] ?? 'photo';
  $category = trim($_POST['category'] ?? '');
  $video_url = convert_to_embed_url(trim($_POST['video_url'] ?? ''));
  $active = isset($_POST['active']) ? 1 : 0;
  
  $file_path = null;
  $thumbnail = null;
  
  if ($type === 'photo' && !empty($_FILES['file']['name'])) {
    $tmp = $_FILES['file']['tmp_name'];
    $ext = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));
    $file_path = uniqid('media_') . '.' . $ext;
    $dest = $uploadsDir . '/' . $file_path;
    move_uploaded_file($tmp, $dest);
    
    $thumbnail = 'thumb_' . $file_path;
    $thumb_dest = $uploadsDir . '/' . $thumbnail;
    if (function_exists('imagecreatefromjpeg')) {
      copy($dest, $thumb_dest);
      resize_image_gd($thumb_dest, $thumb_dest, 400, 300);
    }
    
    // Remove old files
    $old = $db->prepare('SELECT file_path, thumbnail FROM media WHERE id = :id');
    $old->execute([':id'=>$id]);
    $r = $old->fetch(PDO::FETCH_ASSOC);
    if ($r && !empty($r['file_path'])) @unlink($uploadsDir . '/' . $r['file_path']);
    if ($r && !empty($r['thumbnail'])) @unlink($uploadsDir . '/' . $r['thumbnail']);
  }
  
  $sql = 'UPDATE media SET title=:t, description=:d, type=:ty, video_url=:v, category=:c, active=:a';
  if ($file_path) $sql .= ', file_path=:f, thumbnail=:th';
  $sql .= ' WHERE id=:id';
  
  $params = [':t'=>$title, ':d'=>$description, ':ty'=>$type, ':v'=>$video_url, ':c'=>$category, ':a'=>$active, ':id'=>$id];
  if ($file_path) {
    $params[':f'] = $file_path;
    $params[':th'] = $thumbnail;
  }
  
  $db->prepare($sql)->execute($params);
  flash_set('success','Media berhasil diperbarui');
  header('Location: media.php');
  exit;
}

// Get all media
$media_list = $db->query('SELECT * FROM media ORDER BY date_uploaded DESC')->fetchAll(PDO::FETCH_ASSOC);

// Helper function for resize (if not exists)
if (!function_exists('resize_image_gd')) {
  function resize_image_gd($srcPath, $destPath, $maxWidth = 1200, $maxHeight = 800) {
    if (!extension_loaded('gd')) return true;
    $info = getimagesize($srcPath);
    if (!$info) return false;
    list($w, $h) = $info;
    $mime = $info['mime'];
    if (!function_exists('imagecreatefromjpeg')) return true;
    
    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);
    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;
  }
}

require __DIR__ . '/_header.php';
?>

<h1>Kelola Media (Galeri)</h1>
<?php if ($m = flash_get('success')): ?><div class="alert alert-success"><?php echo e($m); ?></div><?php endif; ?>
<?php if ($m = flash_get('error')): ?><div class="alert alert-danger"><?php echo e($m); ?></div><?php endif; ?>

<div class="card mb-3">
  <div class="card-body">
    <h5><?php echo $editing ? 'Edit Media' : 'Tambah Media Baru'; ?></h5>
    <form method="post" enctype="multipart/form-data">
      <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="row g-3">
        <div class="col-md-6">
          <label>Judul *</label>
          <input name="title" value="<?php echo e($editing['title'] ?? ''); ?>" class="form-control" required>
        </div>
        
        <div class="col-md-3">
          <label>Tipe *</label>
          <select name="type" class="form-control" id="mediaType" required>
            <option value="photo" <?php echo (!$editing || $editing['type'] === 'photo') ? 'selected' : ''; ?>>Foto</option>
            <option value="video" <?php echo ($editing && $editing['type'] === 'video') ? 'selected' : ''; ?>>Video</option>
          </select>
        </div>
        
        <div class="col-md-3">
          <label>Kategori</label>
          <input name="category" value="<?php echo e($editing['category'] ?? ''); ?>" class="form-control" placeholder="Kegiatan, Fasilitas, dll">
        </div>
        
        <div class="col-md-12">
          <label>Deskripsi</label>
          <textarea name="description" class="form-control" rows="2"><?php echo e($editing['description'] ?? ''); ?></textarea>
        </div>
        
        <div class="col-md-6" id="photoField">
          <label>Upload Foto</label>
          <input type="file" name="file" class="form-control" accept="image/*">
          <?php if ($editing && $editing['type'] === 'photo' && !empty($editing['file_path'])): ?>
            <small class="text-muted">File saat ini: <?php echo e($editing['file_path']); ?></small>
          <?php endif; ?>
        </div>
        
        <div class="col-md-6" id="videoField" style="display:none;">
          <label>URL Video (YouTube/Vimeo Embed) *</label>
          <input name="video_url" value="<?php echo e($editing['video_url'] ?? ''); ?>" class="form-control" placeholder="https://www.youtube.com/embed/VIDEO_ID">
          <small class="text-muted d-block mt-1">
            <strong>Contoh URL yang benar:</strong><br>
            YouTube: <code>https://www.youtube.com/embed/dQw4w9WgXcQ</code><br>
            Vimeo: <code>https://player.vimeo.com/video/123456789</code><br>
            <span class="text-danger">❌ Jangan gunakan URL biasa (youtube.com/watch?v=...)</span>
          </small>
        </div>
        
        <div class="col-md-2">
          <label>Status</label>
          <div class="form-check">
            <input class="form-check-input" type="checkbox" name="active" <?php echo (!isset($editing) || ($editing && $editing['active'])) ? 'checked' : ''; ?>>
            <label class="form-check-label">Aktif</label>
          </div>
        </div>
        
        <div class="col-md-12">
          <button class="btn btn-primary"><?php echo $editing ? 'Simpan Perubahan' : 'Tambah Media'; ?></button>
          <?php if ($editing): ?>
            <a href="media.php" class="btn btn-secondary">Batal</a>
          <?php endif; ?>
        </div>
      </div>
    </form>
  </div>
</div>

<div class="card">
  <div class="card-body">
    <h5>Daftar Media</h5>
    <div class="table-responsive">
      <table class="table table-bordered">
        <thead>
          <tr>
            <th style="width:80px">Preview</th>
            <th>Judul</th>
            <th>Tipe</th>
            <th>Kategori</th>
            <th>Tanggal</th>
            <th>Status</th>
            <th style="width:150px">Aksi</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($media_list as $m): ?>
            <tr>
              <td>
                <?php if ($m['type'] === 'photo' && !empty($m['thumbnail'])): ?>
                  <img src="<?php echo base_url(); ?>/data/uploads/media/<?php echo e($m['thumbnail']); ?>" style="width:60px;height:45px;object-fit:cover;border-radius:4px;">
                <?php elseif ($m['type'] === 'video'): ?>
                  <i class="fa fa-video fa-2x text-danger"></i>
                <?php endif; ?>
              </td>
              <td><?php echo e($m['title']); ?></td>
              <td><span class="badge bg-<?php echo $m['type'] === 'photo' ? 'info' : 'danger'; ?>"><?php echo ucfirst($m['type']); ?></span></td>
              <td><?php echo e($m['category'] ?? '-'); ?></td>
              <td><?php echo date('d M Y', strtotime($m['date_uploaded'])); ?></td>
              <td><?php echo $m['active'] ? '<span class="badge bg-success">Aktif</span>' : '<span class="badge bg-secondary">Nonaktif</span>'; ?></td>
              <td>
                <a href="media.php?edit=<?php echo $m['id']; ?>" class="btn btn-sm btn-primary">Edit</a>
                <a href="media.php?delete=<?php echo $m['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Hapus media ini?')">Hapus</a>
              </td>
            </tr>
          <?php endforeach; ?>
          <?php if (empty($media_list)): ?>
            <tr><td colspan="7" class="text-center text-muted">Belum ada media</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<script>
// Toggle photo/video fields
document.getElementById('mediaType').addEventListener('change', function() {
  const photoField = document.getElementById('photoField');
  const videoField = document.getElementById('videoField');
  
  if (this.value === 'photo') {
    photoField.style.display = 'block';
    videoField.style.display = 'none';
  } else {
    photoField.style.display = 'none';
    videoField.style.display = 'block';
  }
});

// Initialize on load
window.addEventListener('DOMContentLoaded', function() {
  const type = document.getElementById('mediaType').value;
  const photoField = document.getElementById('photoField');
  const videoField = document.getElementById('videoField');
  
  if (type === 'video') {
    photoField.style.display = 'none';
    videoField.style.display = 'block';
  }
});
</script>

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