<?php
declare(strict_types=1);
require_once __DIR__ . '/_inc/boot.php';
require_once __DIR__ . '/_inc/db.php';
require_once __DIR__ . '/_inc/pickpack.php';
require_once __DIR__ . '/_inc/token.php';

$pdo = db();
auth_require_permission('view_dashboard');

$title = 'Home · Status';
$active = 'home';

$days = isset($_GET['days']) ? max(14, min(365, (int)$_GET['days'])) : 30;
$q = trim((string)($_GET['q'] ?? ''));

$lscStatus = trim((string)($_GET['lsc_status'] ?? ''));
$lscCountry = trim((string)($_GET['lsc_country'] ?? ''));

// countries (enabled affects KPIs + sync; show_on_home affects only Home cards)
$countriesEnabled = $pdo->query("
  SELECT TRIM(code) AS code, name
  FROM countries
  WHERE COALESCE(enabled, 0) = 1
    AND TRIM(code) <> ''
  ORDER BY name
")->fetchAll();
$countriesHome = $pdo->query("
  SELECT TRIM(code) AS code, name, COALESCE(enabled, 0) AS enabled
  FROM countries
  WHERE COALESCE(enabled, 0) = 1
    AND COALESCE(show_on_home, 1) = 1
    AND TRIM(code) <> ''
  ORDER BY name
")->fetchAll();

// aggregates per country
$agg = [];
foreach ($countriesEnabled as $c) {
  $code = $c['code'];
  $st = $pdo->prepare("SELECT
      COUNT(*) AS total_leads,
      SUM(confirmed_at IS NOT NULL) AS confirmed_cnt,
      SUM(delivered_at IS NOT NULL OR current_status='delivered') AS delivered_cnt,
      SUM(returned_at IS NOT NULL OR current_status='returned') AS returned_cnt,
      SUM(rejected_at IS NOT NULL OR current_status='rejected' OR ever_rejected=1) AS rejected_cnt,
      SUM(current_status='in_delivery') AS in_delivery_cnt,
      SUM(current_status='incident') AS incident_cnt,
      SUM(COALESCE(qty_cards,0)) AS cards_qty_all,
      SUM(CASE WHEN confirmed_at IS NOT NULL THEN COALESCE(qty_cards,0) ELSE 0 END) AS cards_qty_confirmed
    FROM leads WHERE country=?");
  $st->execute([$code]);
  $row = $st->fetch() ?: [];
  $st2 = $pdo->prepare("SELECT SUM(COALESCE(last_stock_qty,0)) AS stock_qty FROM cards WHERE active=1 AND country=?");
  $st2->execute([$code]);
  $stock = $st2->fetch();
  $row['stock_qty'] = (int)($stock['stock_qty'] ?? 0);
  $agg[$code] = $row;
}

// latest status changes (optional filters)
$latestWhere = [];
$latestArgs = [];
if ($lscCountry !== '') {
  $latestWhere[] = 'l.country = ?';
  $latestArgs[] = strtoupper($lscCountry);
}
if ($lscStatus !== '') {
  $latestWhere[] = '(h.status_norm = ? OR l.current_status = ?)';
  $latestArgs[] = $lscStatus;
  $latestArgs[] = $lscStatus;
}
if ($q !== '') {
  $like = '%' . $q . '%';
  $latestWhere[] = '(h.lead_number LIKE ? OR l.customer_name LIKE ? OR l.email LIKE ? OR l.phone LIKE ? OR l.tracking_number LIKE ?)';
  array_push($latestArgs, $like, $like, $like, $like, $like);
}
$latestSql = "SELECT h.lead_number,h.status_norm,h.status_raw,h.status_at,l.country,l.customer_name,l.email,l.phone,l.current_status,l.current_status_at,l.tracking_number,l.order_id_remote,l.courier_code,l.qty_cards,l.details_json
  FROM lead_history h
  JOIN leads l ON l.lead_number=h.lead_number";
if (count($latestWhere) > 0) {
  $latestSql .= ' WHERE ' . implode(' AND ', $latestWhere);
}
$latestSql .= " ORDER BY COALESCE(h.status_at,'1970-01-01') DESC, h.id DESC LIMIT 50";
$stLatest = $pdo->prepare($latestSql);
$stLatest->execute($latestArgs);
$latest = $stLatest->fetchAll();

// home countries (respect settings toggle)
$pinnedCountries = $countriesHome;

require_once __DIR__ . '/_inc/layout_top.php';
?>
<div data-autorefresh="1" data-kind="home"></div>

<?php
// overall KPIs
$overall = [
  'total'=>0,'confirmed'=>0,'delivered'=>0,'returned'=>0,'rejected'=>0,'in_delivery'=>0,'incident'=>0,'cards'=>0,'stock'=>0
];
foreach($countriesEnabled as $c){
  $code = $c['code'];
  $a = $agg[$code] ?? [];
  $overall['total'] += (int)($a['total_leads'] ?? 0);
  $overall['confirmed'] += (int)($a['confirmed_cnt'] ?? 0);
  $overall['delivered'] += (int)($a['delivered_cnt'] ?? 0);
  $overall['returned'] += (int)($a['returned_cnt'] ?? 0);
  $overall['rejected'] += (int)($a['rejected_cnt'] ?? 0);
  $overall['in_delivery'] += (int)($a['in_delivery_cnt'] ?? 0);
  $overall['incident'] += (int)($a['incident_cnt'] ?? 0);
  $overall['cards'] += (int)($a['cards_qty_confirmed'] ?? 0);
  $overall['stock'] += (int)($a['stock_qty'] ?? 0);
}
$confRate = $overall['total']>0 ? round($overall['confirmed']*100/$overall['total'],1) : 0;
$delRate  = $overall['confirmed']>0 ? round($overall['delivered']*100/$overall['confirmed'],1) : 0;
$retRate  = $overall['confirmed']>0 ? round($overall['returned']*100/$overall['confirmed'],1) : 0;
$rejRate  = $overall['confirmed']>0 ? round($overall['rejected']*100/$overall['confirmed'],1) : 0;
$inDelRate = $overall['total']>0 ? round($overall['in_delivery']*100/$overall['total'],1) : 0;
$incRate   = $overall['total']>0 ? round($overall['incident']*100/$overall['total'],1) : 0;
?>

<section class="card wide">
  <div class="hd">
    <div class="title">Overview <span class="badge">Enabled countries</span></div>
    <div class="chart-row">
      <div class="pill">Window: <?= (int)$days ?> days</div>
      <svg class="spark" data-spark="trend" data-days="<?= (int)$days ?>" width="220" height="48" aria-label="Trend sparkline"></svg>
    </div>
  </div>
  <div class="bd">
    <div class="kpi-row">
      <div class="kpi neutral"><div class="k">TOTAL LEADS</div><div class="v"><?= (int)$overall['total'] ?></div><div class="p">Across enabled countries</div></div>
      <div class="kpi good"><div class="k">CONFIRMED</div><div class="v"><?= (int)$overall['confirmed'] ?></div><div class="p"><?= $confRate ?>% of total</div></div>
      <div class="kpi good"><div class="k">DELIVERED</div><div class="v"><?= (int)$overall['delivered'] ?></div><div class="p"><?= $delRate ?>% of confirmed</div></div>
      <div class="kpi warn"><div class="k">RETURNED</div><div class="v"><?= (int)$overall['returned'] ?></div><div class="p"><?= $retRate ?>% of confirmed</div></div>
      <div class="kpi bad"><div class="k">REJECTED</div><div class="v"><?= (int)$overall['rejected'] ?></div><div class="p"><?= $rejRate ?>% of confirmed</div></div>
      <div class="kpi neutral"><div class="k">IN DELIVERY</div><div class="v"><?= (int)$overall['in_delivery'] ?></div><div class="p"><?= $inDelRate ?>% of total</div></div>
      <div class="kpi warn"><div class="k">INCIDENT</div><div class="v"><?= (int)$overall['incident'] ?></div><div class="p"><?= $incRate ?>% of total</div></div>
      <div class="kpi neutral"><div class="k">CARDS / STOCK</div><div class="v"><?= (int)$overall['cards'] ?> / <?= (int)$overall['stock'] ?></div><div class="p">Confirmed cards vs active stock</div></div>
    </div>
  </div>
</section>

<section class="card wide" style="margin-top:14px">
  <div class="hd">
    <div class="title">Trend <span class="badge">Created / Confirmed / Delivered / Returned / Rejected</span></div>
    <div class="legend">
      <div class="lg"><span class="dot d-created"></span><span class="t">Created</span></div>
      <div class="lg"><span class="dot d-confirmed"></span><span class="t">Confirmed</span></div>
      <div class="lg"><span class="dot d-delivered"></span><span class="t">Delivered</span></div>
      <div class="lg"><span class="dot d-returned"></span><span class="t">Returned</span></div>
      <div class="lg"><span class="dot d-rejected"></span><span class="t">Rejected</span></div>
    </div>
  </div>
  <div class="bd">
    <svg class="chart" data-chart="trend" data-days="<?= (int)$days ?>" data-h="200" aria-label="Trend chart"></svg>
  </div>
</section>

<?php if(!empty($pinnedCountries)): ?>
<section style="margin-top:14px">
  <div class="countries-wrap">
    <?php foreach($pinnedCountries as $pc):
      $code = $pc['code'];
      $a = $agg[$code] ?? [];
      $total=(int)($a['total_leads'] ?? 0);
      $conf=(int)($a['confirmed_cnt'] ?? 0);
      $del=(int)($a['delivered_cnt'] ?? 0);
      $ret=(int)($a['returned_cnt'] ?? 0);
      $rej=(int)($a['rejected_cnt'] ?? 0);
      // NOTE: aggregated keys come from the query above
      $cards=(int)($a['cards_qty_confirmed'] ?? 0);
      $stock=(int)($a['stock_qty'] ?? 0);

      $confPct = $total>0 ? round($conf*100/$total,1) : 0;
      $delPct  = $total>0 ? ($del*100/$total) : 0;
      $retPct  = $total>0 ? ($ret*100/$total) : 0;
      $rejPct  = $total>0 ? ($rej*100/$total) : 0;
    ?>
    <div class="country-card">
      <div class="country-left">
        <div>
          <div class="country-name"><?= h($pc['name']) ?></div>
          <div class="country-code mono"><?= h($code) ?></div>
        </div>

        <div>
          <div class="total-big"><?= $total ?></div>
          <div class="total-sub">Total leads • Confirmed: <?= $conf ?> (<?= $confPct ?>%)</div>
        </div>

        <div class="country-actions">
          <?php if((int)$pc['enabled']===1): ?>
            <a class="btn btn-sm primary" href="/country.php?country=<?= urlencode($code) ?>">Open</a>
          <?php else: ?>
            <a class="btn btn-sm btn-ghost" href="/settings.php">Enable</a>
          <?php endif; ?>
        </div>
      </div>

      <div class="country-right">
        <div class="chart-row">
          <div class="badge">Cards + Status distribution</div>
          <svg class="spark" data-spark="country" data-country="<?= h($code) ?>" data-days="<?= (int)$days ?>" width="220" height="48" aria-label="Country trend"></svg>
        </div>

        <div class="segbar" aria-label="Status distribution">
          <div class="seg good" style="width: <?= number_format($delPct, 2, '.', '') ?>%"></div>
          <div class="seg warn" style="width: <?= number_format($retPct, 2, '.', '') ?>%"></div>
          <div class="seg bad" style="width: <?= number_format($rejPct, 2, '.', '') ?>%"></div>
          <div class="seg neutral" style="width: <?= number_format(max(0, 100-$delPct-$retPct-$rejPct), 2, '.', '') ?>%"></div>
        </div>

        <div class="mini-grid">
          <div class="mini"><div class="k">DELIVERED</div><div class="v"><?= $del ?></div><div class="p"><?= $total>0?round($del*100/$total,1):0 ?>%</div></div>
          <div class="mini"><div class="k">RETURNED</div><div class="v"><?= $ret ?></div><div class="p"><?= $total>0?round($ret*100/$total,1):0 ?>%</div></div>
          <div class="mini"><div class="k">REJECTED</div><div class="v"><?= $rej ?></div><div class="p"><?= $total>0?round($rej*100/$total,1):0 ?>%</div></div>

          <div class="mini"><div class="k">CONFIRMED</div><div class="v"><?= $conf ?></div><div class="p"><?= $confPct ?>%</div></div>
          <div class="mini"><div class="k">CARDS QTY</div><div class="v"><?= $cards ?></div><div class="p">Confirmed</div></div>
          <div class="mini"><div class="k">STOCK</div><div class="v"><?= $stock ?></div><div class="p">Active</div></div>
        </div>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
</section>
<?php endif; ?>

<section class="card wide" style="margin-top:14px">
  <div class="hd">
    <div class="title">Latest status changes</div>
    <form method="get" action="/" class="row" style="gap:10px; justify-content:flex-end">
      <input type="hidden" name="days" value="<?= (int)$days ?>" />
      <input class="input" type="text" name="q" value="<?= h($q) ?>" placeholder="Search lead/customer/email/phone/tracking" style="min-width:260px" />
      <select class="select" name="lsc_country" style="max-width:190px">
        <option value="">All countries</option>
        <?php foreach($countriesEnabled as $c): ?>
          <option value="<?= h($c['code']) ?>" <?= strtoupper($lscCountry)===strtoupper($c['code'])?'selected':'' ?>><?= h($c['name']) ?></option>
        <?php endforeach; ?>
      </select>
      <select class="select" name="lsc_status" style="max-width:190px">
        <option value="">All statuses</option>
        <?php foreach(['created','confirmed','delivered','returned','rejected','in_delivery','incident','out_of_area','no_data','no_match'] as $st): ?>
          <option value="<?= h($st) ?>" <?= $lscStatus===$st?'selected':'' ?>><?= h($st) ?></option>
        <?php endforeach; ?>
      </select>
      <button class="btn btn-ghost" type="submit">Filter</button>
      <?php if($lscCountry!=='' || $lscStatus!=='' || $q!==''): ?>
        <a class="btn btn-ghost" href="/?days=<?= (int)$days ?>">Reset</a>
      <?php endif; ?>
    </form>
  </div>

  <div class="bd" style="padding-top:0">
  <div class="table-wrap">
    <table class="table">
      <thead>
        <tr>
          <th>Lead</th><th>Country</th><th>Customer</th><th>Mail</th><th>Phone</th>
          <th>Status</th><th>When</th><th>Tracking</th><th class="right">Cards</th>
        </tr>
      </thead>
      <tbody>
      <?php foreach($latest as $r):
        $trackingLabel = trim(strip_tracking_date_suffix((string)($r['tracking_number'] ?? '')));
        $courierLabel = trim((string)($r['courier_code'] ?? ''));
        if (strcasecmp($trackingLabel, 'PICKPACK') === 0 || tracking_value_is_label_url($trackingLabel) || ($trackingLabel !== '' && $trackingLabel === trim((string)($r['order_id_remote'] ?? '')))) $trackingLabel = '';
        if ($courierLabel !== '') $courierLabel = normalize_courier_code($courierLabel) ?? $courierLabel;
        if (strcasecmp($courierLabel, 'PICKPACK') === 0) $courierLabel = '';
        $detailsRaw = [];
        if (!empty($r['details_json'])) {
          $detailsRaw = json_decode((string)$r['details_json'], true);
          if (!is_array($detailsRaw)) $detailsRaw = [];
        }
        if ($trackingLabel === '' && $detailsRaw) $trackingLabel = pickpack_extract_tracking_number($detailsRaw);
        if ($courierLabel === '' && $detailsRaw) {
          $carrierRaw = pickpack_extract_carrier($detailsRaw);
          if ($carrierRaw !== '') $courierLabel = normalize_courier_code($carrierRaw) ?? $carrierRaw;
        }
        $url = $trackingLabel !== '' ? build_tracking_url($courierLabel, $trackingLabel, $r['country']) : null;
      ?>
        <tr>
          <td><a class="lead-link" href="/lead.php?lead=<?= urlencode($r['lead_number']) ?>"><?= h($r['lead_number']) ?></a></td>
          <td><?= h($r['country']) ?></td>
          <td><?= h($r['customer_name']) ?></td>
          <td><?= h($r['email']) ?></td>
          <td><?= h($r['phone']) ?></td>
          <td><span class="badge"><?= h($r['status_norm']) ?></span></td>
          <td><?= h(dd($r['status_at'])) ?></td>
          <td>
            <?php if($url): ?>
              <a class="track-link" href="<?= h($url) ?>" target="_blank" rel="noopener">
                <div class="t-top"><?= h($trackingLabel) ?></div>
                <?php if($courierLabel !== ''): ?><div class="t-sub muted"><?= h($courierLabel) ?></div><?php endif; ?>
              </a>
            <?php else: ?>
              <div class="t-top"><?= h($trackingLabel !== '' ? $trackingLabel : 'Pending') ?></div>
              <?php if($courierLabel !== ''): ?><div class="t-sub muted"><?= h($courierLabel) ?></div><?php endif; ?>
            <?php endif; ?>
          </td>
          <td class="right"><strong><?= (int)($r['qty_cards'] ?? 0) ?></strong></td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>
</section>


<?php require_once __DIR__ . '/_inc/layout_bottom.php'; ?>
