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

// Handle insert/update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $stmt = $pdo->prepare("INSERT INTO partners_offer_security (offer_id, rule_type, rule_value, enabled, notes)
                           VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([
        $offerId,
        $_POST['rule_type'],
        $_POST['rule_value'],
        isset($_POST['enabled']) ? 1 : 0,
        $_POST['notes']
    ]);
    echo "<p class='success'>✅ Security rule saved.</p>";
}

// Fetch rules
$stmt = $pdo->prepare("SELECT * FROM partners_offer_security WHERE offer_id = ? ORDER BY rule_type");
$stmt->execute([$offerId]);
$rules = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
    <title><?php echo SITE_TITLE . ' | Offer Security'; ?></title>
    <link rel="stylesheet" href="css/admin.css">
</head>
<body>
<div class="container">
<h2>🛡️ Security Settings for Offer #<?php echo htmlspecialchars($offerId); ?></h2>
<form method="post">
    <label>Rule Type:
        <select name="rule_type">
            <option value="block_ip">Block IP</option>
            <option value="block_range">Block IP Range</option>
            <option value="block_duplicate">Block Duplicate IP</option>
            <option value="proxy_filter">Proxy Filtering</option>
        </select>
    </label><br>
    <label>Rule Value:<br>
        <input name="rule_value" placeholder="IP / Range / Leave blank for proxy">
    </label><br>
    <label><input type="checkbox" name="enabled" checked> Enabled</label><br>
    <label>Notes:<br>
        <textarea name="notes" placeholder="Notes (optional)"></textarea>
    </label><br>
    <button type="submit">Save Rule</button>
</form>

<hr><h3>📋 Existing Security Rules</h3>
<table><tr><th>Type</th><th>Value</th><th>Enabled</th><th>Notes</th></tr>
<?php
foreach ($rules as $r) {
    echo "<tr>
        <td>" . htmlspecialchars($r['rule_type']) . "</td>
        <td>" . htmlspecialchars($r['rule_value']) . "</td>
        <td>" . ($r['enabled'] ? '✅' : '❌') . "</td>
        <td><textarea readonly style='width:300px;height:40px'>" . htmlspecialchars($r['notes']) . "</textarea></td>
    </tr>";
}
?>
</table>
</div>
</body>
</html>