<?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");
}

// Filters
$start = $_GET['start'] ?? date('Y-m-01');
$end = $_GET['end'] ?? date('Y-m-d');
$affiliateId = $_GET['affiliate_id'] ?? null;
$offerId = $_GET['offer_id'] ?? null;

$query = "SELECT a.name AS affiliate_name, o.name AS offer_name, 
                 p.affiliate_id, p.offer_id, SUM(p.amount) AS total_payout 
          FROM affiliate_payouts p 
          JOIN affiliates a ON p.affiliate_id = a.id 
          JOIN offers o ON p.offer_id = o.id 
          WHERE p.created_at BETWEEN ? AND ?";
$params = [$start . ' 00:00:00', $end . ' 23:59:59'];

if ($affiliateId) {
    $query .= " AND p.affiliate_id = ?";
    $params[] = $affiliateId;
}
if ($offerId) {
    $query .= " AND p.offer_id = ?";
    $params[] = $offerId;
}

$query .= " GROUP BY p.affiliate_id, p.offer_id ORDER BY total_payout DESC";
$stmt = $pdo->prepare($query);
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
    <title><?php echo SITE_TITLE . ' | Payout Summary'; ?></title>
    <link rel="stylesheet" href="css/admin.css">
</head>
<body>
<div class="container">
<h2>🧮 Payout Summary</h2>
<form method="get">
    <label>Start Date:
        <input type="date" name="start" value="<?php echo htmlspecialchars($start); ?>">
    </label>
    <label>End Date:
        <input type="date" name="end" value="<?php echo htmlspecialchars($end); ?>">
    </label>
    <label>Affiliate ID:
        <input name="affiliate_id" placeholder="Affiliate ID" value="<?php echo htmlspecialchars($affiliateId); ?>">
    </label>
    <label>Offer ID:
        <input name="offer_id" placeholder="Offer ID" value="<?php echo htmlspecialchars($offerId); ?>">
    </label>
    <button type="submit">Filter</button>
</form>

<hr><table>
<tr><th>Affiliate</th><th>Offer</th><th>Total Payout</th></tr>
<?php
foreach ($rows as $r) {
    echo "<tr>
        <td>" . htmlspecialchars($r['affiliate_name']) . " (#" . htmlspecialchars($r['affiliate_id']) . ")</td>
        <td>" . htmlspecialchars($r['offer_name']) . " (#" . htmlspecialchars($r['offer_id']) . ")</td>
        <td>$" . number_format($r['total_payout'], 2) . "</td>
    </tr>";
}
?>
</table>
</div>
</body>
</html>