<?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");
}
?>
<!DOCTYPE html>
<html>
<head>
    <title><?php echo SITE_TITLE . ' | Offer Applications'; ?></title>
    <link rel="stylesheet" href="css/admin.css">
</head>
<body>
<div class="container">
<?php
// Handle approval
if (isset($_GET['approve']) && is_numeric($_GET['approve'])) {
    $stmt = $pdo->prepare("UPDATE partners_offer_applications 
                           SET status = 'approved', reviewed_by = ?, reviewed_at = NOW() 
                           WHERE id = ?");
    $stmt->execute([$_SESSION['admin_id'], $_GET['approve']]);
    echo "<p class='success'>✅ Application approved.</p>";
}

// Handle denial
if (isset($_GET['reject']) && is_numeric($_GET['reject'])) {
    $stmt = $pdo->prepare("UPDATE partners_offer_applications 
                           SET status = 'denied', reviewed_by = ?, reviewed_at = NOW() 
                           WHERE id = ?");
    $stmt->execute([$_SESSION['admin_id'], $_GET['reject']]);
    echo "<p class='error'>❌ Application denied.</p>";
}

// Fetch pending applications
$sql = "SELECT a.*, o.offer_title, u.username 
        FROM partners_offer_applications a
        JOIN partners_offers o ON a.offer_id = o.offer_id
        JOIN users u ON a.affiliate_id = u.id
        WHERE a.status = 'pending'
        ORDER BY a.applied_at DESC";
$stmt = $pdo->query($sql);
$apps = $stmt->fetchAll(PDO::FETCH_ASSOC);

// UI
echo "<h2>📝 Offer Applications</h2>
<table><tr><th>Affiliate</th><th>Offer</th><th>Date</th><th>Action</th></tr>";
foreach ($apps as $app) {
    echo "<tr>
        <td>" . htmlspecialchars($app['username']) . "</td>
        <td>" . htmlspecialchars($app['offer_title']) . "</td>
        <td>{$app['applied_at']}</td>
        <td>
            <a href='admin_offer_applications.php?approve=" . htmlspecialchars($app['id']) . "'>Approve</a> | 
            <a href='admin_offer_applications.php?reject=" . htmlspecialchars($app['id']) . "'>Deny</a>
        </td>
    </tr>";
}
echo "</table>";
?>
</div>
</body>
</html>