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

$leads = array_values(array_filter((cms_leads()['items'] ?? []), static fn($item) => empty($item['is_hidden'])));
$statusMap = [
    'new' => 'Новая',
    'in_progress' => 'В работе',
    'confirmed' => 'Подтверждена',
    'done' => 'Заселился / завершена',
    'cancelled' => 'Отменена',
];
$stats = [];
$total = 0.0;
foreach ($statusMap as $key => $label) {
    $subset = array_values(array_filter($leads, static fn($item) => ($item['status'] ?? 'new') === $key));
    $sum = 0.0;
    foreach ($subset as $lead) $sum += (float)preg_replace('/[^\d.]+/', '', (string)($lead['estimated_total'] ?? '0'));
    $stats[$key] = ['label' => $label, 'count' => count($subset), 'sum' => $sum];
    $total += $sum;
}
$byHouse = [];
foreach ($leads as $lead) {
    $house = trim((string)($lead['house'] ?? 'Не указан')) ?: 'Не указан';
    $sum = (float)preg_replace('/[^\d.]+/', '', (string)($lead['estimated_total'] ?? '0'));
    if (!isset($byHouse[$house])) $byHouse[$house] = ['count' => 0, 'sum' => 0.0];
    $byHouse[$house]['count']++;
    $byHouse[$house]['sum'] += $sum;
}
uksort($byHouse, fn($a,$b)=>strcmp($a,$b));
ob_start();
?>
<div class="grid grid-4">
  <div class="card"><div class="badge">Потенциал</div><h2><?= number_format($total, 0, ',', ' ') ?> ₽</h2><p>Сумма по всем не скрытым заявкам.</p></div>
  <?php foreach (['confirmed','done','cancelled'] as $key): ?>
    <div class="card"><div class="badge"><?= e($stats[$key]['label']) ?></div><h2><?= number_format($stats[$key]['sum'], 0, ',', ' ') ?> ₽</h2><p><?= $stats[$key]['count'] ?> заявок</p></div>
  <?php endforeach; ?>
</div>
<div class="grid grid-2" style="margin-top:18px">
  <section class="panel grid">
    <div class="badge">По статусам</div>
    <div class="table-wrap"><table class="admin-table"><thead><tr><th>Статус</th><th>Заявок</th><th>Сумма</th></tr></thead><tbody>
    <?php foreach ($stats as $row): ?><tr><td><?= e($row['label']) ?></td><td><?= $row['count'] ?></td><td><?= number_format($row['sum'], 0, ',', ' ') ?> ₽</td></tr><?php endforeach; ?>
    </tbody></table></div>
  </section>
  <section class="panel grid">
    <div class="badge">По домикам</div>
    <div class="table-wrap"><table class="admin-table"><thead><tr><th>Домик</th><th>Заявок</th><th>Потенциал</th></tr></thead><tbody>
    <?php foreach ($byHouse as $house => $row): ?><tr><td><?= e($house) ?></td><td><?= $row['count'] ?></td><td><?= number_format($row['sum'], 0, ',', ' ') ?> ₽</td></tr><?php endforeach; ?>
    </tbody></table></div>
  </section>
</div>
<?php
admin_layout('Финансовая статистика', ob_get_clean(), 'revenue');
