<?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;
$userId = $_SESSION['user_id'] ?? 0;
if (!$offerId || !$userId) die("Missing offer ID or user session");

// Handle insert
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $stmt = $pdo->prepare("INSERT INTO partners_offer_terms 
        (offer_id, restriction_type, restriction_text, severity, created_by)
        VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([
        $offerId,
        $_POST['restriction_type'],
        $_POST['restriction_text'],
        $_POST['severity'],
        $userId
    ]);
    echo "<p class='success'>✅ Restriction saved.</p>";
}

// Fetch restrictions
$stmt = $pdo->prepare("SELECT r.*, u.username FROM partners_offer_terms r 
                       JOIN users u ON r.created_by = u.id 
                       WHERE r.offer_id = ? ORDER BY r.created_at DESC");
$stmt->execute([$offerId]);
$terms = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
    <title><?php echo SITE_TITLE . ' | Offer Terms'; ?></title>
    <link rel="stylesheet" href="css/admin.css">
</head>
<body>
<div class="container">
<h2>📜 Add Offer Restriction for Offer #<?php echo htmlspecialchars($offerId); ?></h2>
<form method="post">
    <label>Restriction Type:
        <select name="restriction_type">
            <option value="geo">Geo Restriction</option>
            <option value="traffic">Traffic Type</option>
            <option value="content">Content Restriction</option>
            <option value="compliance">Compliance Flag</option>
            <option value="other">Other</option>
        </select>
    </label><br>
    <label>Severity:
        <select name="severity">
            <option value="low">Low</option>
            <option value="medium" selected>Medium</option>
            <option value="high">High</option>
            <option value="critical">Critical</option>
        </select>
    </label><br>
    <label>Restriction Details:<br>
        <textarea name="restriction_text" placeholder="Restriction details..."></textarea>
    </label><br>
    <button type="submit">Save Restriction</button>
</form>

<hr><h3>📋 Offer Restrictions</h3>
<table><tr><th>Type</th><th>Severity</th><th>Details</th><th>By</th><th>Time</th></tr>
<?php
foreach ($terms as $r) {
    echo "<tr>
        <td>" . htmlspecialchars($r['restriction_type']) . "</td>
        <td>" . htmlspecialchars($r['severity']) . "</td>
        <td><textarea readonly style='width:300px;height:40px'>" . htmlspecialchars($r['restriction_text']) . "</textarea></td>
        <td>" . htmlspecialchars($r['username']) . "</td>
        <td>{$r['created_at']}</td>
    </tr>";
}
?>
</table>
</div>
</body>
</html>