<?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_delivery 
        (offer_id, delivery_method, suppression_required, suppression_link, compliance_notes, created_by)
        VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->execute([
        $offerId,
        $_POST['delivery_method'],
        isset($_POST['suppression_required']) ? 1 : 0,
        $_POST['suppression_link'],
        $_POST['compliance_notes'],
        $userId
    ]);
    echo "<p class='success'>✅ Delivery method saved.</p>";
}

// Fetch delivery methods
$stmt = $pdo->prepare("SELECT d.*, u.username FROM partners_offer_delivery d 
                       JOIN users u ON d.created_by = u.id 
                       WHERE d.offer_id = ? ORDER BY d.created_at DESC");
$stmt->execute([$offerId]);
$methods = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
    <title><?php echo SITE_TITLE . ' | Offer Delivery'; ?></title>
    <link rel="stylesheet" href="css/admin.css">
</head>
<body>
<div class="container">
<h2>📥 Add Delivery Method for Offer #<?php echo htmlspecialchars($offerId); ?></h2>
<form method="post">
    <label>Delivery Method:
        <select name="delivery_method">
            <option value="email">Email</option>
            <option value="sms">SMS</option>
            <option value="push">Push Notification</option>
            <option value="native">Native Ad</option>
            <option value="other">Other</option>
        </select>
    </label><br>
    <label><input type="checkbox" name="suppression_required"> Suppression Required</label><br>
    <label>Suppression File URL:<br>
        <input name="suppression_link" placeholder="Suppression File URL">
    </label><br>
    <label>Compliance Notes:<br>
        <textarea name="compliance_notes" placeholder="Compliance Notes"></textarea>
    </label><br>
    <button type="submit">Save Delivery</button>
</form>

<hr><h3>📋 Delivery Methods</h3>
<table><tr>
    <th>Method</th><th>Suppression</th><th>Link</th><th>Notes</th><th>By</th><th>Time</th>
</tr>
<?php
foreach ($methods as $d) {
    echo "<tr>
        <td>" . htmlspecialchars($d['delivery_method']) . "</td>
        <td>" . ($d['suppression_required'] ? '✅' : '❌') . "</td>
        <td>" . htmlspecialchars($d['suppression_link']) . "</td>
        <td><textarea readonly style='width:300px;height:40px'>" . htmlspecialchars($d['compliance_notes']) . "</textarea></td>
        <td>" . htmlspecialchars($d['username']) . "</td>
        <td>{$d['created_at']}</td>
    </tr>";
}
?>
</table>
</div>
</body>
</html>