<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/lib/tenant.php';
require_once dirname(__DIR__) . '/lib/media.php';
require_once dirname(__DIR__) . '/lib/admin_layout.php';

require_admin();
$tenantId = current_tenant_id();

$stmt = db()->prepare('SELECT * FROM media_assets WHERE tenant_id = ? ORDER BY id DESC');
$stmt->execute([$tenantId]);
$assets = $stmt->fetchAll();

admin_header('Media Manager', 'media');
?>
<div class="panel">
  <h2>Upload & crop</h2>
  <p class="muted">Aspect ratios are enforced by destination tag (1:1 staff, 16:9 hero, 4:5 styles). Images optimize to WebP on upload.</p>
  <div class="grid-2">
    <div>
      <label for="upload-tag">Destination tag</label>
      <select id="upload-tag">
        <option value="general">General</option>
        <option value="hero">Hero / Banner (16:9)</option>
        <option value="staff">Staff profile (1:1)</option>
        <option value="style">Style look (4:5)</option>
        <option value="service">Service thumbnail (1:1)</option>
        <option value="product">Product (1:1)</option>
        <option value="banners">Banners</option>
      </select>
      <span class="muted" style="display:block;margin:.35rem 0 .5rem;font-size:.85rem">Upload image</span>
      <label class="dropzone" id="media-dropzone" for="media-file">
        <strong>Drag &amp; drop images here</strong>
        <span class="muted">or click this box to browse · crop opens next for images</span>
        <input type="file" id="media-file" accept="image/*,video/*">
      </label>
      <button type="button" class="btn secondary" id="media-browse-btn" style="margin-top:.65rem">Browse files…</button>
    </div>
    <div>
      <h2 style="margin-top:0">Stock API hook</h2>
      <p class="muted">Searches Pexels/Unsplash when API keys are set in config. Results can be saved into this shop’s asset library.</p>
      <div class="field-row">
        <div>
          <label for="stock-q">Query</label>
          <input type="text" id="stock-q" placeholder="barber fade">
        </div>
        <div>
          <label for="stock-provider">Provider</label>
          <select id="stock-provider">
            <option value="pexels">Pexels</option>
            <option value="unsplash">Unsplash</option>
          </select>
        </div>
      </div>
      <button type="button" class="btn secondary" id="stock-search-btn">Search stock</button>
      <div id="stock-hint" class="muted" style="margin-top:.75rem"></div>
      <div class="stock-results" id="stock-results" style="margin-top:.75rem"></div>
    </div>
  </div>
</div>

<div class="panel">
  <h2>Asset library</h2>
  <div class="media-grid" id="asset-grid">
    <?php foreach ($assets as $a):
      $url = media_public_url($a['optimized_path'] ?: $a['file_path']);
      ?>
      <div class="media-card" data-id="<?= (int) $a['id'] ?>">
        <?php if (str_starts_with((string) ($a['mime_type'] ?? ''), 'video/')): ?>
          <video src="<?= htmlspecialchars($url) ?>" muted playsinline></video>
        <?php else: ?>
          <img src="<?= htmlspecialchars($url) ?>" alt="">
        <?php endif; ?>
        <div class="meta">
          <span class="tag"><?= htmlspecialchars((string) $a['file_tag']) ?></span>
          <div style="margin-top:.4rem;display:flex;gap:.35rem">
            <button class="btn small secondary tag-btn" type="button">Retag</button>
            <button class="btn small danger del-btn" type="button">Delete</button>
          </div>
        </div>
      </div>
    <?php endforeach; ?>
    <?php if (!$assets): ?>
      <p class="muted">No assets yet. Upload your first file above.</p>
    <?php endif; ?>
  </div>
</div>

<div class="crop-modal" id="crop-modal" aria-hidden="true">
  <div class="crop-box">
    <h2 style="margin-top:0">Frame image</h2>
    <div class="crop-stage" id="crop-stage"></div>
    <div class="crop-actions">
      <button type="button" class="btn secondary" id="crop-cancel">Cancel</button>
      <button type="button" class="btn" id="crop-apply">Upload cropped</button>
    </div>
  </div>
