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

// Handle access update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $stmt = $pdo->prepare("REPLACE INTO affiliate_offer_access 
        (affiliate_id, offer_id, access_type, granted_by) VALUES (?, ?, ?, ?)");
    $stmt->execute([
        $affId,
        $_POST['offer_id'],
        $_POST['access_type'],
        $_SESSION['admin_id']
    ]);
    echo "<p class='success'>✅ Access updated.</p>";
}

// Fetch all offers
$stmt = $pdo->query("SELECT offer_id, offer_name FROM partners_offers ORDER BY offer_name");
$offers = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch current access
$stmt = $pdo->prepare("SELECT a.*, u.username FROM affiliate_offer_access a 
                       JOIN admin_users u ON a.granted_by = u.id 
                       WHERE affiliate_id = ?");
$stmt->execute([$affId]);
$access = $stmt->fetchAll(PDO::FETCH_ASSOC);

// UI
echo "<h2>📦 Offer Access for Affiliate #" . htmlspecialchars($affId) . "</h2>
<form method='post'>
    <label>Offer:
        <select name='offer_id'>";
foreach ($offers as $o) {
    echo "<option value='" . htmlspecialchars($o['offer_id']) . "'>" . htmlspecialchars($o['offer_name']) . " (#" . htmlspecialchars($o['offer_id']) . ")</option>";
}
echo "</select></label><br>
    <label>Access Type:
        <select name='access_type'>
            <option value='granted'>Grant Access</option>
            <option value='restricted'>Restrict Access</option>
        </select>
    </label><br>
    <button type='submit'>Update Access</button>
</form>";

echo "<hr><h3>🔍 Current Access Overrides</h3>
<table><tr><th>Offer</th><th>Type</th><th>By</th><th>Time</th></tr>";
foreach ($access as $a) {
    echo "<tr>
        <td>" . htmlspecialchars($a['offer_id']) . "</td>
        <td>" . htmlspecialchars($a['access_type']) . "</td>
        <td>" . htmlspecialchars($a['username']) . "</td>
        <td>{$a['granted_at']}</td>
    </tr>";
}
echo "</table>";
?>
</div>
</body>
</html>