<?php
require_once __DIR__.'/../app/bootstrap.php';
$user=require_login($pdo);
function stat_ids_from_query_report(): array {
    $raw = $_GET['ids'] ?? [];
    if (is_string($raw)) { $raw = [$raw]; }
    return array_values(array_filter(array_map('intval', is_array($raw) ? $raw : [])));
}
$ids = stat_ids_from_query_report();
$where = qr_access_where('q');
$params = [$user['id'],$user['id']];
if ($ids) { $where .= ' AND q.id IN ('.implode(',', array_fill(0,count($ids),'?')).')'; $params = array_merge($params,$ids); }
$lines=[];
$lines[]='Erstellt am: '.date('d.m.Y H:i');
$lines[]='';
$stmt=$pdo->prepare('SELECT q.title,q.code,q.target_url,q.scan_count,q.last_scan_at,g.name AS group_name FROM '.qtbl('qr_codes').' q LEFT JOIN '.qtbl('qr_groups').' g ON g.id=q.group_id WHERE '.$where.' ORDER BY q.title ASC');
$stmt->execute($params);
$lines[]='QR-Codes';
$rows=$stmt->fetchAll();
foreach($rows as $r){ $lines[]='- '.$r['title'].' | '.$r['code'].' | Scans: '.(int)$r['scan_count'].' | Gruppe: '.($r['group_name'] ?: '-'); }
if(!$rows){ $lines[]='- Keine QR-Codes in der aktuellen Auswahl.'; }
$lines[]='';
$daily=$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.' GROUP BY DATE(s.scanned_at) ORDER BY day DESC LIMIT 30');
$daily->execute($params);
$lines[]='Scans pro Tag';
foreach($daily->fetchAll() as $d){ $lines[]='- '.$d['day'].': '.(int)$d['scans']; }
$geo=$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.' GROUP BY country ORDER BY scans DESC LIMIT 15');
$geo->execute($params);
$lines[]=''; $lines[]='Geo-Auswertung';
foreach($geo->fetchAll() as $g){ $lines[]='- '.$g['country'].': '.(int)$g['scans']; }
$utm=$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.' GROUP BY campaign ORDER BY scans DESC LIMIT 15');
$utm->execute($params);
$lines[]=''; $lines[]='UTM-Kampagnen';
foreach($utm->fetchAll() as $u){ $lines[]='- '.$u['campaign'].': '.(int)$u['scans']; }
while (ob_get_level() > 0) { ob_end_clean(); }
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="kuhrator-report-'.date('Y-m-d').'.pdf"');
header('Pragma: no-cache');
header('Expires: 0');
echo simple_pdf_report('KuhRator Statistik-Report', $lines);
exit;
