<?php
declare(strict_types=1);
require_once __DIR__ . '/bootstrap.php';
admin_require_login();

$data = cms_leads();
$data['items'] = is_array($data['items'] ?? null) ? $data['items'] : [];
$notice = '';
$statusMap = [
    'new' => 'Новая',
    'in_progress' => 'В работе',
    'confirmed' => 'Подтверждена',
    'done' => 'Завершена',
    'cancelled' => 'Отменена',
    'hidden' => 'Скрыта',
];

if (request_method() === 'POST') {
    if (!verify_csrf($_POST['csrf_token'] ?? null)) {
        $notice = '<div class="notice notice--error">Ошибка безопасности.</div>';
    } else {
        $items = [];
        foreach (post_array('items') as $item) {
            if (!is_array($item) || empty($item['id'])) continue;
            foreach ($item as $k => $v) {
                if (is_string($v)) $item[$k] = trim($v);
            }
            if (!empty($item['_delete'])) continue;
            $item['is_hidden'] = !empty($item['is_hidden']);
            if ($item['is_hidden'] && ($item['status'] ?? '') === 'hidden') {
                $item['status'] = 'hidden';
            } elseif (($item['status'] ?? '') === 'hidden' && empty($item['is_hidden'])) {
                $item['status'] = 'new';
            }
            $item['updated_at'] = date('c');
            $items[] = $item;
        }
        usort($items, static function(array $a, array $b): int {
            return strcmp((string)($b['created_at'] ?? ''), (string)($a['created_at'] ?? ''));
        });
        $data['items'] = $items;
        cms_save_leads($data);
        $notice = '<div class="notice">CRM-заявки сохранены.</div>';
    }
}

$filter = (string)($_GET['status'] ?? 'all');
$sort = (string)($_GET['sort'] ?? 'newest');
$itemsView = $data['items'];
if ($filter !== 'all') {
    $itemsView = array_values(array_filter($itemsView, static function(array $item) use ($filter): bool {
        return (string)($item['status'] ?? 'new') === $filter;
    }));
}
if ($sort === 'oldest') {
    usort($itemsView, static fn(array $a, array $b): int => strcmp((string)($a['created_at'] ?? ''), (string)($b['created_at'] ?? '')));
} elseif ($sort === 'status') {
    usort($itemsView, static fn(array $a, array $b): int => strcmp((string)($a['status'] ?? ''), (string)($b['status'] ?? '')));
}
$stats = revenue_dashboard_stats();
ob_start();
echo $notice;
?>
<div class="grid grid-4 crm-top-cards">
  <div class="card"><div class="badge">Всего</div><h2><?= count($data['items']) ?></h2><p>Заявок в CRM.</p></div>
  <div class="card"><div class="badge">Новые</div><h2><?= $stats['new'] ?></h2><p>Требуют внимания.</p></div>
  <div class="card"><div class="badge">Подтверждено</div><h2><?= $stats['confirmed'] + $stats['done'] ?></h2><p>Активные и завершённые брони.</p></div>
  <div class="card"><div class="badge">Потенциал</div><h2><?= number_format($stats['revenue_potential'], 0, '.', ' ') ?> ₽</h2><p>Ожидаемая выручка.</p></div>
</div>
<div class="panel crm-toolbar" style="margin:18px 0">
  <div class="module-actions crm-filters">
    <a class="pill <?= $filter==='all' ? 'pill--active' : '' ?>" href="?status=all&sort=<?= e($sort) ?>">Все</a>
    <?php foreach ($statusMap as $key => $label): ?>
      <a class="pill status-chip status-chip--<?= e($key) ?> <?= $filter===$key ? 'pill--active' : '' ?>" href="?status=<?= e($key) ?>&sort=<?= e($sort) ?>"><?= e($label) ?></a>
    <?php endforeach; ?>
  </div>
  <form method="get" class="module-actions">
    <input type="hidden" name="status" value="<?= e($filter) ?>">
    <label><span>Сортировка</span>
      <select name="sort" onchange="this.form.submit()">
        <option value="newest" <?= $sort==='newest' ? 'selected' : '' ?>>сначала новые</option>
        <option value="oldest" <?= $sort==='oldest' ? 'selected' : '' ?>>сначала старые</option>
        <option value="status" <?= $sort==='status' ? 'selected' : '' ?>>по статусам</option>
      </select>
    </label>
  </form>
