<?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 . ' | Affiliate Dashboard'; ?></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 affiliates
$stmt = $pdo->query("SELECT id, username FROM users ORDER BY username");
$affiliates = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Export CSV
if (isset($_GET['export'])) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename=affiliate_dashboard.csv');
    echo "Affiliate,Clicks,Conversions,Revenue,Pending Payouts\n";
    foreach ($affiliates as $a) {
        $affId = $a['id'];
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM partners_clicks WHERE affiliate_id = ? AND click_time BETWEEN ? AND ?");
        $stmt->execute([$affId, $start, $end]);
        $clicks = $stmt->fetchColumn();

        $stmt = $pdo->prepare("SELECT COUNT(*) as convs, SUM(payout) as revenue FROM partners_conversions WHERE affiliate_id = ? AND conversion_time BETWEEN ? AND ?");
        $stmt->execute([$affId, $start, $end]);
        $conv = $stmt->fetch(PDO::FETCH_ASSOC);

        $stmt = $pdo->prepare("SELECT SUM(amount) FROM affiliate_payments WHERE affiliate_id = ? AND status = 'pending'");
        $stmt->execute([$affId]);
        $pending = $stmt->fetchColumn();

        echo "\"{$a['username']}\",\"$clicks\",\"{$conv['convs']}\",\"{$conv['revenue']}\",\"$pending\"\n";
    }
    exit;
}

// UI
echo "<h2>📂 Affiliate Dashboard</h2>
<form method='get'>
    <label>Start: <input type='date' name='start' value='$start'></label>
    <label>End: <input type='date' name='end' value='$end'></label>
    <button type='submit'>Refresh</button>
    <button onclick=\"window.location='?start=$start&end=$end&export=1';return false;\">Export CSV</button>
</form>";

echo "<table><tr>
    <th>Affiliate</th><th>Clicks</th><th>Conversions</th><th>Revenue</th><th>Pending Payouts</th>
</tr>";

$totalClicks = 0;
$totalConversions = 0;
$totalRevenue = 0;
$totalPending = 0;

foreach ($affiliates as $a) {
    $affId = $a['id'];

    $stmt = $pdo->prepare("SELECT COUNT(*) FROM partners_clicks WHERE affiliate_id = ? AND click_time BETWEEN ? AND ?");
    $stmt->execute([$affId, $start, $end]);
    $clicks = $stmt->fetchColumn();

    $stmt = $pdo->prepare("SELECT COUNT(*) as convs, SUM(payout) as revenue FROM partners_conversions WHERE affiliate_id = ? AND conversion_time BETWEEN ? AND ?");
    $stmt->execute([$affId, $start, $end]);
    $conv = $stmt->fetch(PDO::FETCH_ASSOC);

    $stmt = $pdo->prepare("SELECT SUM(amount) FROM affiliate_payments WHERE affiliate_id = ? AND status = 'pending'");
    $stmt->execute([$affId]);
    $pending = $stmt->fetchColumn();

    $totalClicks += $clicks;
    $totalConversions += $conv['convs'];
    $totalRevenue += $conv['revenue'];
    $totalPending += $pending;

    echo "<tr>
        <td>" . htmlspecialchars($a['username']) . " (#$affId)</td>
        <td>$clicks</td>
        <td>{$conv['convs']}</td>
        <td>$" . number_format($conv['revenue'], 2) . "</td>
        <td>$" . number_format($pending, 2) . "</td>
    </tr>";
}

echo "<tr><td><strong>Totals</strong></td>
      <td><strong>$totalClicks</strong></td>
      <td><strong>$totalConversions</strong></td>
      <td><strong>$" . number_format($totalRevenue, 2) . "</strong></td>
      <td><strong>$" . number_format($totalPending, 2) . "</strong></td></tr>";
echo "</table>";
?>
</div>
</body>
</html>