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

// Define modules
$modules = [
    'caps' => 'Caps & Limits',
    'geo' => 'Geo Targeting',
    'redirects' => 'Redirect Logic',
    'affiliates' => 'Affiliate Access',
    'traffic' => 'Traffic Methods',
    'security' => 'Security Rules',
    'notes' => 'Offer Notes',
    'files' => 'File Uploads',
    'postbacks' => 'Postbacks & Pixels',
    'stats' => 'Offer Stats'
];

// Handle update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    foreach ($modules as $key => $label) {
        $enabled = isset($_POST["enable_$key"]) ? 1 : 0;
        $notes = $_POST["notes_$key"] ?? '';

        $stmt = $pdo->prepare("INSERT INTO partners_offer_modules (offer_id, module_name, enabled, notes)
                               VALUES (?, ?, ?, ?)
                               ON DUPLICATE KEY UPDATE enabled = VALUES(enabled), notes = VALUES(notes)");
        $stmt->execute([$offerId, $key, $enabled, $notes]);
    }
    echo "<p class='success'>✅ Module settings updated.</p>";
}

// Fetch current settings
$stmt = $pdo->prepare("SELECT module_name, enabled, notes FROM partners_offer_modules WHERE offer_id = ?");
$stmt->execute([$offerId]);
$current = [];
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
    $current[$row['module_name']] = $row;
}
?>
<!DOCTYPE html>
<html>
<head>
    <title><?php echo SITE_TITLE . ' | Offer Modules'; ?></title>
    <link rel="stylesheet" href="css/admin.css">
</head>
<body>
<div class="container">
<h2>🧩 Module Visibility for Offer #<?php echo htmlspecialchars($offerId); ?></h2>
<form method="post">
<table>
<tr><th>Module</th><th>Enabled</th><th>Notes</th></tr>
<?php
foreach ($modules as $key => $label) {
    $isEnabled = isset($current[$key]) ? $current[$key]['enabled'] : 1;
    $note = isset($current[$key]) ? $current[$key]['notes'] : '';
    echo "<tr>
        <td>" . htmlspecialchars($label) . "</td>
        <td><input type='checkbox' name='enable_$key' " . ($isEnabled ? 'checked' : '') . "></td>
        <td><input name='notes_$key' value='" . htmlspecialchars($note) . "'></td>
    </tr>";
}
?>
</table>
<button type="submit">Save Settings</button>
</form>
</div>
</body>
</html>