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

if (!isset($_SESSION['admin_id']) || !in_array($_SESSION['admin_role'], ['manager','superadmin'])) {
    die("Access denied");
}

$offerId = $_GET['id'] ?? 0;
if (!$offerId) die("Missing offer ID");

$start = $_GET['start'] ?? date('Y-m-d', strtotime('-7 days'));
$end = $_GET['end'] ?? date('Y-m-d');

// Clicks trend
$stmt = $pdo->prepare("SELECT DATE(click_time) as day, COUNT(*) as clicks 
                       FROM partners_clicks 
                       WHERE offer_id = ? AND click_time BETWEEN ? AND ? 
                       GROUP BY day ORDER BY day");
$stmt->execute([$offerId, $start, $end]);
$clicksTrend = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Conversions trend
$stmt = $pdo->prepare("SELECT DATE(conversion_time) as day, COUNT(*) as conversions, SUM(payout) as revenue 
                       FROM partners_conversions 
                       WHERE offer_id = ? AND conversion_time BETWEEN ? AND ? 
                       GROUP BY day ORDER BY day");
$stmt->execute([$offerId, $start, $end]);
$convTrend = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Affiliate outliers
$stmt = $pdo->prepare("SELECT affiliate_id, COUNT(*) as convs, SUM(payout) as revenue 
                       FROM partners_conversions 
                       WHERE offer_id = ? AND conversion_time BETWEEN ? AND ? 
                       GROUP BY affiliate_id HAVING convs > 10 ORDER BY revenue DESC");
$stmt->execute([$offerId, $start, $end]);
$outliers = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
    <title><?php echo SITE_TITLE . ' | Offer Insights'; ?></title>
    <link rel="stylesheet" href="css/admin.css">
</head>
<body>
<div class="container">
<h2>📊 Offer Insights for #<?php echo htmlspecialchars($offerId); ?></h2>
<form method="get">
    <input type="hidden" name="id" value="<?php echo htmlspecialchars($offerId); ?>">
    Start: <input type="date" name="start" value="<?php echo htmlspecialchars($start); ?>">
    End: <input type="date" name="end" value="<?php echo htmlspecialchars($end); ?>">
    <button type="submit">Refresh</button>
</form>

<hr><h3>📈 Clicks & Conversion Trends</h3>
<table><tr><th>Date</th><th>Clicks</th><th>Conversions</th><th>Revenue</th></tr>
<?php
foreach ($clicksTrend as $i => $row) {
    $conv = $convTrend[$i]['conversions'] ?? 0;
    $rev = $convTrend[$i]['revenue'] ?? 0;
    echo "<tr>
        <td>" . htmlspecialchars($row['day']) . "</td>
        <td>" . htmlspecialchars($row['clicks']) . "</td>
        <td>" . htmlspecialchars($conv) . "</td>
        <td>" . htmlspecialchars($rev) . "</td>
    </tr>";
}
?>
</table>

<hr><h3>🚨 Affiliate Outliers</h3>
<table><tr><th>ID</th><th>Conversions</th><th>Revenue</th></tr>
<?php
foreach ($outliers as $o) {
    echo "<tr>
        <td>" . htmlspecialchars($o['affiliate_id']) . "</td>
        <td>" . htmlspecialchars($o['convs']) . "</td>
        <td>" . htmlspecialchars($o['revenue']) . "</td>
    </tr>";
}
?>
</table>

<hr><h3>🧠 Optimization Suggestions</h3>
<ul>
    <li>📍 Geo or device targeting may need adjustment if mobile clicks dominate but conversions lag.</li>
    <li>💸 Consider tiered payouts for top affiliates with high revenue.</li>
    <li>🔁 Enable rollover caps if conversions spike near reset windows.</li>
    <li>📡 Review postback delivery logs for failed callbacks or delays.</li>
    <li>🧪 Add test links and QA notes if conversion rate drops unexpectedly.</li>
</ul>
</div>
</body>
</html>