<?php
include('../config/db.php');
include('../includes/auth.php');
require_admin_role();

$today = date('Y-m-d');
$tab   = $_GET['tab'] ?? 'overview';

// ── Helpers ────────────────────────────────────────────────────────────────
function qval($conn, string $sql, string $types = '', array $params = []): int {
    if ($types === '') {
        $r = $conn->query($sql);
        return $r ? (int)$r->fetch_assoc()['c'] : 0;
    }
    $st = $conn->prepare($sql);
    $st->bind_param($types, ...$params);
    $st->execute();
    $c = (int)$st->get_result()->fetch_assoc()['c'];
    $st->close();
    return $c;
}


function timeAgo($ts) {
    if (!$ts) return '—';
    $diff = time() - strtotime($ts);
    if ($diff < 60)    return $diff.'s ago';
    if ($diff < 3600)  return floor($diff/60).'m ago';
    if ($diff < 86400) return floor($diff/3600).'h ago';
    return date('d M Y, H:i', strtotime($ts));
}
function fmtDate($ts) {
    return $ts ? date('d M Y, H:i', strtotime($ts)) : '—';
}
function pgLinks($cur, $total, $base) {
    if ($total <= 1) return '';
    $out = '';
    $show = [];
    foreach([1,$total] as $p) $show[$p]=true;
    for($p=max(1,$cur-2);$p<=min($total,$cur+2);$p++) $show[$p]=true;
    ksort($show); $prev=0;
    $out .= $cur>1 ? "<a href='{$base}".($cur-1)."' class='pg-num'><i class='bi bi-chevron-left'></i></a>" : "<span class='pg-num disabled'><i class='bi bi-chevron-left'></i></span>";
    foreach(array_keys($show) as $p) {
        if($prev && $p-$prev>1) $out .= "<span class='pg-ellipsis'>…</span>";
        $cls = $p===$cur ? 'pg-num active' : 'pg-num';
        $out .= "<a href='{$base}{$p}' class='{$cls}'>{$p}</a>";
        $prev=$p;
    }
    $out .= $cur<$total ? "<a href='{$base}".($cur+1)."' class='pg-num'><i class='bi bi-chevron-right'></i></a>" : "<span class='pg-num disabled'><i class='bi bi-chevron-right'></i></span>";
    return $out;
}

// ── Data queries (run before any output) ───────────────────────────────────
// ── Overview Stats ────────────────────────────────────────────────────────────
$sTotalClaims   = qval($conn, 'SELECT COUNT(*) c FROM voucher_claims');
$sRedeemed      = qval($conn, "SELECT COUNT(*) c FROM voucher_claims WHERE status='redeemed'");
$sPending       = $sTotalClaims - $sRedeemed;
$sRate          = $sTotalClaims > 0 ? round($sRedeemed / $sTotalClaims * 100) : 0;
$sCustomers     = qval($conn, 'SELECT COUNT(*) c FROM customers');
$sVouchers      = qval($conn, 'SELECT COUNT(*) c FROM vouchers WHERE parent_voucher_id IS NULL');
$sActiveVouchers= qval($conn, 'SELECT COUNT(*) c FROM vouchers WHERE parent_voucher_id IS NULL AND start_date <= ? AND end_date >= ?', 'ss', [$today, $today]);
$sTodayClaims   = qval($conn, 'SELECT COUNT(*) c FROM voucher_claims WHERE DATE(claimed_at)=?', 's', [$today]);
$sTodayRedeem   = qval($conn, 'SELECT COUNT(*) c FROM voucher_claims WHERE DATE(redeemed_at)=?', 's', [$today]);

// ── 30-day daily series ───────────────────────────────────────────────────────
$daily = [];
for ($i = 29; $i >= 0; $i--) {
    $d = date('Y-m-d', strtotime("-$i days"));
    $daily[] = [
        'date'     => $d,
        'label'    => date('d M', strtotime($d)),
        'claims'   => qval($conn, 'SELECT COUNT(*) c FROM voucher_claims WHERE DATE(claimed_at)=?', 's', [$d]),
        'redeemed' => qval($conn, 'SELECT COUNT(*) c FROM voucher_claims WHERE DATE(redeemed_at)=?', 's', [$d]),
    ];
}

