<?php session_start(); require __DIR__ . '/../config.php'; if(!isset($_SESSION['admin_id'])) header('Location: login.php'); $pdo=get_pdo(); if(isset($_GET['export_campaign']) && intval($_GET['export_campaign'])){ $cid=intval($_GET['export_campaign']); $stmt=$pdo->prepare('SELECT cl.*, lc.email, lc.name FROM campaign_logs cl LEFT JOIN list_contacts lc ON lc.id=cl.contact_id WHERE cl.campaign_id=?'); $stmt->execute([$cid]); $rows=$stmt->fetchAll(); header('Content-Type:text/csv'); header('Content-Disposition: attachment; filename="campaign_'.$cid.'_logs.csv"'); $out=fopen('php://output','w'); fputcsv($out,['contact_id','email','name','status','opened','unsubscribed','created_at']); foreach($rows as $r) fputcsv($out,[$r['contact_id'],$r['email'],$r['name'],$r['status'],$r['opened'],$r['unsubscribed'],$r['created_at']]); fclose($out); exit;} $campaigns=$pdo->query('SELECT * FROM campaigns ORDER BY created_at DESC')->fetchAll(); ?><!doctype html><html><head><meta charset='utf-8'><title>Reports</title><link rel='stylesheet' href='/assets/css/style.css'></head><body><nav class='top'><a href='dashboard.php'>Dashboard</a></nav><div class='container'><h1>Reports</h1><?php foreach($campaigns as $c){ $stats=$pdo->prepare('SELECT COUNT(*) as total, SUM(opened) as opens, SUM(unsubscribed) as unsub FROM campaign_logs WHERE campaign_id=?'); $stats->execute([$c['id']]); $s=$stats->fetch(); echo "<div style='border:1px solid #eee;padding:10px;margin-bottom:8px;'><h3>".htmlspecialchars($c['name'])."</h3>Sent: " . ($c['sent']?:0) . " | Opened: " . ($s['opens']?:0) . " | Unsubscribes: " . ($s['unsub']?:0) . "<br><a class='btn' href='reports.php?export_campaign=".$c['id']."'>Export CSV</a></div>"; } ?></div></body></html>