<?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();
$flash = '';
$error = '';

$services = db()->prepare('SELECT id, name FROM services WHERE tenant_id = ? ORDER BY display_order, name');
$services->execute([$tenantId]);
$serviceRows = $services->fetchAll();
$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 style_gallery WHERE id = ? AND tenant_id = ?')->execute([$id, $tenantId]);
            $flash = 'Style removed.';
        } else {
            $id = (int) ($_POST['id'] ?? 0);
            $name = trim((string) ($_POST['style_name'] ?? ''));
            $cat = trim((string) ($_POST['category_tag'] ?? ''));
            $img = media_normalize_stored_path(trim((string) ($_POST['image_url'] ?? '')));
            $link = ($_POST['linked_service_id'] ?? '') !== '' ? (int) $_POST['linked_service_id'] : null;
            if ($name === '' || $img === '') {
                throw new RuntimeException('Style name and image are required.');
            }
            if ($id > 0) {
                db()->prepare('UPDATE style_gallery SET style_name=?, category_tag=?, image_url=?, linked_service_id=?, is_active_stock=0 WHERE id=? AND tenant_id=?')
                    ->execute([$name, $cat, $img, $link, $id, $tenantId]);
                $flash = 'Style updated.';
            } else {
                db()->prepare('INSERT INTO style_gallery (tenant_id, style_name, category_tag, image_url, linked_service_id, is_active_stock) VALUES (?,?,?,?,?,0)')
                    ->execute([$tenantId, $name, $cat, $img, $link]);
                $flash = 'Style added.';
            }
        }
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

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

$currentImg = media_normalize_stored_path((string) ($edit['image_url'] ?? ''));
$currentIsRemote = (bool) preg_match('#^https?://#i', (string) ($edit['image_url'] ?? ''));

$list = db()->prepare('SELECT g.*, s.name AS service_name FROM style_gallery g LEFT JOIN services s ON s.id = g.linked_service_id WHERE g.tenant_id = ? ORDER BY g.display_order, g.id');
$list->execute([$tenantId]);
$styles = $list->fetchAll();

