<?php
require_once __DIR__.'/../app/bootstrap.php';
require_once __DIR__.'/_layout.php';
$user=require_login($pdo);
csrf_check();
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reset_qr_id'])) {
    require_post();
    $resetId = (int)$_POST['reset_qr_id'];
    $check = $pdo->prepare('SELECT q.id FROM '.qtbl('qr_codes').' q WHERE q.id=? AND '.qr_edit_where('q').' LIMIT 1');
    $check->execute([$resetId,$user['id'],$user['id']]);
    if ($check->fetchColumn()) {
        $pdo->prepare('DELETE FROM '.qtbl('qr_scans').' WHERE qr_code_id=?')->execute([$resetId]);
        $pdo->prepare('UPDATE '.qtbl('qr_codes').' SET scan_count=0,last_scan_at=NULL WHERE id=?')->execute([$resetId]);
        header('Location: statistics.php?reset=1'); exit;
    }
}
$where=qr_access_where('q');
$stmt=$pdo->prepare('SELECT q.id,q.title,q.code,q.target_url,q.scan_count,q.last_scan_at,g.name AS group_name,COUNT(s.id) AS detailed_scans,MAX(s.scanned_at) AS last_detailed_scan FROM '.qtbl('qr_codes').' q LEFT JOIN '.qtbl('qr_groups').' g ON g.id=q.group_id LEFT JOIN '.qtbl('qr_scans').' s ON s.qr_code_id=q.id WHERE '.$where.' GROUP BY q.id,g.name ORDER BY q.title ASC');
$stmt->execute([$user['id'],$user['id']]);
$allRows=$stmt->fetchAll();
$availableIds=array_map('intval', array_column($allRows,'id'));
$requested = array_map('intval', $_GET['ids'] ?? []);
$selectedIds = $requested ? array_values(array_intersect($availableIds, $requested)) : $availableIds;
$selectedSet = array_flip($selectedIds);
$daily=[]; $geo=[]; $utm=[];
if ($selectedIds) {
    $ph=implode(',', array_fill(0,count($selectedIds),'?'));
    $params=array_merge([$user['id'],$user['id']],$selectedIds);
    $dailyStmt=$pdo->prepare('SELECT DATE(s.scanned_at) AS day, COUNT(*) AS scans FROM '.qtbl('qr_scans').' s INNER JOIN '.qtbl('qr_codes').' q ON q.id=s.qr_code_id WHERE '.$where.' AND q.id IN ('.$ph.') GROUP BY DATE(s.scanned_at) ORDER BY day DESC LIMIT 30');
    $dailyStmt->execute($params); $daily=$dailyStmt->fetchAll();
    $geoStmt=$pdo->prepare('SELECT COALESCE(NULLIF(s.country_name,""), NULLIF(s.country_code,""), "Unbekannt") AS country, COUNT(*) AS scans FROM '.qtbl('qr_scans').' s INNER JOIN '.qtbl('qr_codes').' q ON q.id=s.qr_code_id WHERE '.$where.' AND q.id IN ('.$ph.') GROUP BY country ORDER BY scans DESC LIMIT 15');
    $geoStmt->execute($params); $geo=$geoStmt->fetchAll();
    $utmStmt=$pdo->prepare('SELECT COALESCE(NULLIF(q.utm_campaign,""), "Ohne Kampagne") AS campaign, COUNT(s.id) AS scans FROM '.qtbl('qr_codes').' q LEFT JOIN '.qtbl('qr_scans').' s ON s.qr_code_id=q.id WHERE '.$where.' AND q.id IN ('.$ph.') GROUP BY campaign ORDER BY scans DESC LIMIT 15');
    $utmStmt->execute($params); $utm=$utmStmt->fetchAll();
}
$query = ($selectedIds && count($selectedIds) !== count($availableIds)) ? '?'.http_build_query(['ids'=>$selectedIds]) : '';
$exportUrl='statistics-export.php'.$query; $reportUrl='statistics-report.php'.$query;
$chartDaily=array_reverse($daily);
page_header('Statistik'); if(isset($_GET['reset'])) echo '<p class="notice ok">Statistik wurde zurückgesetzt.</p>';
?>
<section class="card">
  <h2>QR-Codes</h2>
  <p class="muted">Standardmässig sind alle QR-Codes aktiv. Entferne die Auswahl und wähle einzelne Codes manuell aus.</p>
  <form id="stats-select-form" method="get">
    <div class="stats-actions">
      <a class="btn secondary" href="statistics.php">Alle aktivieren</a>
      <button class="btn secondary" type="button" data-uncheck-all="[data-stat-id]">Auswahl aufheben</button>
      <button class="btn" type="submit">Auswertung aktualisieren</button>
      <a class="btn secondary" href="<?= e($exportUrl) ?>">CSV exportieren</a>
      <a class="btn" href="<?= e($reportUrl) ?>">PDF-Report</a>
    </div>
    <table class="table stats-table"><thead><tr><th class="check-col"><input type="checkbox" data-check-all="[data-stat-id]" <?= count($selectedIds)===count($availableIds)?'checked':'' ?> aria-label="Alle QR-Codes auswählen"></th><th>Titel</th><th>Gruppe</th><th>Kurzcode</th><th>Scans total</th><th>Letzter Scan</th><th>Aktion</th></tr></thead><tbody>
    <?php foreach($allRows as $r): $isSelected=isset($selectedSet[(int)$r['id']]); ?>
      <tr class="<?= $isSelected ? '' : 'is-muted-row' ?>"><td class="check-col"><input data-stat-id type="checkbox" name="ids[]" value="<?= (int)$r['id'] ?>" <?= $isSelected?'checked':'' ?>></td><td><strong><?= e($r['title']) ?></strong><div class="muted"><?= e($r['target_url']) ?></div></td><td><?= e($r['group_name'] ?? '–') ?></td><td><?= e($r['code']) ?></td><td><?= $isSelected ? (int)$r['scan_count'] : '–' ?></td><td><?= $isSelected ? e($r['last_scan_at'] ?? $r['last_detailed_scan'] ?? '-') : '–' ?></td><td><?php if($isSelected): ?><form method="post" data-confirm="Statistik für diesen QR-Code wirklich auf 0 setzen?"><input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>"><input type="hidden" name="reset_qr_id" value="<?= (int)$r['id'] ?>"><button class="btn secondary small" type="submit">Reset</button></form><?php else: ?><span class="muted">–</span><?php endif; ?></td></tr>
    <?php endforeach; if(!$allRows): ?><tr><td colspan="7">Noch keine QR-Codes vorhanden.</td></tr><?php endif; ?>
    </tbody></table>
  </form>
