<?php
declare(strict_types=1);

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

require_admin();
$tenantId = current_tenant_id();
$flash = '';
$error = '';

$localFiles = media_list_local_files($tenantId);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'save';
    try {
        if ($action === 'delete') {
            $id = (int) ($_POST['id'] ?? 0);
            db()->prepare('DELETE FROM products WHERE id = ? AND tenant_id = ?')->execute([$id, $tenantId]);
            $flash = 'Product deleted.';
        } elseif ($action === 'reorder') {
            $order = json_decode((string) ($_POST['order'] ?? '[]'), true) ?: [];
            $stmt = db()->prepare('UPDATE products SET display_order = ? WHERE id = ? AND tenant_id = ?');
            foreach (array_values($order) as $i => $id) {
                $stmt->execute([$i + 1, (int) $id, $tenantId]);
            }
            json_response(['ok' => true]);
        } else {
            $id = (int) ($_POST['id'] ?? 0);
            $name = trim((string) ($_POST['name'] ?? ''));
            $short = trim((string) ($_POST['short_description'] ?? ''));
            $desc = trim((string) ($_POST['description'] ?? ''));
            $price = (float) ($_POST['price'] ?? 0);
            $stock = (int) ($_POST['stock'] ?? 0);
            $cat = trim((string) ($_POST['category'] ?? 'Grooming')) ?: 'Grooming';
            $img = media_normalize_stored_path(trim((string) ($_POST['image_path'] ?? '')));
            $active = isset($_POST['is_active']) ? 1 : 0;
            if ($name === '') {
                throw new RuntimeException('Product name is required.');
            }
            $slug = product_unique_slug($tenantId, $name, $id ?: null);
            if ($id > 0) {
                db()->prepare(
                    'UPDATE products SET name=?, slug=?, short_description=?, description=?, price=?, stock=?, image_path=?, category=?, is_active=?
                     WHERE id=? AND tenant_id=?'
                )->execute([$name, $slug, $short, $desc, $price, $stock, $img ?: null, $cat, $active, $id, $tenantId]);
                $flash = 'Product updated.';
            } else {
                $ord = (int) db()->query('SELECT COALESCE(MAX(display_order),0)+1 FROM products WHERE tenant_id=' . (int) $tenantId)->fetchColumn();
                db()->prepare(
                    'INSERT INTO products (tenant_id, name, slug, short_description, description, price, stock, image_path, category, is_active, display_order)
                     VALUES (?,?,?,?,?,?,?,?,?,?,?)'
                )->execute([$tenantId, $name, $slug, $short, $desc, $price, $stock, $img ?: null, $cat, $active, $ord]);
                $flash = 'Product added.';
            }
        }
    } catch (Throwable $e) {
        if (($action ?? '') === 'reorder') {
            json_response(['ok' => false, 'error' => $e->getMessage()], 400);
        }
        $error = $e->getMessage();
    }
}

$editId = (int) ($_GET['edit'] ?? 0);
$edit = null;
if ($editId) {
    $st = db()->prepare('SELECT * FROM products WHERE id = ? AND tenant_id = ?');
    $st->execute([$editId, $tenantId]);
    $edit = $st->fetch() ?: null;
}
$currentImg = media_normalize_stored_path((string) ($edit['image_path'] ?? ''));

$list = db()->prepare('SELECT * FROM products WHERE tenant_id = ? ORDER BY display_order, id');
$list->execute([$tenantId]);
$products = $list->fetchAll();

admin_header('Products', 'products');
if ($flash): ?><div class="flash"><?= htmlspecialchars($flash) ?></div><?php endif; ?>
<?php if ($error): ?><div class="flash error"><?= htmlspecialchars($error) ?></div><?php endif; ?>