admin_header('Styles Showcase', 'styles');
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 style' : 'Add style' ?></h2>
  <form method="post" id="style-form">
    <input type="hidden" name="id" value="<?= (int) ($edit['id'] ?? 0) ?>">
    <div class="grid-2">
      <div>
        <label>Style name</label>
        <input type="text" name="style_name" required value="<?= htmlspecialchars((string) ($edit['style_name'] ?? '')) ?>">
        <label>Category tag</label>
        <select name="category_tag">
          <?php foreach (['Haircut', 'Beard', 'Kid', 'Color', 'Other'] as $c): ?>
            <option <?= (($edit['category_tag'] ?? '') === $c) ? 'selected' : '' ?>><?= $c ?></option>
          <?php endforeach; ?>
        </select>
        <label>Map to service menu (Book This Look)</label>
        <select name="linked_service_id">
          <option value="">— None —</option>
          <?php foreach ($serviceRows as $sv): ?>
            <option value="<?= (int) $sv['id'] ?>" <?= ((int) ($edit['linked_service_id'] ?? 0) === (int) $sv['id']) ? 'selected' : '' ?>>
              <?= htmlspecialchars($sv['name']) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div>
        <label>Primary image (local uploads)</label>
        <p class="muted" style="margin:.25rem 0 .75rem">
          Select a file from <code>uploads/</code> (or Media library). Upload new files in
          <a href="<?= APP_BASE ?>/admin/media.php">Media</a> first.
        </p>
        <input type="hidden" name="image_url" id="style_image_url" required value="<?= htmlspecialchars((string) ($edit['image_url'] ?? '')) ?>">

        <?php if ($localFiles): ?>
          <div class="picker-grid" id="style-picker">
            <?php foreach ($localFiles as $f):
              $sel = (!$currentIsRemote && $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="<?= htmlspecialchars($f['label']) ?>">
                <span class="check">✓</span>
              </button>
            <?php endforeach; ?>
          </div>
          <p class="muted" id="style-path-label" style="font-size:.85rem;margin:.25rem 0 .75rem">
            <?php if ($currentImg !== '' && !$currentIsRemote): ?>
              Selected: <code>uploads/<?= htmlspecialchars($currentImg) ?></code>
            <?php else: ?>
              No local file selected yet.
            <?php endif; ?>
          </p>
        <?php else: ?>
          <div class="flash" style="margin-bottom:.75rem">No local files yet. Upload in Media, then return here.</div>
        <?php endif; ?>

        <label>Or external / manual path</label>
        <input type="text" id="style_image_manual" placeholder="uploads/tenant_1/photo.webp  or  https://…" value="<?php
          echo $currentIsRemote ? htmlspecialchars((string) $edit['image_url']) : ($currentImg !== '' ? htmlspecialchars('uploads/' . $currentImg) : '');
        ?>">
      </div>
    </div>
    <button class="btn" type="submit">Save style</button>
    <?php if ($edit): ?><a class="btn secondary" href="<?= APP_BASE ?>/admin/styles.php">Cancel edit</a><?php endif; ?>
  </form>
</div>

<div class="panel">
  <h2>Gallery catalog</h2>
  <table class="table">
    <thead>
      <tr><th></th><th>Name</th><th>Category</th><th>Image path</th><th>Linked service</th><th>Stock</th><th></th></tr>
    </thead>
    <tbody>
      <?php foreach ($styles as $g):
        $img = media_public_url($g['image_url']);
        $stored = (string) $g['image_url'];
        $pathLabel = preg_match('#^https?://#i', $stored)
          ? 'remote'
          : 'uploads/' . media_normalize_stored_path($stored);
        ?>
        <tr>
          <td><img class="thumb" src="<?= htmlspecialchars($img) ?>" alt=""></td>
          <td><?= htmlspecialchars($g['style_name']) ?></td>
          <td><span class="tag"><?= htmlspecialchars((string) $g['category_tag']) ?></span></td>
          <td><code style="font-size:.75rem"><?= htmlspecialchars($pathLabel) ?></code></td>
          <td><?= htmlspecialchars((string) ($g['service_name'] ?? '—')) ?></td>
          <td><?= !empty($g['is_active_stock']) ? 'Yes' : 'No' ?></td>
          <td style="white-space:nowrap">
            <a class="btn small secondary" href="?edit=<?= (int) $g['id'] ?>">Edit</a>
            <form method="post" style="display:inline" onsubmit="return confirm('Delete style?')">
              <input type="hidden" name="action" value="delete">
              <input type="hidden" name="id" value="<?= (int) $g['id'] ?>">
              <button class="btn small danger" type="submit">Delete</button>
            </form>
          </td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>
<script>
(function(){
  const hidden = document.getElementById('style_image_url');
  const manual = document.getElementById('style_image_manual');
  const label = document.getElementById('style-path-label');

  function normalize(path) {
    path = (path || '').trim().replace(/\\/g, '/').replace(/^\.\//, '');
    path = path.replace(/^\/?uploads\//, '');
    return path;
  }

  document.querySelectorAll('#style-picker .picker-item').forEach(btn => {
    btn.addEventListener('click', () => {
      document.querySelectorAll('#style-picker .picker-item').forEach(b => b.classList.remove('selected'));
      btn.classList.add('selected');
      const path = btn.dataset.path || '';
      hidden.value = path;
      if (manual) manual.value = path ? ('uploads/' + path) : '';
      if (label) label.innerHTML = path ? ('Selected: <code>uploads/' + path + '</code>') : 'No local file selected yet.';
    });
  });

  if (manual) {
    manual.addEventListener('input', () => {
      const v = manual.value.trim();
      hidden.value = /^https?:\/\//i.test(v) ? v : normalize(v);
      document.querySelectorAll('#style-picker .picker-item').forEach(b => {
        b.classList.toggle('selected', b.dataset.path === normalize(v));
      });
      if (label) {
        label.innerHTML = /^https?:\/\//i.test(v)
          ? ('Selected: <code>remote URL</code>')
          : (hidden.value ? ('Selected: <code>uploads/' + hidden.value + '</code>') : 'No local file selected yet.');
      }
    });
  }

  document.getElementById('style-form').addEventListener('submit', (e) => {
    if (!hidden.value.trim()) {
      e.preventDefault();
      BarberAdmin.toast('Select a local upload or enter an image path/URL', true);
    }
  });
})();
</script>
<?php admin_footer(); ?>
