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

$allServices = db()->prepare('SELECT id, name FROM services WHERE tenant_id = ? ORDER BY display_order, name');
$allServices->execute([$tenantId]);
$serviceRows = $allServices->fetchAll();
$localFiles = media_list_local_files($tenantId);

$days = ['mon' => 'Monday', 'tue' => 'Tuesday', 'wed' => 'Wednesday', 'thu' => 'Thursday', 'fri' => 'Friday', 'sat' => 'Saturday', 'sun' => 'Sunday'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'save';
    try {
        if ($action === 'delete') {
            $id = (int) ($_POST['id'] ?? 0);
            db()->prepare('DELETE FROM staff_barbers WHERE id = ? AND tenant_id = ?')->execute([$id, $tenantId]);
            $flash = 'Staff member removed.';
        } else {
            $id = (int) ($_POST['id'] ?? 0);
            $name = trim((string) ($_POST['name'] ?? ''));
            $title = trim((string) ($_POST['title'] ?? ''));
            $bio = trim((string) ($_POST['bio'] ?? ''));
            $specialties = trim((string) ($_POST['specialties'] ?? ''));
            $photo = media_normalize_stored_path(trim((string) ($_POST['profile_image_url'] ?? ''))) ?: null;
            if ($name === '') {
                throw new RuntimeException('Name is required.');
            }
            $hours = [];
            foreach ($days as $key => $label) {
                if (!empty($_POST['day_off'][$key])) {
                    $hours[$key] = null;
                } else {
                    $hours[$key] = [
                        'open' => $_POST['open'][$key] ?? '09:00',
                        'close' => $_POST['close'][$key] ?? '17:00',
                    ];
                }
            }
            $assigned = array_map('intval', $_POST['services'] ?? []);

            if ($id > 0) {
                db()->prepare('UPDATE staff_barbers SET name=?, title=?, bio=?, specialties=?, profile_image_url=?, working_hours=? WHERE id=? AND tenant_id=?')
                    ->execute([$name, $title, $bio, $specialties, $photo, json_encode($hours), $id, $tenantId]);
                $staffId = $id;
                $flash = 'Staff updated.';
            } else {
                db()->prepare('INSERT INTO staff_barbers (tenant_id, name, title, bio, specialties, profile_image_url, working_hours) VALUES (?,?,?,?,?,?,?)')
                    ->execute([$tenantId, $name, $title, $bio, $specialties, $photo, json_encode($hours)]);
                $staffId = (int) db()->lastInsertId();
                $flash = 'Staff added.';
            }

            db()->prepare('DELETE FROM staff_services WHERE staff_id = ?')->execute([$staffId]);
            $ins = db()->prepare('INSERT INTO staff_services (staff_id, service_id) VALUES (?, ?)');
            foreach ($assigned as $sid) {
                $chk = db()->prepare('SELECT id FROM services WHERE id = ? AND tenant_id = ?');
                $chk->execute([$sid, $tenantId]);
                if ($chk->fetch()) {
                    $ins->execute([$staffId, $sid]);
                }
            }
        }
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

$editId = (int) ($_GET['edit'] ?? 0);
$edit = null;
$assignedIds = [];
if ($editId) {
    $st = db()->prepare('SELECT * FROM staff_barbers WHERE id = ? AND tenant_id = ?');
    $st->execute([$editId, $tenantId]);
    $edit = $st->fetch() ?: null;
    if ($edit) {
        $as = db()->prepare('SELECT service_id FROM staff_services WHERE staff_id = ?');
        $as->execute([$editId]);
        $assignedIds = array_map('intval', array_column($as->fetchAll(), 'service_id'));
    }
}
$hoursEdit = json_decode((string) ($edit['working_hours'] ?? '{}'), true) ?: [];
$currentImg = media_normalize_stored_path((string) ($edit['profile_image_url'] ?? ''));

$list = db()->prepare('SELECT * FROM staff_barbers WHERE tenant_id = ? ORDER BY name');
$list->execute([$tenantId]);
$staff = $list->fetchAll();

admin_header('Staff / Barbers', 'staff');
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 barber' : 'Add barber' ?></h2>
  <form method="post" id="staff-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>Title / role</label>
        <input type="text" name="title" value="<?= htmlspecialchars((string) ($edit['title'] ?? '')) ?>">
        <label>Specialties</label>
        <input type="text" name="specialties" value="<?= htmlspecialchars((string) ($edit['specialties'] ?? '')) ?>" placeholder="Fades, Beard work">
        <label>Bio</label>
        <textarea name="bio"><?= htmlspecialchars((string) ($edit['bio'] ?? '')) ?></textarea>

        <span class="muted" style="display:block;margin:1rem 0 .5rem;font-size:.85rem">Profile photo</span>
        <label class="dropzone" id="staff-dropzone" for="staff-file">
          <strong>Drag &amp; drop profile photo</strong>
          <span class="muted">or click · crops 1:1 then saves to Media</span>
          <input type="file" id="staff-file" accept="image/*">
        </label>
        <button type="button" class="btn secondary" id="staff-browse-btn" style="margin-top:.65rem">Browse files…</button>
        <input type="hidden" name="profile_image_url" id="staff_image_path" value="<?= htmlspecialchars((string) ($edit['profile_image_url'] ?? '')) ?>">
        <p class="muted" style="margin:1rem 0 .4rem;font-size:.85rem">Or select from library</p>
        <div class="picker-grid" id="staff-picker">
          <?php if (!$localFiles): ?>
            <p class="muted" style="grid-column:1/-1">No uploads yet. Use the drop zone or <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="staff-path-label" style="font-size:.85rem">
          <?= $currentImg !== '' ? 'Selected: <code>uploads/' . htmlspecialchars($currentImg) . '</code>' : 'No photo selected.' ?>
        </p>
      </div>
      <div>
        <label>Assigned services</label>
        <div class="checkbox-grid">
          <?php foreach ($serviceRows as $sv): ?>
            <label>
              <input type="checkbox" name="services[]" value="<?= (int) $sv['id'] ?>" <?= in_array((int) $sv['id'], $assignedIds, true) ? 'checked' : '' ?>>
              <?= htmlspecialchars($sv['name']) ?>
            </label>
          <?php endforeach; ?>
        </div>
        <label>Working hours matrix</label>
        <?php foreach ($days as $key => $label):
          $off = array_key_exists($key, $hoursEdit) ? ($hoursEdit[$key] === null) : ($key === 'sun');
          $open = is_array($hoursEdit[$key] ?? null) ? ($hoursEdit[$key]['open'] ?? '09:00') : '09:00';
          $close = is_array($hoursEdit[$key] ?? null) ? ($hoursEdit[$key]['close'] ?? '17:00') : '17:00';
          ?>
          <div class="field-row" style="align-items:center;margin-bottom:.4rem">
            <div style="flex:1.2"><strong><?= $label ?></strong></div>
            <div><input type="text" name="open[<?= $key ?>]" value="<?= htmlspecialchars($open) ?>" placeholder="09:00"></div>
            <div><input type="text" name="close[<?= $key ?>]" value="<?= htmlspecialchars($close) ?>" placeholder="17:00"></div>
            <label style="flex:.8;display:flex;gap:.35rem;align-items:center;margin:0;color:var(--text)">
              <input type="checkbox" name="day_off[<?= $key ?>]" value="1" <?= $off ? 'checked' : '' ?>> Off
            </label>
          </div>
        <?php endforeach; ?>
      </div>
    </div>
    <button class="btn" type="submit">Save staff</button>
    <?php if ($edit): ?><a class="btn secondary" href="<?= htmlspecialchars(APP_BASE) ?>/admin/staff.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 profile photo (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>Team</h2>
  <table class="table">
    <thead><tr><th></th><th>Name</th><th>Title</th><th>Specialties</th><th></th></tr></thead>
    <tbody>
      <?php foreach ($staff as $b): ?>
        <tr>
          <td>
            <?php if (!empty($b['profile_image_url'])): ?>
              <img class="thumb" src="<?= htmlspecialchars(media_public_url($b['profile_image_url'])) ?>" alt="">
            <?php else: ?>
              <div class="thumb" style="background:#2a3142"></div>
            <?php endif; ?>
          </td>
          <td><?= htmlspecialchars($b['name']) ?></td>
          <td><?= htmlspecialchars((string) $b['title']) ?></td>
          <td><?= htmlspecialchars((string) ($b['specialties'] ?? '')) ?></td>
          <td style="white-space:nowrap">
            <a class="btn small secondary" href="?edit=<?= (int) $b['id'] ?>">Edit</a>
            <form method="post" style="display:inline" onsubmit="return confirm('Remove staff?')">
              <input type="hidden" name="action" value="delete">
              <input type="hidden" name="id" value="<?= (int) $b['id'] ?>">
              <button class="btn small danger" type="submit">Delete</button>
            </form>
          </td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>
<?php
$staffScript = <<<'JS'
<script>
(function(){
  const APP_BASE = window.APP_BASE || '';
  const hidden = document.getElementById('staff_image_path');
  const label = document.getElementById('staff-path-label');
  const input = document.getElementById('staff-file');
  const dropzone = document.getElementById('staff-dropzone');
  const browseBtn = document.getElementById('staff-browse-btn');
  const modal = document.getElementById('crop-modal');
  const stage = document.getElementById('crop-stage');
  const grid = document.getElementById('staff-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 photo 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', 'staff');
    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('Photo uploaded — save staff to keep it');
    } catch (e) { toast(e.message, true); }
  });
})();
</script>
JS;

admin_footer($staffScript);
