<?php
$d = $data;
$hour = (int) date('G');
$hi = $hour < 12 ? 'Good morning' : ($hour < 17 ? 'Good afternoon' : 'Good evening');
$colors = ['#3b82f6', '#22c55e', '#eab308', '#a855f7', '#ef4444', '#14b8a6', '#f97316'];
$deltas = $d['deltas'] ?? [];
$mkt = $d['marketing'] ?? [];
$funnel = [];
foreach ($d['pipeline'] as $s) {
    if ((int) $s['is_lost'] === 1) {
        continue;
    }
    $funnel[] = $s;
}
$rankIcons = [
    ['bi-trophy-fill', '#f59e0b'],
    ['bi-award-fill', '#94a3b8'],
    ['bi-trophy-fill', '#fb923c'],
    ['bi-4-circle-fill', '#60a5fa'],
];
$kpis = [
    ['New Leads', (string) (int) $d['new_leads'], 'bi-person-plus', '#3b82f6', $deltas['new_leads'] ?? null],
    [opportunity_label(), (string) (int) $d['opportunities'], 'bi-currency-dollar', '#22c55e', $deltas['opportunities'] ?? null],
    ['Pipeline Value', money_compact($d['pipeline_value']), 'bi-diagram-3', '#8b5cf6', $deltas['pipeline_value'] ?? null],
    ['Won ' . opportunity_label(), (string) (int) $d['won_deals'], 'bi-bag-check', '#f97316', $deltas['won_deals'] ?? null],
    ['Emails Sent', (string) (int) $d['emails_month'], 'bi-envelope', '#14b8a6', $deltas['emails_month'] ?? null],
    ['Tasks Due', (string) (int) $d['tasks_due'], 'bi-calendar-check', '#ef4444', $deltas['tasks_due'] ?? null],
];
$actTypes = [
    ['Calls', 'call', 'bi-telephone', '#3b82f6'],
    ['Meetings', 'meeting', 'bi-people', '#22c55e'],
    ['Emails', 'email', 'bi-envelope', '#14b8a6'],
    ['Notes', 'note', 'bi-sticky', '#eab308'],
];
$chart = $d['activity_chart'] ?? ['labels' => [], 'values' => []];
?>
<div class="d-flex justify-content-between align-items-start mb-3 dash-head">
  <div>
    <h1 class="page-title"><?= e($hi) ?>, <?= e(current_user()['first_name']) ?>! <span class="dash-wave">👋</span></h1>
    <p class="page-sub mb-0">Here’s what’s happening with your business today.</p>
  </div>
  <div class="d-flex flex-wrap align-items-center gap-2">
    <?php \App\Core\View::partial('smart_tips_jump', ['tips' => $tips ?? []]); ?>
    <div class="dash-date"><i class="bi bi-calendar3"></i> <?= date('M j, Y') ?></div>
  </div>
</div>
<?php if (dash_on('kpis')): ?>
<div class="kpi-row mb-3">
  <?php foreach ($kpis as $k):
    $delta = $k[4];
  ?>
    <div class="card-soft kpi kpi-compact">
      <div class="kpi-icon" style="background:<?= e($k[3]) ?>"><i class="bi <?= e($k[2]) ?>"></i></div>
      <div class="kpi-body">
        <span><?= e($k[0]) ?></span>
        <h3><?= e($k[1]) ?></h3>
        <?php if (is_array($delta) && !empty($delta['show'])): ?>
          <div class="kpi-delta <?= !empty($delta['up']) ? 'up' : 'down' ?>">
            <i class="bi <?= !empty($delta['up']) ? 'bi-arrow-up' : 'bi-arrow-down' ?>"></i>
            <?= (int) $delta['pct'] ?>% vs yesterday
          </div>
        <?php endif; ?>
      </div>
    </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>
