<?php
$newLeads = $newLeads ?? [];
$needsAction = $needsAction ?? [];
$riskDeals = $riskDeals ?? [];
$riskAccounts = $riskAccounts ?? [];
$mine = !empty($mine);
$leadTitle = $mine ? 'New leads assigned to me' : 'New leads';
$dealTitle = 'Opportunities requiring action';
$riskTitle = 'At-risk customers or deals';
?>
<div class="row g-3 mb-3">
  <?php if (can_see('leads')):
    $leadN = count($newLeads);
    $leadTodayN = 0;
    foreach ($newLeads as $leadRow) {
        $made = (string) ($leadRow['created_at'] ?? '');
        if ($made !== '' && date('Y-m-d', (int) strtotime($made)) === date('Y-m-d')) {
            $leadTodayN++;
        }
    }
    $leadSub = $leadN
        ? $leadN . ' waiting to qualify'
        : ($mine ? 'Nobody new on your list' : 'No new leads right now');
  ?>
  <div class="col-lg-4">
    <div class="card-soft hl-card h-100">
      <div class="hl-head">
        <div class="hl-head-icon"><i class="bi bi-person-plus"></i></div>
        <div class="min-w-0 flex-grow-1">
          <h2><?= e($leadTitle) ?></h2>
          <p><?= e($leadSub) ?></p>
        </div>
        <a href="<?= e(url('leads')) ?>">Leads</a>
      </div>
      <?php if ($leadN): ?>
      <div class="hl-pills">
        <span class="hl-pill is-new"><i class="bi bi-sparkles"></i> <?= (int) $leadN ?> new</span>
        <?php if ($leadTodayN): ?>
          <span class="hl-pill is-today"><i class="bi bi-sun"></i> <?= (int) $leadTodayN ?> today</span>
        <?php endif; ?>
      </div>
      <div class="hl-list">
        <?php foreach ($newLeads as $lead):
            $leadName = trim(($lead['first_name'] ?? '') . ' ' . ($lead['last_name'] ?? ''));
            if ($leadName === '') {
                $leadName = 'Lead';
            }
            $co = trim((string) ($lead['company'] ?? ''));
            $src = trim((string) ($lead['source'] ?? ''));
            $owner = trim((string) ($lead['owner_name'] ?? ''));
            $fresh = !empty($lead['created_at']) && date('Y-m-d', (int) strtotime((string) $lead['created_at'])) === date('Y-m-d');
        ?>
          <a class="hl-item<?= $fresh ? ' is-today' : '' ?>" href="<?= e(url('leads/' . (int) $lead['id'])) ?>">
            <span class="hl-avatar"><?= e(name_initials($leadName)) ?></span>
            <span class="hl-body min-w-0">
              <span class="hl-title text-truncate"><?= e($leadName) ?></span>
              <span class="hl-meta">
                <?php if ($co !== ''): ?><span class="hl-co text-truncate"><?= e($co) ?></span><?php endif; ?>
                <?php if ($src !== ''): ?><span class="hl-src"><?= e($src) ?></span><?php endif; ?>
                <?php if (!$mine && $owner !== ''): ?><span class="hl-owner text-truncate"><?= e($owner) ?></span><?php endif; ?>
              </span>
              <?php if (!empty($lead['email']) || !empty($lead['phone'])): ?>
                <span class="hl-contact">
                  <?php if (!empty($lead['email'])): ?><span class="text-truncate"><i class="bi bi-envelope"></i> <?= e($lead['email']) ?></span><?php endif; ?>
                  <?php if (!empty($lead['phone'])): ?><span><i class="bi bi-telephone"></i> <?= e($lead['phone']) ?></span><?php endif; ?>
                </span>
              <?php endif; ?>
            </span>
            <span class="hl-when"><?= e(relative_when($lead['created_at'] ?? null)) ?></span>
          </a>
        <?php endforeach; ?>
      </div>
      <?php else: ?>
      <div class="hl-empty">
        <i class="bi bi-person-plus"></i>
        <strong>No new leads</strong>
        <span><?= $mine ? 'Nothing new assigned to you yet.' : 'No new leads in the queue.' ?></span>
      </div>
      <?php endif; ?>
    </div>
  </div>
  <?php endif; ?>
  <?php if (can_see('opportunities')):
    $dealN = count($needsAction);
    $dealLateN = 0;
    $dealMissN = 0;
    $todayKey = date('Y-m-d');
    foreach ($needsAction as $dealRow) {
        $stepAt = (string) ($dealRow['next_step_at'] ?? '');
        $stepNote = trim((string) ($dealRow['next_step'] ?? ''));
        $stepDay = $stepAt !== '' ? date('Y-m-d', (int) strtotime($stepAt)) : '';
        if ($stepAt === '' || $stepNote === '') {
            $dealMissN++;
        } elseif ($stepDay !== '' && $stepDay < $todayKey) {
            $dealLateN++;
        }
    }
    $dealSub = $dealN ? $dealN . ' waiting on a next step' : 'Nothing waiting on a next step';
  ?>
  <div class="col-lg-4">
    <div class="card-soft ho-card h-100">
      <div class="ho-head">
        <div class="ho-head-icon"><i class="bi bi-briefcase"></i></div>
        <div class="min-w-0 flex-grow-1">
          <h2><?= e($dealTitle) ?></h2>
          <p><?= e($dealSub) ?></p>
        </div>
        <a href="<?= e(url('opportunities')) ?>">Pipeline</a>
      </div>
      <?php if ($dealN): ?>
      <div class="ho-pills">
        <?php if ($dealLateN): ?>
          <span class="ho-pill is-late"><i class="bi bi-exclamation-circle"></i> <?= (int) $dealLateN ?> late</span>
        <?php endif; ?>
        <?php if ($dealMissN): ?>
          <span class="ho-pill is-miss"><i class="bi bi-flag"></i> <?= (int) $dealMissN ?> no next step</span>
        <?php endif; ?>
        <?php if (!$dealLateN && !$dealMissN): ?>
          <span class="ho-pill is-due"><i class="bi bi-clock"></i> <?= (int) $dealN ?> due</span>
        <?php endif; ?>
      </div>
      <div class="ho-list">
        <?php foreach ($needsAction as $deal):
            $due = due_label($deal['next_step_at'] ?? null);
            $stepNote = trim((string) ($deal['next_step'] ?? ''));
            $stepAt = (string) ($deal['next_step_at'] ?? '');
            $stepDay = $stepAt !== '' ? date('Y-m-d', (int) strtotime($stepAt)) : '';
            $tone = ($stepAt === '' || $stepNote === '') ? 'miss' : (($stepDay !== '' && $stepDay < $todayKey) ? 'late' : 'due');
            $acct = trim((string) ($deal['account_name'] ?? ''));
            $stage = trim((string) ($deal['stage_name'] ?? ''));
            $amount = $deal['amount'] ?? null;
        ?>
          <a class="ho-item is-<?= e($tone) ?>" href="<?= e(url('opportunities/' . (int) $deal['id'])) ?>">
            <span class="ho-mark"><i class="bi <?= $tone === 'late' ? 'bi-exclamation-lg' : ($tone === 'miss' ? 'bi-flag' : 'bi-arrow-right') ?>"></i></span>
            <span class="ho-body min-w-0">
              <span class="ho-title text-truncate"><?= e($deal['name'] ?: 'Untitled') ?></span>
              <span class="ho-meta">
                <?php if ($acct !== ''): ?><span class="ho-acct text-truncate"><?= e($acct) ?></span><?php endif; ?>
                <?php if ($stage !== ''): ?><span class="ho-stage"><?= e($stage) ?></span><?php endif; ?>
                <?php if ($amount !== null && $amount !== '' && (float) $amount > 0): ?><span class="ho-amt"><?= e(money_fmt($amount)) ?></span><?php endif; ?>
              </span>
              <?php if ($stepNote !== ''): ?>
                <span class="ho-step text-truncate"><?= e($stepNote) ?></span>
              <?php else: ?>
                <span class="ho-step is-empty">Add a next step</span>
              <?php endif; ?>
            </span>
            <span class="ho-due <?= e($due['class'] ?: 'due-later') ?>"><?= e($due['text'] !== '' ? $due['text'] : 'No date') ?></span>
          </a>
        <?php endforeach; ?>
      </div>
      <?php else: ?>
      <div class="ho-empty">
        <i class="bi bi-briefcase"></i>
        <strong>All next steps are set</strong>
        <span>No open opportunities are waiting on you.</span>
      </div>
      <?php endif; ?>
    </div>
  </div>
  <?php endif; ?>
  <?php
    $riskDealN = count($riskDeals);
    $riskAcctN = count($riskAccounts);
    $riskN = $riskDealN + $riskAcctN;
    $riskSub = $riskN
        ? trim(($riskDealN ? $riskDealN . ' deal' . ($riskDealN === 1 ? '' : 's') : '') . ($riskDealN && $riskAcctN ? ' · ' : '') . ($riskAcctN ? $riskAcctN . ' customer' . ($riskAcctN === 1 ? '' : 's') : ''))
        : 'Nothing looks shaky right now';
    $riskGroups = [
        ['key' => 'deal', 'label' => 'Deals', 'icon' => 'bi-briefcase', 'rows' => $riskDeals],
        ['key' => 'account', 'label' => 'Customers', 'icon' => 'bi-buildings', 'rows' => $riskAccounts],
    ];
  ?>
  <div class="col-lg-4">
    <div class="card-soft hr-card h-100">
      <div class="hr-head">
        <div class="hr-head-icon"><i class="bi bi-exclamation-triangle"></i></div>
        <div class="min-w-0 flex-grow-1">
          <h2><?= e($riskTitle) ?></h2>
          <p><?= e($riskSub) ?></p>
        </div>
      </div>
      <?php if ($riskN): ?>
      <div class="hr-pills">
        <?php if ($riskDealN): ?>
          <span class="hr-pill is-deal"><i class="bi bi-briefcase"></i> <?= (int) $riskDealN ?> deal<?= $riskDealN === 1 ? '' : 's' ?></span>
        <?php endif; ?>
        <?php if ($riskAcctN): ?>
          <span class="hr-pill is-account"><i class="bi bi-buildings"></i> <?= (int) $riskAcctN ?> customer<?= $riskAcctN === 1 ? '' : 's' ?></span>
        <?php endif; ?>
      </div>
      <div class="hr-list">
        <?php foreach ($riskGroups as $group):
            if (!$group['rows']) {
                continue;
            }
        ?>
          <div class="hr-group-label is-<?= e($group['key']) ?>"><i class="bi <?= e($group['icon']) ?>"></i> <?= e($group['label']) ?></div>
          <?php foreach ($group['rows'] as $risk): ?>
            <a class="hr-item is-<?= e($group['key']) ?>" href="<?= e((string) $risk['url']) ?>">
              <span class="hr-mark"><i class="bi <?= e($group['icon']) ?>"></i></span>
              <span class="hr-body min-w-0">
                <span class="hr-title text-truncate"><?= e((string) $risk['title']) ?></span>
                <span class="hr-why text-truncate"><?= e((string) $risk['why']) ?></span>
              </span>
            </a>
          <?php endforeach; ?>
        <?php endforeach; ?>
      </div>
      <?php else: ?>
      <div class="hr-empty">
        <i class="bi bi-shield-check"></i>
        <strong>Nothing at risk</strong>
        <span>No cold deals or late customers right now.</span>
      </div>
      <?php endif; ?>
    </div>
  </div>
</div>
