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

// Predefined traffic types
$types = ['email', 'display', 'social', 'search', 'native', 'push', 'sms', 'in-app'];

// Handle update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    foreach ($types as $type) {
        $allowed = isset($_POST["allow_$type"]) ? 1 : 0;
        $notes = $_POST["notes_$type"] ?? '';

        $sql = "INSERT INTO partners_offer_traffic (offer_id, traffic_type, allowed, notes)
                VALUES (?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE allowed = VALUES(allowed), notes = VALUES(notes)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$offerId, $type, $allowed, $notes]);
    }
    echo "<p class='success'>✅ Traffic settings updated.</p>";
}

// Fetch current settings
$stmt = $pdo->prepare("SELECT traffic_type, allowed, notes FROM partners_offer_traffic WHERE offer_id = ?");
$stmt->execute([$offerId]);
$current = [];
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
    $current[$row['traffic_type']] = $row;
}
?>
<!DOCTYPE html>
<html>
<head>
    <title><?php echo SITE_TITLE . ' | Offer Traffic'; ?></title>
    <link rel="stylesheet" href="css/admin.css">
</head>
<body>
<div class="container">
<h2>📣 Allowed Traffic Methods for Offer #<?php echo htmlspecialchars($offerId); ?></h2>
<form method="post">
<table><tr><th>Type</th><th>Allowed</th><th>Notes</th></tr>
<?php
foreach ($types as $type) {
    $isAllowed = isset($current[$type]) ? $current[$type]['allowed'] : 1;
    $note = isset($current[$type]) ? $current[$type]['notes'] : '';
    echo "<tr>
        <td>" . htmlspecialchars($type) . "</td>
        <td><input type='checkbox' name='allow_$type' " . ($isAllowed ? 'checked' : '') . "></td>
        <td><input name='notes_$type' value='" . htmlspecialchars($note) . "'></td>
    </tr>";
}
?>
</table>
<button type="submit">Save Settings</button>
</form>
</div>
</body>
</html>