<div class="panel">
  <h2><?= $edit ? 'Edit product' : 'Add product' ?></h2>
  <p class="muted">Upload below or pick a thumbnail from Media / local uploads, then Save product.</p>
  <form method="post" id="product-form">
    <input type="hidden" name="id" value="<?= (int) ($edit['id'] ?? 0) ?>">
    <div class="grid-2">
      <div>
        <label>Name</label>
        <input type="text" name="name" required value="<?= htmlspecialchars((string) ($edit['name'] ?? '')) ?>">
        <label>Short description</label>
        <input type="text" name="short_description" value="<?= htmlspecialchars((string) ($edit['short_description'] ?? '')) ?>">
        <label>Full description</label>
        <textarea name="description"><?= htmlspecialchars((string) ($edit['description'] ?? '')) ?></textarea>
        <div class="field-row">
          <div>
            <label>Price</label>
            <input type="number" step="0.01" min="0" name="price" required value="<?= htmlspecialchars((string) ($edit['price'] ?? '0')) ?>">
          </div>
          <div>
            <label>Stock</label>
            <input type="number" min="0" name="stock" value="<?= htmlspecialchars((string) ($edit['stock'] ?? '0')) ?>">
          </div>
        </div>
        <label>Category</label>
        <input type="text" name="category" value="<?= htmlspecialchars((string) ($edit['category'] ?? 'Grooming')) ?>">
        <label style="display:flex;gap:.5rem;align-items:center;color:var(--text)">
          <input type="checkbox" name="is_active" <?= !isset($edit['is_active']) || !empty($edit['is_active']) ? 'checked' : '' ?>>
          Active on storefront
        </label>
      </div>
      <div>
        <span class="muted" style="display:block;margin:0 0 .5rem;font-size:.85rem">Product image</span>
        <label class="dropzone" id="product-dropzone" for="product-file">
          <strong>Drag &amp; drop product image</strong>
          <span class="muted">or click this box · crops 1:1 then saves to Media</span>
          <input type="file" id="product-file" accept="image/*">
        </label>
        <button type="button" class="btn secondary" id="product-browse-btn" style="margin-top:.65rem">Browse files…</button>
        <input type="hidden" name="image_path" id="product_image_path" value="<?= htmlspecialchars((string) ($edit['image_path'] ?? '')) ?>">
        <p class="muted" style="margin:1rem 0 .4rem;font-size:.85rem">Or select from library</p>
        <div class="picker-grid" id="product-picker">
          <?php if (!$localFiles): ?>
            <p class="muted" style="grid-column:1/-1">No uploads yet. Use the drop zone above or add files in <a href="<?= htmlspecialchars(APP_BASE) ?>/admin/media.php">Media</a>.</p>
          <?php endif; ?>
          <?php foreach ($localFiles as $f):
            $sel = ($currentImg === $f['path']) ? 'selected' : '';
            ?>
            <button type="button" class="picker-item <?= $sel ?>" data-path="<?= htmlspecialchars($f['path']) ?>" title="<?= htmlspecialchars($f['path']) ?>">
              <img src="<?= htmlspecialchars($f['url']) ?>" alt="">
              <span class="check">✓</span>
            </button>
          <?php endforeach; ?>
        </div>
        <p class="muted" id="product-path-label" style="font-size:.85rem">
          <?= $currentImg !== '' ? 'Selected: <code>uploads/' . htmlspecialchars($currentImg) . '</code>' : 'No image selected.' ?>
        </p>
      </div>
    </div>
    <button class="btn" type="submit">Save product</button>
    <?php if ($edit): ?><a class="btn secondary" href="<?= htmlspecialchars(APP_BASE) ?>/admin/products.php">Cancel</a><?php endif; ?>
  </form>
</div>

<div class="crop-modal" id="crop-modal" aria-hidden="true">
  <div class="crop-box">
    <h2 style="margin-top:0">Frame product image (1:1)</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>

<div class="panel">
  <h2>Catalog (drag ⋮⋮ to reorder)</h2>
  <div id="product-list">
    <?php foreach ($products as $p): ?>
      <div class="service-row" data-id="<?= (int) $p['id'] ?>" style="display:grid;grid-template-columns:28px 56px 1fr auto auto auto;gap:.75rem;align-items:center;padding:.55rem 0;border-bottom:1px solid var(--line)">
        <span class="drag-handle" title="Drag to reorder">⋮⋮</span>
        <?php if (!empty($p['image_path'])): ?>
          <img class="thumb" src="<?= htmlspecialchars(media_public_url($p['image_path'])) ?>" alt="">
        <?php else: ?>
          <div class="thumb" style="background:#2a3142"></div>
        <?php endif; ?>
        <div>
          <strong><?= htmlspecialchars($p['name']) ?></strong>
          <div class="muted" style="font-size:.85rem">$<?= number_format((float) $p['price'], 2) ?> · stock <?= (int) $p['stock'] ?> · <?= htmlspecialchars((string) $p['category']) ?></div>
        </div>
        <span class="tag"><?= !empty($p['is_active']) ? 'active' : 'hidden' ?></span>
        <a class="btn small secondary" href="?edit=<?= (int) $p['id'] ?>">Edit</a>
        <form method="post" onsubmit="return confirm('Delete product?')">
          <input type="hidden" name="action" value="delete">
          <input type="hidden" name="id" value="<?= (int) $p['id'] ?>">
          <button class="btn small danger" type="submit">Delete</button>
        </form>
      </div>
    <?php endforeach; ?>
  </div>
  <p class="muted" style="margin-top:1rem"><a href="<?= htmlspecialchars(APP_BASE) ?>/shop.php<?= htmlspecialchars(tenant_qs()) ?>" target="_blank">View public catalog →</a></p>