</div>
<?php
$mediaScript = <<<'JS'
<script>
(function(){
  const APP_BASE = window.APP_BASE || '';
  const tagSelect = document.getElementById('upload-tag');
  const ratios = { hero: 16/9, banners: 16/9, staff: 1, service: 1, style: 4/5, product: 1, general: NaN };
  const input = document.getElementById('media-file');
  const dropzone = document.getElementById('media-dropzone');
  const browseBtn = document.getElementById('media-browse-btn');
  const modal = document.getElementById('crop-modal');
  const stage = document.getElementById('crop-stage');
  let cropper = null, pending = null;

  function uploadUrl() { return APP_BASE + '/api/media_upload.php'; }
  function mediaApi() { return APP_BASE + '/api/media.php'; }

  function toast(msg, err) {
    if (window.BarberAdmin && BarberAdmin.toast) BarberAdmin.toast(msg, !!err);
    else alert(msg);
  }

  async function postForm(url, fd) {
    if (window.BarberAdmin && BarberAdmin.postForm) return BarberAdmin.postForm(url, fd);
    const res = await fetch(url, { method: 'POST', body: fd, credentials: 'same-origin' });
    const data = await res.json().catch(() => ({}));
    if (!res.ok || data.ok === false) throw new Error(data.error || 'Request failed');
    return data;
  }

  async function uploadRaw(file, crop) {
    const fd = new FormData();
    fd.append('file', file);
    fd.append('tag', tagSelect.value);
    if (crop) {
      fd.append('crop_x', crop.x);
      fd.append('crop_y', crop.y);
      fd.append('crop_w', crop.width);
      fd.append('crop_h', crop.height);
    }
    await postForm(uploadUrl(), fd);
    location.reload();
  }

  function closeCrop() {
    modal.classList.remove('open');
    modal.setAttribute('aria-hidden', 'true');
    input.value = '';
    if (cropper) { cropper.destroy(); cropper = null; }
    pending = null;
  }

  function handleFile(file) {
    if (!file) return;
    if (!file.type || !file.type.startsWith('image/')) {
      uploadRaw(file).catch(e => toast(e.message, true));
      return;
    }
    if (!window.Cropper) {
      toast('Cropper failed to load — uploading without crop.', true);
      uploadRaw(file).catch(e => toast(e.message, true));
      return;
    }
    pending = file;
    stage.innerHTML = '';
    const img = document.createElement('img');
    img.alt = 'Crop preview';
    img.src = URL.createObjectURL(file);
    stage.appendChild(img);
    modal.classList.add('open');
    modal.setAttribute('aria-hidden', 'false');
    if (cropper) cropper.destroy();
    const ratio = ratios[tagSelect.value];
    cropper = new Cropper(img, {
      aspectRatio: Number.isFinite(ratio) ? ratio : NaN,
      viewMode: 1,
      autoCropArea: 0.9
    });
  }

  browseBtn.addEventListener('click', (e) => {
    e.preventDefault();
    input.click();
  });

  ['dragenter', 'dragover'].forEach(evt => {
    dropzone.addEventListener(evt, (e) => {
      e.preventDefault();
      e.stopPropagation();
      dropzone.classList.add('dragover');
    });
  });
  ['dragleave', 'dragend'].forEach(evt => {
    dropzone.addEventListener(evt, (e) => {
      e.preventDefault();
      dropzone.classList.remove('dragover');
    });
  });
  dropzone.addEventListener('drop', (e) => {
    e.preventDefault();
    e.stopPropagation();
    dropzone.classList.remove('dragover');
    const file = e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files[0];
    handleFile(file);
  });
  ['dragover', 'drop'].forEach(evt => {
    window.addEventListener(evt, (e) => {
      if (e.target === dropzone || dropzone.contains(e.target)) return;
      e.preventDefault();
    });
  });

  input.addEventListener('change', () => handleFile(input.files && input.files[0]));

  document.getElementById('crop-cancel').addEventListener('click', closeCrop);
  document.getElementById('crop-apply').addEventListener('click', async () => {
    if (!cropper || !pending) return;
    try {
      const d = cropper.getData(true);
      await uploadRaw(pending, { x: d.x, y: d.y, width: d.width, height: d.height });
    } catch (e) {
      toast(e.message, true);
    }
  });

  document.getElementById('stock-search-btn').addEventListener('click', async () => {
    const q = document.getElementById('stock-q').value.trim();
    const provider = document.getElementById('stock-provider').value;
    const hint = document.getElementById('stock-hint');
    const box = document.getElementById('stock-results');
    box.innerHTML = '';
    hint.textContent = 'Searching…';
    try {
      const res = await fetch(mediaApi() + '?action=stock_search&q=' + encodeURIComponent(q) + '&provider=' + encodeURIComponent(provider));
      const data = await res.json();
      if (!data.configured) {
        hint.textContent = data.hint || 'API key not configured — placeholder hook is ready.';
        return;
      }
      const results = data.results || [];
      hint.textContent = results.length + ' result' + (results.length === 1 ? '' : 's');
      results.forEach(item => {
        const btn = document.createElement('button');
        btn.type = 'button';
        btn.innerHTML = '<img src="' + item.thumb + '" alt="">';
        btn.addEventListener('click', async () => {
          const fd = new FormData();
          fd.append('action', 'stock_save');
          fd.append('url', item.full);
          fd.append('tag', 'stock');
          try {
            await postForm(mediaApi(), fd);
            location.reload();
          } catch (e) { toast(e.message, true); }
        });
        box.appendChild(btn);
      });
    } catch (e) {
      hint.textContent = e.message || 'Stock search failed.';
    }
  });

  document.querySelectorAll('.del-btn').forEach(btn => {
    btn.addEventListener('click', async () => {
      if (!confirm('Delete this asset?')) return;
      const card = btn.closest('.media-card');
      const fd = new FormData();
      fd.append('action', 'delete');
      fd.append('id', card.dataset.id);
      try {
        await postForm(mediaApi(), fd);
        card.remove();
      } catch (e) { toast(e.message, true); }
    });
  });
  document.querySelectorAll('.tag-btn').forEach(btn => {
    btn.addEventListener('click', async () => {
      const tag = prompt('New tag (hero, staff, style, banners, general):', 'general');
      if (!tag) return;
      const card = btn.closest('.media-card');
      const fd = new FormData();
      fd.append('action', 'tag');
      fd.append('id', card.dataset.id);
      fd.append('tag', tag);
      try {
        await postForm(mediaApi(), fd);
        location.reload();
      } catch (e) { toast(e.message, true); }
    });
  });
})();
</script>
JS;

admin_footer($mediaScript);
