<?php
require_once __DIR__ . '/auth_guard.php';
require_once __DIR__ . '/../backend/config/database.php';

$db = getDB();
$adminUserName = $_SESSION['user_name'];
$adminPage     = 'gallery';
$adminPageTitle= 'Gallery';

$msg   = '';
$error = '';
$uploadDir = __DIR__ . '/../backend/uploads/gallery/';

function detectMediaType(array $item): string {
  $rawType = strtolower(trim((string)($item['media_type'] ?? '')));
  if (in_array($rawType, ['image', 'video'], true)) {
    return $rawType;
  }

  $path = strtolower(parse_url((string)($item['image_url'] ?? ''), PHP_URL_PATH) ?? '');
  $ext = pathinfo($path, PATHINFO_EXTENSION);
  if (in_array($ext, ['mp4', 'webm', 'ogg', 'mov', 'm4v', 'avi', 'mkv'], true)) {
    return 'video';
  }

  if (!empty($item['image_url'])) {
    $urlPath = parse_url((string)$item['image_url'], PHP_URL_PATH);
    if (is_string($urlPath) && $urlPath !== '') {
      $rel = $urlPath;
      if (str_starts_with($rel, '/stile-lpg')) {
        $rel = substr($rel, strlen('/stile-lpg'));
      }
      $localPath = realpath(__DIR__ . '/..' . $rel);
      if ($localPath && file_exists($localPath)) {
        $mime = @mime_content_type($localPath);
        if (is_string($mime) && str_starts_with($mime, 'video/')) {
          return 'video';
        }
      }
    }
  }

  return 'image';
}

// ── Delete ─────────────────────────────────────────────────────────────────
if (isset($_GET['delete'])) {
    $row = $db->prepare("SELECT image_url FROM gallery WHERE id=?");
    $row->execute([$_GET['delete']]);
    $r = $row->fetch(PDO::FETCH_ASSOC);
    if ($r && $r['image_url'] && str_starts_with($r['image_url'], '/stile-lpg/backend/uploads/')) {
        $localPath = __DIR__ . '/../backend/uploads/gallery/' . basename($r['image_url']);
        if (file_exists($localPath)) @unlink($localPath);
    }
    $db->prepare("DELETE FROM gallery WHERE id=?")->execute([$_GET['delete']]);
    header('Location: /stile-lpg/admin/gallery.php?deleted=1');
    exit;
}
if (isset($_GET['deleted'])) $msg = 'Media deleted successfully.';

// ── Upload & Add ───────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_image'])) {
    $title = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $category = trim($_POST['category'] ?? 'General');

    if (!$title) {
        $error = 'Please enter a title.';
    } elseif (empty($_FILES['image_file']['name'])) {
        $error = 'Please choose an image or video file.';
    } else {
    $file     = $_FILES['image_file'];
    $ext      = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    $imageExts = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
    $videoExts = ['mp4', 'webm', 'ogg']; // Only allow web-compatible video formats
    $allowedExts = array_merge($imageExts, $videoExts);
    $maxBytes = 50 * 1024 * 1024; // 50 MB for videos

    if (!in_array($ext, $allowedExts)) {
      $error = 'Only JPG, PNG, WebP, GIF, MP4, WebM, OGG files are allowed.';
    } elseif ($file['size'] > $maxBytes) {
      $error = 'File is too large. Max 50 MB.';
    } else {
      $filename  = 'gal_' . bin2hex(random_bytes(8)) . '.' . $ext;
      $destPath  = $uploadDir . $filename;
      if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
      if (move_uploaded_file($file['tmp_name'], $destPath)) {
        $imageUrl = '/stile-lpg/backend/uploads/gallery/' . $filename;
        $id = 'gal_' . bin2hex(random_bytes(8));
        $mediaType = in_array($ext, $videoExts) ? 'video' : 'image';
        // MIME type check for video
        if ($mediaType === 'video') {
          $finfo = finfo_open(FILEINFO_MIME_TYPE);
          $mime = finfo_file($finfo, $destPath);
          finfo_close($finfo);
          if (!in_array($mime, ['video/mp4', 'video/webm', 'video/ogg'])) {
            $error = 'Video format not supported for web playback. Please upload MP4, WebM, or OGG.';
            @unlink($destPath);
          } else {
            // Check if media_type column exists
            try {
              $db->prepare("INSERT INTO gallery(id,title,description,image_url,media_type,category,created_at) VALUES(?,?,?,?,?,?,NOW())")
                 ->execute([$id, $title, $description, $imageUrl, $mediaType, $category]);
            } catch (PDOException $e) {
              $db->prepare("INSERT INTO gallery(id,title,description,image_url,category,created_at) VALUES(?,?,?,?,?,NOW())")
                 ->execute([$id, $title, $description, $imageUrl, $category]);
            }
            $msg = ucfirst($mediaType) . ' uploaded and added to gallery.';
          }
        } else {
          // Check if media_type column exists
          try {
            $db->prepare("INSERT INTO gallery(id,title,description,image_url,media_type,category,created_at) VALUES(?,?,?,?,?,?,NOW())")
               ->execute([$id, $title, $description, $imageUrl, $mediaType, $category]);
          } catch (PDOException $e) {
            $db->prepare("INSERT INTO gallery(id,title,description,image_url,category,created_at) VALUES(?,?,?,?,?,NOW())")
               ->execute([$id, $title, $description, $imageUrl, $category]);
          }
          $msg = ucfirst($mediaType) . ' uploaded and added to gallery.';
        }
      } else {
        $error = 'Failed to save file. Check server write permissions.';
      }
    }
    }
}