<div class="row g-3 mb-3">
  <?php if (dash_on('pipeline')): ?>
  <div class="col-lg-6">
    <div class="card-soft dp-card h-100">
      <div class="dp-head">
        <div class="dp-head-icon"><i class="bi bi-diagram-3-fill"></i></div>
        <div class="min-w-0 flex-grow-1">
          <h2>Pipeline Overview</h2>
          <p>Open deals by stage</p>
        </div>
        <a href="<?= e(url('opportunities')) ?>">Pipeline</a>
      </div>
      <div class="dp-body">
        <div class="funnel-board">
          <div class="funnel">
            <?php
            $n = max(1, count($funnel));
            foreach ($funnel as $i => $s):
              $w = 100 - (int) round(($i / max(1, $n - 1)) * 42);
            ?>
              <div class="funnel-slice" style="width:<?= $w ?>%;background:<?= e($colors[$i % count($colors)]) ?>"></div>
            <?php endforeach; ?>
          </div>
          <div class="funnel-legend">
            <?php foreach ($funnel as $i => $s): ?>
              <div class="funnel-legend-row">
                <span class="funnel-dot" style="background:<?= e($colors[$i % count($colors)]) ?>"></span>
                <span class="flex-grow-1"><?= e($s['name']) ?> (<?= (int) $s['deal_count'] ?>)</span>
                <span class="text-muted"><?= money_fmt($s['deal_value']) ?></span>
              </div>
            <?php endforeach; ?>
          </div>
        </div>
        <div class="d-flex justify-content-between align-items-end mt-3 pt-2 border-top">
          <div>
            <div class="small text-muted">Total Pipeline Value</div>
            <div class="fw-bold fs-5"><?= money_fmt($d['pipeline_value']) ?></div>
          </div>
          <a class="small" href="<?= e(url('opportunities')) ?>">View full pipeline →</a>
        </div>
      </div>
    </div>
  </div>
  <?php endif; ?>
  <?php if (dash_on('team')): ?>
  <div class="col-lg-6">
    <div class="card-soft da-card h-100">
      <div class="da-head">
        <div class="da-head-icon"><i class="bi bi-graph-up-arrow"></i></div>
        <div class="min-w-0 flex-grow-1">
          <h2>Sales Activity</h2>
          <p>This month</p>
        </div>
      </div>
      <div class="da-chart">
        <canvas id="salesActivityChart" height="140"></canvas>
      </div>
      <div class="da-stats">
        <?php foreach ($actTypes as $t):
          $td = $deltas[$t[1]] ?? null;
        ?>
          <div class="da-stat" style="--act-accent: <?= e($t[3]) ?>">
            <div class="da-stat-ico" style="background:<?= e($t[3]) ?>20;color:<?= e($t[3]) ?>"><i class="bi <?= e($t[2]) ?>"></i></div>
            <div class="min-w-0">
              <div class="da-stat-n"><?= (int) ($d['type_counts'][$t[1]] ?? 0) ?></div>
              <div class="da-stat-l"><?= e($t[0]) ?></div>
              <?php if (is_array($td) && !empty($td['show'])): ?>
                <div class="kpi-delta <?= !empty($td['up']) ? 'up' : 'down' ?>">
                  <i class="bi <?= !empty($td['up']) ? 'bi-arrow-up' : 'bi-arrow-down' ?>"></i> <?= (int) $td['pct'] ?>%
                </div>
              <?php endif; ?>
            </div>
          </div>
        <?php endforeach; ?>
      </div>
    </div>
  </div>
  <?php endif; ?>
</div>
<?php if (dash_on('team')): ?>
<div class="row g-3 mb-3">
  <div class="col-lg-6">
    <?php \App\Core\View::partial('home_tasks', ['tasks' => $d['tasks'] ?? [], 'mode' => 'today']); ?>
  </div>
  <div class="col-lg-6">
    <?php \App\Core\View::partial('home_tasks', ['tasks' => $d['tasks'] ?? [], 'mode' => 'overdue']); ?>
  </div>
