<?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 = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'save';
    try {
        if ($action === 'delete') {
            $id = (int) ($_POST['id'] ?? 0);
            db()->prepare('DELETE FROM services WHERE id = ? AND tenant_id = ?')->execute([$id, $tenantId]);
            $flash = 'Service deleted.';
        } else {
            $id = (int) ($_POST['id'] ?? 0);
            $name = trim((string) ($_POST['name'] ?? ''));
            $desc = trim((string) ($_POST['description'] ?? ''));
            $duration = (int) ($_POST['duration_minutes'] ?? 0);
            $price = (float) ($_POST['price'] ?? 0);
            $depositMode = (string) ($_POST['deposit_mode'] ?? 'none');
            if (!in_array($depositMode, ['none', 'fixed', 'percent', 'full'], true)) {
                $depositMode = 'none';
            }
            $depositValue = (float) ($_POST['deposit_value'] ?? 0);
            $image = trim((string) ($_POST['image_url'] ?? '')) ?: null;
            if ($name === '' || $duration <= 0) {
                throw new RuntimeException('Name and duration are required.');
            }
            if ($id > 0) {
                db()->prepare('UPDATE services SET name=?, description=?, duration_minutes=?, price=?, deposit_mode=?, deposit_value=?, image_url=? WHERE id=? AND tenant_id=?')
                    ->execute([$name, $desc, $duration, $price, $depositMode, $depositValue, $image, $id, $tenantId]);
                $flash = 'Service updated.';
            } else {
                $ord = (int) db()->query('SELECT COALESCE(MAX(display_order),0)+1 FROM services WHERE tenant_id=' . (int) $tenantId)->fetchColumn();
                db()->prepare('INSERT INTO services (tenant_id, name, description, duration_minutes, price, deposit_mode, deposit_value, image_url, display_order) VALUES (?,?,?,?,?,?,?,?,?)')
                    ->execute([$tenantId, $name, $desc, $duration, $price, $depositMode, $depositValue, $image, $ord]);
                $flash = 'Service added.';
            }
        }
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

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

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

admin_header('Service Menu', 'services');
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 service' : 'Add service' ?></h2>
  <form method="post">
    <input type="hidden" name="id" value="<?= (int) ($edit['id'] ?? 0) ?>">
    <div class="grid-2">
      <div>
        <label>Service name</label>
        <input type="text" name="name" required value="<?= htmlspecialchars((string) ($edit['name'] ?? '')) ?>">
        <label>Description</label>
        <textarea name="description"><?= htmlspecialchars((string) ($edit['description'] ?? '')) ?></textarea>
      </div>
      <div>
        <label>Duration (minutes)</label>
        <input type="number" name="duration_minutes" min="5" step="5" required value="<?= htmlspecialchars((string) ($edit['duration_minutes'] ?? '30')) ?>">
        <label>Price</label>
        <input type="number" name="price" min="0" step="0.01" required value="<?= htmlspecialchars((string) ($edit['price'] ?? '0')) ?>">
        <label>Deposit rule (when booking payments = deposit/optional)</label>
        <select name="deposit_mode">
          <?php foreach (['none' => 'None (use full price if deposit mode)', 'fixed' => 'Fixed $ amount', 'percent' => 'Percent of price', 'full' => 'Full price'] as $k => $label): ?>
            <option value="<?= $k ?>" <?= (($edit['deposit_mode'] ?? 'none') === $k) ? 'selected' : '' ?>><?= htmlspecialchars($label) ?></option>
          <?php endforeach; ?>
        </select>
        <label>Deposit value ($ or %)</label>
        <input type="number" name="deposit_value" min="0" step="0.01" value="<?= htmlspecialchars((string) ($edit['deposit_value'] ?? '0')) ?>">
        <label>Optional thumbnail URL/path</label>
        <input type="text" name="image_url" value="<?= htmlspecialchars((string) ($edit['image_url'] ?? '')) ?>">
      </div>
    </div>
    <button class="btn" type="submit">Save service</button>
    <?php if ($edit): ?><a class="btn secondary" href="<?= APP_BASE ?>/admin/services.php">Cancel</a><?php endif; ?>
  </form>
</div>

<div class="panel">
  <h2>Menu (drag handle to reorder)</h2>
  <div id="service-list">
    <?php foreach ($services as $sv): ?>
      <div class="service-row" data-id="<?= (int) $sv['id'] ?>" style="display:grid;grid-template-columns:28px 56px 1fr 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($sv['image_url'])): ?>
          <img class="thumb" src="<?= htmlspecialchars(media_public_url($sv['image_url'])) ?>" alt="">
        <?php else: ?>
          <div class="thumb" style="background:#2a3142"></div>
        <?php endif; ?>
        <div>
          <strong><?= htmlspecialchars($sv['name']) ?></strong>
          <div class="muted" style="font-size:.85rem"><?= (int) $sv['duration_minutes'] ?> min · $<?= number_format((float) $sv['price'], 2) ?>
            <?php
            $dm = (string) ($sv['deposit_mode'] ?? 'none');
            if ($dm !== 'none'):
              $dv = (float) ($sv['deposit_value'] ?? 0);
              $hint = $dm === 'percent' ? $dv . '%' : ($dm === 'full' ? 'full' : '$' . number_format($dv, 2));
            ?>
              · deposit <?= htmlspecialchars($hint) ?>
            <?php endif; ?>
          </div>
        </div>
        <a class="btn small secondary" href="?edit=<?= (int) $sv['id'] ?>">Edit</a>
        <form method="post" onsubmit="return confirm('Delete service?')">
          <input type="hidden" name="action" value="delete">
          <input type="hidden" name="id" value="<?= (int) $sv['id'] ?>">
          <button class="btn small danger" type="submit">Delete</button>
        </form>
      </div>
    <?php endforeach; ?>
  </div>
</div>
<?php admin_footer(); ?>