</section>
<section class="card"><h2>Scans pro Tag</h2><div class="chart-bars" aria-label="Scans pro Tag"><?php $max=max(1,...array_map(fn($d)=>(int)$d['scans'],$chartDaily ?: [['scans'=>0]])); foreach($chartDaily as $d): $h=max(4,round(((int)$d['scans']/$max)*160)); ?><div class="chart-bar"><span data-height="<?= (int)$h ?>"></span><small><?= e(substr($d['day'],5)) ?></small><b><?= (int)$d['scans'] ?></b></div><?php endforeach; if(!$chartDaily): ?><p class="muted">Noch keine Scans für die aktuelle Auswahl erfasst.</p><?php endif; ?></div><table class="table compact"><thead><tr><th>Datum</th><th>Scans</th></tr></thead><tbody><?php foreach($daily as $d): ?><tr><td><?= e($d['day']) ?></td><td><?= (int)$d['scans'] ?></td></tr><?php endforeach; if(!$daily): ?><tr><td colspan="2">Noch keine Scans für die aktuelle Auswahl erfasst.</td></tr><?php endif; ?></tbody></table></section>
<section class="grid2 stats-grid"><div class="card"><h2>Geo-Auswertung</h2><p class="muted">Erfasst Länder über Cloudflare-Header oder optionalen Geo-Anbieter.</p><table class="table compact"><thead><tr><th>Land</th><th>Scans</th></tr></thead><tbody><?php foreach($geo as $g): ?><tr><td><?= e($g['country']) ?></td><td><?= (int)$g['scans'] ?></td></tr><?php endforeach; if(!$geo): ?><tr><td colspan="2">Noch keine Geo-Daten vorhanden.</td></tr><?php endif; ?></tbody></table></div><div class="card"><h2>UTM-Kampagnen</h2><table class="table compact"><thead><tr><th>Kampagne</th><th>Scans</th></tr></thead><tbody><?php foreach($utm as $u): ?><tr><td><?= e($u['campaign']) ?></td><td><?= (int)$u['scans'] ?></td></tr><?php endforeach; if(!$utm): ?><tr><td colspan="2">Noch keine UTM-Daten vorhanden.</td></tr><?php endif; ?></tbody></table></div></section>
<?php page_footer(); ?>