</div>
<div class="row g-3 mb-3">
  <div class="col-lg-4">
    <div class="card-soft do-card h-100">
      <div class="do-head">
        <div class="do-head-icon"><i class="bi bi-trophy-fill"></i></div>
        <div class="min-w-0 flex-grow-1">
          <h2>Top <?= e(opportunity_label()) ?></h2>
          <p><?= $d['top_opps'] ? count($d['top_opps']) . ' highest open deals' : 'Highest open deals' ?></p>
        </div>
        <a href="<?= e(url('opportunities')) ?>">View all</a>
      </div>
      <?php if ($d['top_opps']): ?>
      <div class="do-list">
        <?php foreach ($d['top_opps'] as $i => $o):
            $icon = $rankIcons[$i] ?? ['bi-circle-fill', '#94a3b8'];
        ?>
          <a class="do-item is-<?= (int) $i + 1 ?>" href="<?= e(url('opportunities/'.$o['id'])) ?>">
            <span class="do-rank" style="color:<?= e($icon[1]) ?>"><i class="bi <?= e($icon[0]) ?>"></i></span>
            <span class="min-w-0 flex-grow-1">
              <span class="do-name"><?= e($o['name']) ?></span>
              <span class="do-co"><?= e($o['account_name']) ?></span>
            </span>
            <span class="do-amt"><?= money_fmt($o['amount']) ?></span>
          </a>
        <?php endforeach; ?>
      </div>
      <?php else: ?>
      <div class="do-empty"><i class="bi bi-trophy"></i><strong>No open deals yet</strong><span>Top deals by value will show here.</span></div>
      <?php endif; ?>
    </div>
  </div>
  <div class="col-lg-4">
    <?php \App\Core\View::partial('home_recent', ['recent' => $d['recent'] ?? []]); ?>
  </div>
  <div class="col-lg-4">
    <?php \App\Core\View::partial('home_upcoming', ['meetings' => $d['meetings'] ?? []]); ?>
  </div>
  <?php endif; ?>
</div>
<?php \App\Core\View::partial('home_work_lists', [
    'newLeads' => $d['new_lead_rows'] ?? [],
    'needsAction' => $d['needs_action'] ?? [],
    'riskDeals' => $d['risk_deals'] ?? [],
    'riskAccounts' => $d['risk_accounts'] ?? [],
    'mine' => false,
]); ?>
<?php if (dash_on('marketing')): ?>
<?php \App\Core\View::partial('home_marketing', ['mkt' => $mkt, 'wide' => true]); ?>
<?php endif; ?>
<?php \App\Core\View::partial('smart_tips', ['tips' => $tips ?? [], 'kind' => 'manager', 'ask' => $ask ?? null]); ?>
<?php
$chartJson = json_encode($chart, JSON_UNESCAPED_SLASHES);
$scripts = <<<HTML
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
<script>
(function () {
  var el = document.getElementById('salesActivityChart');
  if (!el || typeof Chart === 'undefined') return;
  var data = {$chartJson};
  var ctx = el.getContext('2d');
  var grad = ctx.createLinearGradient(0, 0, 0, 140);
  grad.addColorStop(0, 'rgba(26,86,200,.28)');
  grad.addColorStop(1, 'rgba(26,86,200,0)');
  new Chart(ctx, {
    type: 'line',
    data: {
      labels: data.labels || [],
      datasets: [{
        data: data.values || [],
        borderColor: '#1a56c8',
        backgroundColor: grad,
        fill: true,
        tension: 0.35,
        pointRadius: 3,
        pointHoverRadius: 5,
        pointBackgroundColor: '#1a56c8',
        borderWidth: 2
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: { legend: { display: false } },
      scales: {
        x: { grid: { display: false }, ticks: { maxTicksLimit: 6, color: '#9ca3af', font: { size: 11 } } },
        y: { beginAtZero: true, grid: { color: '#eef2f7' }, ticks: { color: '#9ca3af', font: { size: 11 }, precision: 0 } }
      }
    }
  });
})();
</script>
HTML;
?>
