<?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 Performance'; ?></title>
    <link rel="stylesheet" href="css/admin.css">
</head>
<body>
<div class="container">
<?php
$affId = $_GET['id'] ?? 0;
if (!$affId) die("Missing affiliate ID");

$start = $_GET['start'] ?? date('Y-m-01');
$end = $_GET['end'] ?? date('Y-m-d');

// Offer-level performance
$stmt = $pdo->prepare("SELECT o.offer_id, o.offer_name,
    COUNT(c.id) as conversions,
    SUM(c.payout) as revenue,
    (SELECT COUNT(*) FROM partners_clicks WHERE offer_id = o.offer_id AND affiliate_id = ? AND click_time BETWEEN ? AND ?) as clicks
    FROM partners_conversions c
    JOIN partners_offers o ON c.offer_id = o.offer_id
    WHERE c.affiliate_id = ? AND c.conversion_time BETWEEN ? AND ?
    GROUP BY o.offer_id ORDER BY revenue DESC");
$stmt->execute([$affId, $start, $end, $affId, $start, $end]);
$stats = $stmt->fetchAll(PDO::FETCH_ASSOC);

// UI
echo "<h2>📊 Performance for Affiliate #" . htmlspecialchars($affId) . "</h2>
<form method='get'>
    <input type='hidden' name='id' value='" . htmlspecialchars($affId) . "'>
    <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'>Refresh</button>
</form>";

echo "<table><tr>
    <th>Offer</th><th>Clicks</th><th>Conversions</th><th>Revenue</th><th>CR (%)</th><th>EPC</th>
</tr>";
foreach ($stats as $s) {
    $cr = $s['clicks'] ? round(($s['conversions'] / $s['clicks']) * 100, 2) : 0;
    $epc = $s['clicks'] ? round($s['revenue'] / $s['clicks'], 4) : 0;
    echo "<tr>
        <td>" . htmlspecialchars($s['offer_name']) . " (#" . htmlspecialchars($s['offer_id']) . ")</td>
        <td>{$s['clicks']}</td>
        <td>{$s['conversions']}</td>
        <td>$" . number_format($s['revenue'], 2) . "</td>
        <td>$cr</td>
        <td>$epc</td>
    </tr>";
}
echo "</table>";
?>
</div>
</body>
</html>