</div>
<form class="grid" method="post">
  <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>">
  <?php foreach ($itemsView as $i => $item): $status=(string)($item['status'] ?? 'new'); $collapsed = $status !== 'new'; ?>
    <section class="panel grid collection-item crm-lead status-chip--<?= e($status) ?>" data-collapsible-card>
      <div class="collection-item__head crm-lead__header">
        <div>
          <strong><?= e($item['name'] ?? 'Заявка') ?></strong>
          <div class="muted"><?= e(($item['created_at'] ?? '') . ' • IP: ' . ($item['ip'] ?? '—') . ' • Страна: ' . ($item['country'] ?? '—') . ' • Заходов: ' . (string)($item['visits'] ?? '0')) ?></div>
        </div>
        <div class="module-actions">
          <span class="pill status-chip status-chip--<?= e($status) ?>"><?= e($statusMap[$status] ?? 'Новая') ?></span>
          <button class="button button--ghost button--sm" type="button" data-card-toggle><?= $collapsed ? 'Развернуть' : 'Свернуть' ?></button>
        </div>
      </div>
      <div class="crm-lead__summary">
        <span><strong>Домик:</strong> <?= e($item['house'] ?? '—') ?></span>
        <span><strong>Даты:</strong> <?= e(($item['checkin'] ?? '—') . ' → ' . ($item['checkout'] ?? '—')) ?></span>
        <span><strong>Телефон:</strong> <?= e($item['phone'] ?? '—') ?></span>
        <span><strong>Источник:</strong> <?= e($item['source'] ?? '—') ?></span>
      </div>
      <div class="crm-lead__body <?= $collapsed ? 'is-collapsed' : '' ?>" data-card-body>
      <input type="hidden" name="items[<?= $i ?>][id]" value="<?= e($item['id'] ?? '') ?>">
      <input type="hidden" name="items[<?= $i ?>][created_at]" value="<?= e($item['created_at'] ?? '') ?>">
      <div class="grid grid-4">
        <label><span>Статус</span><select name="items[<?= $i ?>][status]"><?php foreach ($statusMap as $key=>$label): ?><option value="<?= e($key) ?>" <?= $status === $key ? 'selected' : '' ?>><?= e($label) ?></option><?php endforeach; ?></select></label>
        <label><span>Имя</span><input name="items[<?= $i ?>][name]" value="<?= e($item['name'] ?? '') ?>"></label>
        <label><span>Телефон</span><input name="items[<?= $i ?>][phone]" value="<?= e($item['phone'] ?? '') ?>"></label>
        <label><span>Telegram / WA</span><input name="items[<?= $i ?>][contact_nick]" value="<?= e($item['contact_nick'] ?? '') ?>"></label>
      </div>
      <div class="grid grid-4">
        <label><span>Домик</span><input name="items[<?= $i ?>][house]" value="<?= e($item['house'] ?? '') ?>"></label>
        <label><span>Заезд</span><input name="items[<?= $i ?>][checkin]" value="<?= e($item['checkin'] ?? '') ?>"></label>
        <label><span>Выезд</span><input name="items[<?= $i ?>][checkout]" value="<?= e($item['checkout'] ?? '') ?>"></label>
        <label><span>Ориентир суммы</span><input name="items[<?= $i ?>][estimated_total]" value="<?= e($item['estimated_total'] ?? '') ?>"></label>
      </div>
      <div class="grid grid-4">
        <label><span>Взрослые</span><input name="items[<?= $i ?>][adults]" value="<?= e($item['adults'] ?? '') ?>"></label>
        <label><span>Дети</span><input name="items[<?= $i ?>][children]" value="<?= e($item['children'] ?? '') ?>"></label>
        <label><span>Питомец</span><input name="items[<?= $i ?>][pet]" value="<?= e($item['pet'] ?? '') ?>"></label>
        <label><span>Источник</span><input name="items[<?= $i ?>][source]" value="<?= e($item['source'] ?? '') ?>"></label>
      </div>
      <div class="grid grid-3">
        <label><span>IP</span><input name="items[<?= $i ?>][ip]" value="<?= e($item['ip'] ?? '') ?>"></label>
        <label><span>Страна</span><input name="items[<?= $i ?>][country]" value="<?= e($item['country'] ?? '') ?>"></label>
        <label><span>Заходов</span><input name="items[<?= $i ?>][visits]" value="<?= e((string)($item['visits'] ?? '0')) ?>"></label>
      </div>
      <label><span>Комментарий</span><textarea name="items[<?= $i ?>][comment]"><?= e($item['comment'] ?? '') ?></textarea></label>
      <label><span>User-Agent</span><textarea name="items[<?= $i ?>][user_agent]"><?= e($item['user_agent'] ?? '') ?></textarea></label>
      <label><span>Заметка менеджера</span><textarea name="items[<?= $i ?>][manager_note]"><?= e($item['manager_note'] ?? '') ?></textarea></label>
      <div class="module-actions">
        <label class="pill"><input type="checkbox" name="items[<?= $i ?>][is_hidden]" value="1" <?= !empty($item['is_hidden']) || $status==='hidden' ? 'checked' : '' ?>> скрыть</label>
        <label class="pill danger"><input type="checkbox" name="items[<?= $i ?>][_delete]" value="1"> удалить</label>
      </div>
      </div>
    </section>
  <?php endforeach; ?>
  <div class="panel sticky-actions"><button class="button" type="submit">Сохранить CRM</button></div>
</form>
<?php
admin_layout('CRM заявки', ob_get_clean(), 'leads');