</div>
<?php
$productsScript = <<<'JS'
<script>
(function(){
  const APP_BASE = window.APP_BASE || '';
  const hidden = document.getElementById('product_image_path');
  const label = document.getElementById('product-path-label');
  const input = document.getElementById('product-file');
  const dropzone = document.getElementById('product-dropzone');
  const browseBtn = document.getElementById('product-browse-btn');
  const modal = document.getElementById('crop-modal');
  const stage = document.getElementById('crop-stage');
  const grid = document.getElementById('product-picker');
  let cropper = null, pending = null;

  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;
  }

  function selectPath(path, url) {
    path = String(path || '').replace(/^\/?uploads\//, '');
    hidden.value = path;
    label.innerHTML = path ? ('Selected: <code>uploads/' + path + '</code>') : 'No image selected.';
    grid.querySelectorAll('.picker-item').forEach(b => {
      b.classList.toggle('selected', (b.dataset.path || '') === path);
    });
    if (path && url && ![...grid.querySelectorAll('.picker-item')].some(b => (b.dataset.path || '') === path)) {
      const btn = document.createElement('button');
      btn.type = 'button';
      btn.className = 'picker-item selected';
      btn.dataset.path = path;
      btn.innerHTML = '<img src="' + url + '" alt=""><span class="check">✓</span>';
      grid.prepend(btn);
      bindPicker(btn);
    }
  }

  function bindPicker(btn) {
    btn.addEventListener('click', (e) => {
      e.preventDefault();
      e.stopPropagation();
      selectPath(btn.dataset.path || '');
    });
  }
  grid.querySelectorAll('.picker-item').forEach(bindPicker);

  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 || !file.type || !file.type.startsWith('image/')) return;
    if (!window.Cropper) {
      toast('Cropper failed to load — try Media page upload first.', 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();
    cropper = new Cropper(img, { aspectRatio: 1, 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');
    handleFile(e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files[0]);
  });
  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;
    const d = cropper.getData(true);
    const fd = new FormData();
    fd.append('file', pending);
    fd.append('tag', 'product');
    fd.append('crop_x', d.x); fd.append('crop_y', d.y); fd.append('crop_w', d.width); fd.append('crop_h', d.height);
    try {
      const data = await postForm(APP_BASE + '/api/media_upload.php', fd);
      const path = data.asset.optimized_path || data.asset.file_path;
      selectPath(path, data.asset.url);
      closeCrop();
      toast('Image uploaded — save product to keep it');
    } catch (e) { toast(e.message, true); }
  });

  const list = document.getElementById('product-list');
  let dragEl = null;
  list.querySelectorAll('.service-row').forEach(row => {
    const handle = row.querySelector('.drag-handle');
    if (!handle) return;
    handle.setAttribute('draggable', 'true');
    handle.addEventListener('dragstart', e => { dragEl = row; row.classList.add('dragging'); e.dataTransfer.effectAllowed = 'move'; });
    handle.addEventListener('dragend', async () => {
      row.classList.remove('dragging');
      const ids = [...list.querySelectorAll('.service-row')].map(r => r.dataset.id);
      const fd = new FormData();
      fd.append('action', 'reorder');
      fd.append('order', JSON.stringify(ids));
      try {
        await postForm(APP_BASE + '/admin/products.php', fd);
        toast('Order saved');
      } catch (err) { toast(err.message, true); }
    });
    row.addEventListener('dragover', e => {
      e.preventDefault();
      if (!dragEl || dragEl === row) return;
      const rect = row.getBoundingClientRect();
      const after = (e.clientY - rect.top) > rect.height / 2;
      list.insertBefore(dragEl, after ? row.nextSibling : row);
    });
  });
})();
</script>
JS;

admin_footer($productsScript);