// Fetch gallery items - handle if media_type column doesn't exist
try {
    $items = $db->query("SELECT * FROM gallery ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $items = [];
}

// Keep legacy rows untouched; detectMediaType() handles missing media_type.

// Category color mapping
$categoryColors = [
    'Delivery'       => ['bg' => '#fff7ed', 'color' => '#f97316'],
    'Installation'   => ['bg' => '#eff6ff', 'color' => '#2563eb'],
    'Infrastructure' => ['bg' => '#f5f3ff', 'color' => '#7c3aed'],
    'Commercial'     => ['bg' => '#f0fdf4', 'color' => '#15803d'],
    'Products'       => ['bg' => '#fef9c3', 'color' => '#a16207'],
    'General'        => ['bg' => '#f1f5f9', 'color' => '#475569'],
];
?>
<?php require_once __DIR__ . '/layout_top.php'; ?>

<?php if ($msg): ?>
<div style="background:#f0fdf4;border:1px solid #bbf7d0;color:#15803d;padding:.8rem 1.1rem;border-radius:10px;font-size:.875rem;font-weight:500;margin-bottom:1.5rem;display:flex;align-items:center;gap:.5rem">
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
  <?= htmlspecialchars($msg) ?>
</div>
<?php endif; ?>
<?php if ($error): ?>
<div style="background:#fef2f2;border:1px solid #fecaca;color:#dc2626;padding:.8rem 1.1rem;border-radius:10px;font-size:.875rem;font-weight:500;margin-bottom:1.5rem;display:flex;align-items:center;gap:.5rem">
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>
  <?= htmlspecialchars($error) ?>
</div>
<?php endif; ?>

<div style="display:grid;grid-template-columns:1fr 380px;gap:1.75rem;align-items:start" class="gal-layout">

  <!-- ── Gallery grid ── -->
  <div>
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:1.25rem;flex-wrap:wrap;gap:1rem">
      <div>
        <h2 style="font-weight:700;font-size:1rem;color:#0f172a;margin:0"><?= count($items) ?> Media Files</h2>
        <p style="color:#64748b;font-size:.8rem;margin:.2rem 0 0">Images, videos, projects, deliveries, and installations</p>
      </div>
      <div style="display:flex;gap:.45rem;flex-wrap:wrap">
        <?php foreach ($categoryColors as $cat => $style): ?>
        <span style="background:<?= $style['bg'] ?>;color:<?= $style['color'] ?>;border-radius:20px;padding:.25rem .7rem;font-size:.7rem;font-weight:700"><?= $cat ?></span>
        <?php endforeach; ?>
      </div>
    </div>

    <?php if (empty($items)): ?>
    <div style="background:#fff;border:1px solid #e8ecf0;border-radius:14px;text-align:center;padding:4rem 1rem">
      <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#cbd5e1" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="margin:0 auto 1rem;display:block"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
      <p style="color:#94a3b8;font-size:.9rem">No media yet. Upload one using the form.</p>
    </div>
    <?php else: ?>
    <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:.875rem">
    <?php foreach ($items as $item): 
    $cat = $item['category'] ?: 'General';
    $catStyle = $categoryColors[$cat] ?? ['bg' => '#f1f5f9', 'color' => '#475569'];
    // Debug: detect server file existence and mime for uploaded media
    $server_file_status = null;
    if (!empty($item['image_url'])) {
      // Try to map URL to local path. Many installs use '/stile-lpg' prefix; handle general case.
      $urlPath = parse_url($item['image_url'], PHP_URL_PATH);
      // common prefix fallback: if path begins with '/stile-lpg', remove it for local mapping
      $rel = $urlPath;
      if (str_starts_with($rel, '/stile-lpg')) {
        $rel = substr($rel, strlen('/stile-lpg'));
      }
      $localPath = realpath(__DIR__ . '/..' . $rel);
      if ($localPath && file_exists($localPath)) {
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime = finfo_file($finfo, $localPath);
        finfo_close($finfo);
        $server_file_status = ['exists' => true, 'path' => $localPath, 'mime' => $mime];
      } else {
        $server_file_status = ['exists' => false, 'path' => __DIR__ . '/..' . $rel];
      }
    }
      ?>
      <div style="background:#fff;border:1px solid #e8ecf0;border-radius:16px;overflow:hidden;transition:all .2s" onmouseover="this.style.boxShadow='0 8px 30px rgba(0,0,0,.12)';this.style.transform='translateY(-4px)'" onmouseout="this.style.boxShadow='none';this.style.transform='translateY(0)'">
        <div style="height:200px;background:#f8fafc;overflow:hidden;position:relative">
          <?php if ($item['image_url']): 
            $mediaType = detectMediaType($item);
            if ($mediaType === 'video'): ?>
            <video src="<?= htmlspecialchars($item['image_url']) ?>" style="width:100%;height:100%;object-fit:cover;display:block" controls preload="metadata" playsinline autoplay muted loop>
              Your browser does not support video.
            </video>
            <div style="position:absolute;top:10px;left:10px;background:rgba(239,68,68,.9);color:#fff;border-radius:20px;padding:.3rem .7rem;font-size:.65rem;font-weight:700;display:flex;align-items:center;gap:.3rem">
              <svg width="10" height="10" viewBox="0 0 24 24" fill="#fff"><polygon points="5 3 19 12 5 21 5 3"/></svg>
              VIDEO
            </div>
            <?php if ($server_file_status): ?>
              <div style="position:absolute;top:10px;right:10px;background:rgba(17,24,39,.95);color:#fff;border-radius:8px;padding:.25rem .5rem;font-size:.65rem;font-weight:700;display:flex;align-items:center;gap:.4rem;z-index:80">
                <?php if ($server_file_status['exists']): ?>
                  <span style="color:#60a5fa">EXISTS</span>
                  <span style="opacity:.8;font-size:.65rem;margin-left:.4rem"><?= htmlspecialchars($server_file_status['mime'] ?? 'unknown') ?></span>
                <?php else: ?>
                  <span style="color:#f87171">MISSING</span>
                <?php endif; ?>
              </div>
            <?php endif; ?>
          <?php else: ?>
          <img src="<?= htmlspecialchars($item['image_url']) ?>" alt="<?= htmlspecialchars($item['title']) ?>" style="width:100%;height:100%;object-fit:cover;display:block" loading="lazy">
          <?php endif; ?>
          <div style="position:absolute;inset:0;background:linear-gradient(to top,rgba(15,23,42,.7) 0%,rgba(15,23,42,.1) 50%,transparent 100%);<?= $mediaType === 'video' ? 'pointer-events:none' : '' ?>"></div>
          <!-- Category badge -->
          <span style="position:absolute;top:10px;right:10px;background:<?= $catStyle['bg'] ?>;color:<?= $catStyle['color'] ?>;border-radius:20px;padding:.25rem .7rem;font-size:.7rem;font-weight:700;backdrop-filter:blur(8px)"><?= htmlspecialchars($cat) ?></span>
          <!-- Title overlay -->
          <div style="position:absolute;bottom:0;left:0;right:0;padding:.9rem 1rem;<?= $mediaType === 'video' ? 'pointer-events:none' : '' ?>">
            <h3 style="color:#fff;font-weight:700;font-size:.92rem;margin:0;text-shadow:0 2px 8px rgba(0,0,0,.4)"><?= htmlspecialchars($item['title']) ?></h3>
          </div>
          <?php else: ?>
          <div style="width:100%;height:100%;display:flex;align-items:center;justify-content:center">
            <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="#cbd5e1" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
          </div>
          <?php endif; ?>
        </div>
        <div style="padding:1rem;display:flex;flex-direction:column;gap:.75rem">
          <?php if ($item['description']): ?>
          <div style="display:flex;align-items:start;gap:.6rem">
            <div style="width:28px;height:28px;border-radius:8px;background:<?= $catStyle['bg'] ?>;display:flex;align-items:center;justify-content:center;flex-shrink:0">
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="<?= $catStyle['color'] ?>" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
            </div>
            <p style="color:#64748b;font-size:.8rem;line-height:1.5;margin:0;flex:1"><?= htmlspecialchars($item['description']) ?></p>
          </div>
          <?php endif; ?>
          <div style="display:flex;align-items:center;justify-content:space-between;gap:.5rem;padding-top:.5rem;border-top:1px solid #f1f5f9">
            <div style="color:#94a3b8;font-size:.72rem"><?= date('M j, Y', strtotime($item['created_at'])) ?></div>
            <a href="/stile-lpg/admin/gallery.php?delete=<?= urlencode($item['id']) ?>" onclick="return confirm('Delete this media permanently?')" style="width:28px;height:28px;border-radius:8px;background:#fef2f2;border:1px solid #fecaca;display:flex;align-items:center;justify-content:center;transition:background .15s" title="Delete">
              <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#dc2626" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/><path d="M9 6V4h6v2"/></svg>
            </a>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <?php endif; ?>
  </div>

  <!-- ── Upload form ── -->
  <div style="background:#fff;border:1px solid #e8ecf0;border-radius:14px;overflow:hidden;position:sticky;top:76px">
    <div style="padding:1.125rem 1.5rem;border-bottom:1px solid #f0f2f5">
      <h3 style="font-weight:700;font-size:.9rem;color:#0f172a;margin:0">Upload Media</h3>
      <p style="color:#64748b;font-size:.78rem;margin:.2rem 0 0">Images (JPG, PNG, WebP, GIF) or Videos (MP4, WebM, OGG) — max 50 MB</p>
    </div>
    <form method="POST" enctype="multipart/form-data" style="padding:1.25rem;display:flex;flex-direction:column;gap:1rem">

      <!-- Title -->
      <div>
        <label style="display:block;font-size:.75rem;font-weight:600;color:#374151;margin-bottom:.4rem">Media Title <span style="color:#ef4444">*</span></label>
        <input type="text" name="title" required placeholder="e.g. Delivery Team at Work"
          style="font-family:inherit;font-size:.875rem;width:100%;padding:.65rem .9rem;border:1.5px solid #e2e8f0;border-radius:8px;outline:none;color:#0f172a;transition:border-color .18s"
          onfocus="this.style.borderColor='#0f172a'" onblur="this.style.borderColor='#e2e8f0'">
      </div>

      <!-- Category -->
      <div>
        <label style="display:block;font-size:.75rem;font-weight:600;color:#374151;margin-bottom:.4rem">Category <span style="color:#ef4444">*</span></label>
        <select name="category" required
          style="font-family:inherit;font-size:.875rem;width:100%;padding:.65rem .9rem;border:1.5px solid #e2e8f0;border-radius:8px;outline:none;color:#0f172a;transition:border-color .18s;background:#fff"
          onfocus="this.style.borderColor='#0f172a'" onblur="this.style.borderColor='#e2e8f0'">
          <option value="Delivery">🚚 Delivery</option>
          <option value="Installation">🔧 Installation</option>
          <option value="Infrastructure">🏗️ Infrastructure</option>
          <option value="Commercial">🏢 Commercial</option>
          <option value="Products">📦 Products</option>
          <option value="General" selected>📸 General</option>
        </select>
      </div>

      <!-- Description -->
      <div>
        <label style="display:block;font-size:.75rem;font-weight:600;color:#374151;margin-bottom:.4rem">Description</label>
        <textarea name="description" rows="3" placeholder="Brief description of the image..."
          style="font-family:inherit;font-size:.875rem;width:100%;padding:.65rem .9rem;border:1.5px solid #e2e8f0;border-radius:8px;outline:none;color:#0f172a;transition:border-color .18s;resize:vertical"
          onfocus="this.style.borderColor='#0f172a'" onblur="this.style.borderColor='#e2e8f0'"></textarea>
      </div>

      <!-- File chooser -->
      <div>
        <label style="display:block;font-size:.75rem;font-weight:600;color:#374151;margin-bottom:.4rem">Image or Video File <span style="color:#ef4444">*</span></label>
        <label id="drop-zone" style="display:flex;flex-direction:column;align-items:center;justify-content:center;gap:.5rem;border:2px dashed #e2e8f0;border-radius:10px;padding:1.5rem 1rem;cursor:pointer;transition:border-color .18s,background .18s;background:#fafafa;text-align:center" onmouseover="this.style.borderColor='#0f172a';this.style.background='#f8fafc'" onmouseout="resetDropZone()">
          <svg id="dz-icon" width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#94a3b8" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
          <div>
            <span id="dz-text" style="display:block;font-size:.82rem;font-weight:600;color:#374151">Click to choose file</span>
            <span style="font-size:.72rem;color:#94a3b8">or drag & drop here</span>
          </div>
          <input type="file" name="image_file" id="image_file" accept=".jpg,.jpeg,.png,.webp,.gif,.mp4,.webm,.ogg" required style="display:none" onchange="previewFile(this)">
        </label>
      </div>

      <!-- Preview -->
      <div id="img-preview-wrap" style="display:none;border-radius:10px;overflow:hidden;height:150px;background:#f1f5f9;position:relative">
        <img id="img-preview" src="" alt="Preview" style="width:100%;height:100%;object-fit:cover;display:block">
        <button type="button" onclick="clearFile()" style="position:absolute;top:6px;right:6px;width:26px;height:26px;border-radius:50%;background:rgba(15,23,42,.6);border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;color:#fff">
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
        </button>
      </div>

      <button type="submit" name="add_image" value="1"
        style="display:flex;align-items:center;justify-content:center;gap:.5rem;background:#0f172a;color:#fff;border:none;padding:.75rem 1rem;border-radius:8px;font-weight:600;font-size:.875rem;cursor:pointer;font-family:inherit;transition:background .18s"
        onmouseover="this.style.background='#1e293b'" onmouseout="this.style.background='#0f172a'">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
        Upload Media
      </button>
    </form>
  </div>
</div>

<style>
@media(max-width:960px){.gal-layout{grid-template-columns:1fr!important}}
</style>

<script>
function previewFile(input){
  if(!input.files||!input.files[0]) return;
  var file = input.files[0];
  var dz = document.getElementById('drop-zone');
  document.getElementById('dz-text').textContent = file.name;
  dz.style.borderColor = '#0f172a';
  dz.style.background = '#f8fafc';
  var reader = new FileReader();
  reader.onload = function(e){
    var wrap = document.getElementById('img-preview-wrap');
    document.getElementById('img-preview').src = e.target.result;
    wrap.style.display = 'block';
  };
  reader.readAsDataURL(file);
}
function clearFile(){
  document.getElementById('image_file').value = '';
  document.getElementById('img-preview-wrap').style.display = 'none';
  document.getElementById('dz-text').textContent = 'Click to choose file';
  resetDropZone();
}
function resetDropZone(){
  var dz = document.getElementById('drop-zone');
  dz.style.borderColor = '#e2e8f0';
  dz.style.background = '#fafafa';
}
// Drag & drop
var dz = document.getElementById('drop-zone');
dz.addEventListener('dragover', function(e){ e.preventDefault(); this.style.borderColor='#0f172a'; this.style.background='#f8fafc'; });
dz.addEventListener('dragleave', resetDropZone);
dz.addEventListener('drop', function(e){
  e.preventDefault();
  var fi = document.getElementById('image_file');
  fi.files = e.dataTransfer.files;
  previewFile(fi);
});
</script>

<?php require_once __DIR__ . '/layout_bottom.php'; ?>
