<?php
require_once __DIR__.'/../app/bootstrap.php';
$user=require_login($pdo);
function stat_ids_from_query(): 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();
$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);
}
while (ob_get_level() > 0) { ob_end_clean(); }
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="qr-statistik-'.date('Y-m-d').'.csv"');
header('Pragma: no-cache');
header('Expires: 0');
$out=fopen('php://output','w');
fwrite($out, "\xEF\xBB\xBF");
fputcsv($out,['Titel','Gruppe','Kurzcode','Kurz-URL','Ziel-URL','UTM Source','UTM Medium','UTM Campaign','Scans total','Letzter Scan','Erstellt am'],';');
$stmt=$pdo->prepare('SELECT q.title,q.code,q.target_url,q.utm_source,q.utm_medium,q.utm_campaign,q.scan_count,q.last_scan_at,q.created_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.created_at DESC');
$stmt->execute($params);
while($r=$stmt->fetch()){
    fputcsv($out,[$r['title'],$r['group_name'] ?? '',$r['code'],base_url($config).'/q/'.$r['code'],$r['target_url'],$r['utm_source'],$r['utm_medium'],$r['utm_campaign'],(int)$r['scan_count'],$r['last_scan_at'],$r['created_at']],';');
}
fclose($out);
exit;
