<?php
require_once '../includes/constants.php';
require_once '../includes/session.php';

if (!isset($_SESSION['admin_id']) || !in_array($_SESSION['admin_role'], ['manager','superadmin'])) {
    die("Access denied");
}
?>
<!DOCTYPE html>
<html>
<head>
    <title><?php echo SITE_TITLE . ' | Geo Reports'; ?></title>
    <link rel="stylesheet" href="css/admin.css">
</head>
<body>
<div class="container">
<?php
$start = $_GET['start'] ?? date('Y-m-01');
$end = $_GET['end'] ?? date('Y-m-d');

// Fetch data
$stmt = $pdo->prepare("
    SELECT geo_country, device_type, traffic_type,
           COUNT(*) AS conversions,
           SUM(payout) AS total_payout
    FROM conversions
    WHERE created_at BETWEEN ? AND ?
    GROUP BY geo_country, device_type, traffic_type
    ORDER BY total_payout DESC
");
$stmt->execute([$start, $end]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Export CSV
if (isset($_GET['export'])) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename=geo_report.csv');
    echo "Country,Device,Traffic,Conversions,Payout\n";
    foreach ($rows as $r) {
        echo "\"{$r['geo_country']}\",\"{$r['device_type']}\",\"{$r['traffic_type']}\",\"{$r['conversions']}\",\"{$r['total_payout']}\"\n";
    }
    exit;
}

// UI
echo "<h2>🌍 Geo Reports</h2>
<form method='get'>
    <label>Start: <input type='date' name='start' value='" . htmlspecialchars($start) . "'></label>
    <label>End: <input type='date' name='end' value='" . htmlspecialchars($end) . "'></label>
    <button type='submit'>Filter</button>
    <button onclick=\"window.location='?start=$start&end=$end&export=1';return false;\">Export CSV</button>
</form>";

echo "<table><tr>
    <th>Country</th><th>Device</th><th>Traffic</th><th>Conversions</th><th>Payout</th>
</tr>";

$totalConversions = 0;
$totalPayout = 0;

foreach ($rows as $r) {
    $totalConversions += $r['conversions'];
    $totalPayout += $r['total_payout'];
    echo "<tr>
        <td>" . htmlspecialchars($r['geo_country']) . "</td>
        <td>" . htmlspecialchars($r['device_type']) . "</td>
        <td>" . htmlspecialchars($r['traffic_type']) . "</td>
        <td>{$r['conversions']}</td>
        <td>$" . number_format($r['total_payout'], 2) . "</td>
    </tr>";
}

echo "<tr><td colspan='3'><strong>Totals</strong></td>
      <td><strong>$totalConversions</strong></td>
      <td><strong>$" . number_format($totalPayout, 2) . "</strong></td></tr>";
echo "</table>";
?>
</div>
</body>
</html>