<?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_postbacks 
        (offer_id, affiliate_id, postback_type, callback_url, fire_condition, notes, created_by, token_preview)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([
        $offerId,
        $_POST['affiliate_id'] ?? 0,
        $_POST['postback_type'],
        $_POST['callback_url'],
        $_POST['fire_condition'],
        $_POST['notes'],
        $userId,
        $_POST['token_preview'] ?? null
    ]);
    echo "<p class='success'>✅ Postback saved.</p>";
}

// Fetch postbacks
$stmt = $pdo->prepare("SELECT p.*, u.username, a.username AS aff_name 
                       FROM partners_offer_postbacks p 
                       JOIN users u ON p.created_by = u.id 
                       LEFT JOIN users a ON p.affiliate_id = a.id 
                       WHERE p.offer_id = ? ORDER BY p.created_at DESC");
$stmt->execute([$offerId]);
$postbacks = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
    <title><?php echo SITE_TITLE . ' | Offer Postbacks'; ?></title>
    <link rel="stylesheet" href="css/admin.css">
</head>
<body>
<div class="container">
<h2>📡 Add Postback for Offer #<?php echo htmlspecialchars($offerId); ?></h2>
<form method="post">
    <label>Affiliate ID (0 = global):<br>
        <input name="affiliate_id" value="0" placeholder="Affiliate ID">
    </label><br>
    <label>Postback Type:
        <select name="postback_type">
            <option value="pixel">Pixel</option>
            <option value="postback">Postback URL</option>
        </select>
    </label><br>
    <label>Callback URL:<br>
        <input name="callback_url" placeholder="Callback URL">
    </label><br>
    <label>Fire Condition:
        <select name="fire_condition">
            <option value="conversion">Conversion</option>
            <option value="lead">Lead</option>
            <option value="click">Click</option>
            <option value="other">Other</option>
        </select>
    </label><br>
    <label>Token Preview:<br>
        <textarea name="token_preview" placeholder="Token Preview (e.g. {subid}, {amount})"></textarea>
    </label><br>
    <label>Notes:<br>
        <textarea name="notes" placeholder="Notes (optional)"></textarea>
    </label><br>
    <button type="submit">Save Postback</button>
</form>

<hr><h3>📋 Existing Postbacks</h3>
<table><tr>
    <th>Affiliate</th><th>Type</th><th>URL</th><th>Condition</th><th>Tokens</th><th>Notes</th><th>By</th><th>Time</th>
</tr>
<?php
foreach ($postbacks as $p) {
    $aff = $p['affiliate_id'] == 0 ? 'Global' : htmlspecialchars($p['aff_name']) . " (" . htmlspecialchars($p['affiliate_id']) . ")";
    echo "<tr>
        <td>$aff</td>
        <td>" . htmlspecialchars($p['postback_type']) . "</td>
        <td><textarea readonly style='width:300px;height:40px'>" . htmlspecialchars($p['callback_url']) . "</textarea></td>
        <td>" . htmlspecialchars($p['fire_condition']) . "</td>
        <td><textarea readonly style='width:300px;height:40px'>" . htmlspecialchars($p['token_preview']) . "</textarea></td>
        <td><textarea readonly style='width:300px;height:40px'>" . htmlspecialchars($p['notes']) . "</textarea></td>
        <td>" . htmlspecialchars($p['username']) . "</td>
        <td>{$p['created_at']}</td>
    </tr>";
}
?>
</table>
</div>
</body>
</html>