<?php
session_start();
include "includes/layout.php";
include __DIR__ . '/../database/search_log_config.php';
$autoKeyword = $_GET['keyword'] ?? '';
$message = "";

if($_SERVER["REQUEST_METHOD"] === "POST"){
    $keyword = strtolower(trim($_POST['keyword']));
    $url = trim($_POST['redirect_url']);
    $expiry = $_POST['expiry_date'] ?: NULL;

    $stmt = $log_conn->prepare("
        INSERT INTO sponsored_keywords
        (keyword, redirect_url, expiry_date, is_active)
        VALUES (?, ?, ?, 1)
    ");
    $stmt->bind_param("sss", $keyword, $url, $expiry);
    $stmt->execute();
    include "includes/activity_logger.php";
logActivity($log_conn, $_SESSION['admin_id'], 
    "Added Sponsored Keyword: ".$keyword
);
    $stmt->close();

    $message = "Sponsored keyword added successfully!";
}
?>

<h1>Add Sponsored Keyword</h1>

<div class="card">

<?php if($message): ?>
<p style="color:green;"><?= $message ?></p>
<?php endif; ?>

<form method="POST">
<input type="text" 
name="keyword" 
value="<?= htmlspecialchars($autoKeyword) ?>" 
placeholder="Keyword" 
required 
style="width:100%;padding:12px;margin-bottom:15px;border-radius:8px;border:1px solid #ddd;">

<input type="url" name="redirect_url" placeholder="Redirect URL" required style="width:100%;padding:12px;margin-bottom:15px;border-radius:8px;border:1px solid #ddd;">

<input type="date" name="expiry_date" style="width:100%;padding:12px;margin-bottom:15px;border-radius:8px;border:1px solid #ddd;">

<button class="btn">Save Sponsored</button>
</form>

</div>

<?php
$log_conn->close();
include "includes/footer.php";
?>