// ── Voucher performance ───────────────────────────────────────────────────────
$vPerfStmt = $conn->prepare("
    SELECT v.id, v.event_name, v.type, v.code, v.start_date, v.end_date,
           v.max_per_user, v.is_public,
           COUNT(vc.id)               AS total_claims,
           SUM(vc.status='redeemed')  AS redeemed,
           SUM(vc.status='claimed')   AS pending,
           COUNT(DISTINCT vc.customer_id) AS unique_users
    FROM vouchers v
    LEFT JOIN vouchers cv ON (cv.id = v.id OR cv.parent_voucher_id = v.id)
    LEFT JOIN voucher_claims vc ON vc.voucher_id = cv.id
    WHERE v.parent_voucher_id IS NULL
    GROUP BY v.id
    ORDER BY total_claims DESC
");
$vPerfRows = [];
if ($vPerfStmt) {
    $vPerfStmt->execute();
    $vPerfResult = $vPerfStmt->get_result();
    while ($r = $vPerfResult->fetch_assoc()) $vPerfRows[] = $r;
    $vPerfStmt->close();
}

// ── Redeem log (paginated) ────────────────────────────────────────────────────
$rPage  = max(1,(int)($_GET['rp']??1)); $rLimit = 20;
$rSearch= trim($_GET['rs']??'');
// BUG FIX: counts also need prepared statements
if ($rSearch !== '') {
    $rLike = '%' . $rSearch . '%';
    $rCntStmt = $conn->prepare("SELECT COUNT(*) c FROM voucher_claims vc JOIN customers c ON vc.customer_id=c.id JOIN vouchers v ON vc.voucher_id=v.id WHERE vc.status='redeemed' AND (c.name LIKE ? OR c.phone LIKE ? OR v.event_name LIKE ? OR v.code LIKE ?)");
    $rCntStmt->bind_param('ssss', $rLike, $rLike, $rLike, $rLike);
} else {
    $rCntStmt = $conn->prepare("SELECT COUNT(*) c FROM voucher_claims WHERE status='redeemed'");
}
$rCntStmt->execute();
$rTotal = (int)$rCntStmt->get_result()->fetch_assoc()['c'];
$rPages = max(1,(int)ceil($rTotal/$rLimit));
$rPage  = min($rPage,$rPages);
$rOff   = ($rPage-1)*$rLimit;
$rSearch= trim($_GET['rs']??'');
// BUG FIX: was using addslashes() string interpolation — converted to prepared statement
if ($rSearch !== '') {
    $rLike = '%' . $rSearch . '%';
    $rStmt = $conn->prepare("
        SELECT vc.id, c.name, c.phone, v.event_name, v.type, v.code,
               vc.claimed_at, vc.redeemed_at
        FROM voucher_claims vc
        JOIN customers c ON vc.customer_id = c.id
        JOIN vouchers  v ON vc.voucher_id  = v.id
        WHERE vc.status='redeemed'
          AND (c.name LIKE ? OR c.phone LIKE ? OR v.event_name LIKE ? OR v.code LIKE ?)
        ORDER BY vc.redeemed_at DESC
        LIMIT $rLimit OFFSET $rOff
    ");
    $rStmt->bind_param('ssss', $rLike, $rLike, $rLike, $rLike);
} else {
    $rStmt = $conn->prepare("
        SELECT vc.id, c.name, c.phone, v.event_name, v.type, v.code,
               vc.claimed_at, vc.redeemed_at
        FROM voucher_claims vc
        JOIN customers c ON vc.customer_id = c.id
        JOIN vouchers  v ON vc.voucher_id  = v.id
        WHERE vc.status='redeemed'
        ORDER BY vc.redeemed_at DESC
        LIMIT $rLimit OFFSET $rOff
    ");
}
$redeemRows = [];
if ($rStmt) {
    $rStmt->execute();
    $redeemLog = $rStmt->get_result();
    while ($r = $redeemLog->fetch_assoc()) $redeemRows[] = $r;
    $rStmt->close();
}

// ── Claim log (paginated) ─────────────────────────────────────────────────────
$cPage  = max(1,(int)($_GET['cp']??1)); $cLimit = 20;
$cTotal = qval($conn, "SELECT COUNT(*) c FROM voucher_claims");
$cPages = max(1,(int)ceil($cTotal/$cLimit));
$cPage  = min($cPage,$cPages);
$cOff   = ($cPage-1)*$cLimit;
$cSearch= trim($_GET['cs']??'');
// BUG FIX: was using addslashes() — converted to prepared statement
if ($cSearch !== '') {
    $cLike = '%' . $cSearch . '%';
    $cStmt = $conn->prepare("
        SELECT vc.id, c.name, c.phone, v.event_name, v.type, v.code,
               vc.status, vc.claimed_at, vc.redeemed_at
        FROM voucher_claims vc
        JOIN customers c ON vc.customer_id = c.id
        JOIN vouchers  v ON vc.voucher_id  = v.id
        WHERE (c.name LIKE ? OR c.phone LIKE ? OR v.event_name LIKE ?)
        ORDER BY vc.id DESC
        LIMIT $cLimit OFFSET $cOff
    ");
    $cStmt->bind_param('sss', $cLike, $cLike, $cLike);
} else {
    $cStmt = $conn->prepare("
        SELECT vc.id, c.name, c.phone, v.event_name, v.type, v.code,
               vc.status, vc.claimed_at, vc.redeemed_at
        FROM voucher_claims vc
        JOIN customers c ON vc.customer_id = c.id
        JOIN vouchers  v ON vc.voucher_id  = v.id
        ORDER BY vc.id DESC
        LIMIT $cLimit OFFSET $cOff
    ");
}
$claimRows = [];
if ($cStmt) {
    $cStmt->execute();
    $claimLog = $cStmt->get_result();
    while ($r = $claimLog->fetch_assoc()) $claimRows[] = $r;
    $cStmt->close();
}

// ── Voucher log ───────────────────────────────────────────────────────────────
$vPage  = max(1,(int)($_GET['vp']??1)); $vLimit = 20;
$vSearch= trim($_GET['vs']??'');
if ($vSearch !== '') {
    $vLike = '%' . $vSearch . '%';
    $vCntStmt = $conn->prepare("SELECT COUNT(*) c FROM vouchers WHERE parent_voucher_id IS NULL AND (event_name LIKE ? OR code LIKE ? OR type LIKE ?)");
    $vCntStmt->bind_param('sss', $vLike, $vLike, $vLike);
    $vCntStmt->execute();
    $vTotal = (int)$vCntStmt->get_result()->fetch_assoc()['c'];
    $vCntStmt->close();
} else {
    $vTotal = qval($conn, "SELECT COUNT(*) c FROM vouchers WHERE parent_voucher_id IS NULL");
}
$vPages = max(1,(int)ceil($vTotal/$vLimit));
$vPage  = min($vPage,$vPages);
$vOff   = ($vPage-1)*$vLimit;
// BUG FIX: was using addslashes() — converted to prepared statement
if ($vSearch !== '') {
    $vLike = '%' . $vSearch . '%';
    $vStmt = $conn->prepare("
        SELECT v.id, v.code, v.event_name, v.type, v.start_date, v.end_date,
               v.is_public, v.max_per_user, v.created_at,
               COUNT(vc.id)               AS total_claims,
               SUM(vc.status='redeemed')  AS redeemed,
               COUNT(DISTINCT vc.customer_id) AS unique_users
        FROM vouchers v
        LEFT JOIN vouchers cv ON (cv.id = v.id OR cv.parent_voucher_id = v.id)
        LEFT JOIN voucher_claims vc ON vc.voucher_id = cv.id
        WHERE v.parent_voucher_id IS NULL
          AND (v.event_name LIKE ? OR v.code LIKE ? OR v.type LIKE ?)
        GROUP BY v.id
        ORDER BY v.id DESC
        LIMIT $vLimit OFFSET $vOff
    ");
    $vStmt->bind_param('sss', $vLike, $vLike, $vLike);
} else {
    $vStmt = $conn->prepare("
        SELECT v.id, v.code, v.event_name, v.type, v.start_date, v.end_date,
               v.is_public, v.max_per_user, v.created_at,
               COUNT(vc.id)               AS total_claims,
               SUM(vc.status='redeemed')  AS redeemed,
               COUNT(DISTINCT vc.customer_id) AS unique_users
        FROM vouchers v
        LEFT JOIN vouchers cv ON (cv.id = v.id OR cv.parent_voucher_id = v.id)
        LEFT JOIN voucher_claims vc ON vc.voucher_id = cv.id
        WHERE v.parent_voucher_id IS NULL
        GROUP BY v.id
        ORDER BY v.id DESC
        LIMIT $vLimit OFFSET $vOff
    ");
}
$voucherRows = [];
if ($vStmt) {
    $vStmt->execute();
    $voucherLog = $vStmt->get_result();
    while ($r = $voucherLog->fetch_assoc()) $voucherRows[] = $r;
    $vStmt->close();
}

include('partials/header.php');
?>

<style>
/* ── Tab nav ── */
.ana-tabs{display:flex;gap:2px;background:var(--surface2);border:1px solid var(--border);border-radius:10px;padding:4px;margin-bottom:24px;overflow-x:auto;scrollbar-width:none}
.ana-tabs::-webkit-scrollbar{display:none}
.ana-tab{flex-shrink:0;display:flex;align-items:center;gap:7px;padding:9px 18px;border-radius:7px;font-size:13px;font-weight:600;color:var(--muted);cursor:pointer;text-decoration:none;transition:all .15s;white-space:nowrap;border:none;background:none;font-family:var(--font)}
.ana-tab i{font-size:15px}
.ana-tab:hover{color:var(--text);background:var(--surface)}
.ana-tab.active{background:var(--surface);color:var(--text);box-shadow:0 1px 4px rgba(0,0,0,.25)}
.ana-tab.active i{color:var(--accent)}

/* ── KPI cards ── */
.kpi-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:24px}
@media(max-width:767px){.kpi-grid{grid-template-columns:repeat(2,1fr)}}
.kpi{background:var(--surface);border:1px solid var(--border);border-radius:10px;padding:18px 20px;transition:border-color .2s}
.kpi:hover{border-color:rgba(232,160,32,.3)}
.kpi-top{display:flex;align-items:center;justify-content:space-between;margin-bottom:12px}
.kpi-icon{width:36px;height:36px;border-radius:8px;display:grid;place-items:center;font-size:17px;flex-shrink:0}
.kpi-val{font-family:var(--mono);font-size:28px;font-weight:700;line-height:1;margin-bottom:4px}
.kpi-lbl{font-size:11px;font-weight:700;letter-spacing:.9px;text-transform:uppercase;color:var(--muted)}
.kpi-sub{font-size:11.5px;color:var(--muted);margin-top:5px}

/* ── Section header ── */
.sec-hd{display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;flex-wrap:wrap;gap:10px}
.sec-hd-title{font-size:15px;font-weight:700;display:flex;align-items:center;gap:8px}
.sec-hd-title i{color:var(--accent)}

/* ── Performance bars ── */
.perf-bar-wrap{display:flex;flex-direction:column;gap:12px}
.perf-item{background:var(--surface2);border:1px solid var(--border);border-radius:8px;padding:14px 16px}
.perf-meta{display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:10px;gap:8px}
.perf-name{font-size:13px;font-weight:600}
.perf-type{font-size:11px;color:var(--muted);margin-top:2px}
.perf-nums{display:flex;gap:14px;flex-shrink:0;text-align:right}
.perf-num{font-family:var(--mono);font-size:16px;font-weight:700}
.perf-num-lbl{font-size:10px;color:var(--muted)}
.perf-track{height:6px;background:var(--bg);border-radius:3px;overflow:hidden;margin-bottom:8px}
.perf-fill{height:100%;border-radius:3px;transition:width .4s ease}
.perf-chips{display:flex;gap:8px;flex-wrap:wrap}
.chip{display:inline-flex;align-items:center;gap:4px;font-size:10.5px;font-weight:600;padding:3px 9px;border-radius:20px}
.chip-green{background:rgba(45,189,135,.1);color:#2dbd87;border:1px solid rgba(45,189,135,.2)}
.chip-yellow{background:rgba(245,197,24,.1);color:#f5c518;border:1px solid rgba(245,197,24,.2)}
.chip-blue{background:rgba(75,158,255,.1);color:#4b9eff;border:1px solid rgba(75,158,255,.2)}
.chip-red{background:rgba(224,82,82,.1);color:#e05252;border:1px solid rgba(224,82,82,.2)}
.chip-muted{background:rgba(107,115,148,.1);color:#6b7394;border:1px solid rgba(107,115,148,.2)}

/* ── Log table enhancements ── */
.log-search{display:flex;gap:8px;margin-bottom:14px}
.log-search input{flex:1}
.log-empty{padding:48px;text-align:center;color:var(--muted)}
.log-empty i{font-size:36px;display:block;margin-bottom:10px;opacity:.3}
.log-empty p{font-size:13px;margin:0}

/* ── Export btn ── */
.btn-export{display:inline-flex;align-items:center;gap:6px;padding:7px 14px;border-radius:8px;font-size:12px;font-weight:600;color:var(--muted);border:1px solid var(--border);background:transparent;cursor:pointer;transition:all .15s;text-decoration:none;font-family:var(--font)}
.btn-export:hover{border-color:var(--text);color:var(--text)}

/* ── Mini trend badge ── */
.trend{display:inline-flex;align-items:center;gap:3px;font-size:11px;font-weight:700;padding:2px 7px;border-radius:20px}
.trend-up{background:rgba(45,189,135,.12);color:#2dbd87}
.trend-dn{background:rgba(224,82,82,.12);color:#e05252}
.trend-nt{background:rgba(107,115,148,.12);color:#6b7394}

/* ── Summary row under chart ── */
.chart-summary{display:flex;gap:20px;flex-wrap:wrap;margin-top:14px;padding-top:14px;border-top:1px solid var(--border)}
.chart-summary-item{display:flex;align-items:center;gap:8px;font-size:13px}
.dot{width:10px;height:10px;border-radius:50%;flex-shrink:0}

/* ── Voucher status pills ── */
.vs-active  {background:rgba(45,189,135,.1);color:#2dbd87;border:1px solid rgba(45,189,135,.25)}
.vs-expired {background:rgba(224,82,82,.1);color:#e05252;border:1px solid rgba(224,82,82,.25)}
.vs-upcoming{background:rgba(75,158,255,.1);color:#4b9eff;border:1px solid rgba(75,158,255,.25)}
.vs-pill{display:inline-flex;align-items:center;gap:4px;font-size:10.5px;font-weight:700;padding:3px 9px;border-radius:20px}
</style>


<div class="pg-title">Analytics</div>
<div class="pg-sub">Reports, logs &amp; audit trail — <?= date('d F Y') ?></div>

<!-- ── Tab Navigation ── -->
<nav class="ana-tabs">
  <a href="?tab=overview" class="ana-tab <?= $tab==='overview'?'active':'' ?>">
    <i class="bi bi-graph-up-arrow"></i>Overview
  </a>
  <a href="?tab=redeem" class="ana-tab <?= $tab==='redeem'?'active':'' ?>">
    <i class="bi bi-check2-circle"></i>Redeem Log
  </a>
  <a href="?tab=claims" class="ana-tab <?= $tab==='claims'?'active':'' ?>">
    <i class="bi bi-bookmark-fill"></i>Claim Log
  </a>
  <a href="?tab=vouchers" class="ana-tab <?= $tab==='vouchers'?'active':'' ?>">
    <i class="bi bi-ticket-perforated-fill"></i>Voucher Log
  </a>
</nav>

<!-- ══════════════════════════════════════════════════════════════════════ -->
<?php include 'partials/claims/_tab_overview.php'; ?>
<?php include 'partials/claims/_tab_redeem.php'; ?>
<?php include 'partials/claims/_tab_claims.php'; ?>
<?php include 'partials/claims/_tab_vouchers.php'; ?>

<?php include('partials/footer.php'); ?>
