<?php
session_start();
include "includes/layout.php";
include __DIR__ . '/../database/search_log_config.php';

$id = (int)$_GET['id'];

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

    $stmt = $log_conn->prepare("
        UPDATE sponsored_keywords 
        SET keyword=?, redirect_url=?, expiry_date=? 
        WHERE id=?
    ");
    $stmt->bind_param("sssi", $keyword, $url, $expiry, $id);
    $stmt->execute();
    $stmt->close();
include "includes/activity_logger.php";
logActivity($log_conn, $_SESSION['admin_id'], 
    "Edited Sponsored ID: ".$id
);
    echo "<script>window.location='view_sponsored.php';</script>";
}

$row = $log_conn->query("
SELECT * FROM sponsored_keywords WHERE id=$id
")->fetch_assoc();
?>

<h1>Edit Sponsored</h1>

<div class="card">
<form method="POST">
<input type="text" name="keyword" 
value="<?= htmlspecialchars($row['keyword']) ?>" 
style="width:100%;padding:10px;margin-bottom:10px;">

<input type="url" name="redirect_url" 
value="<?= htmlspecialchars($row['redirect_url']) ?>" 
style="width:100%;padding:10px;margin-bottom:10px;">

<input type="date" name="expiry_date" 
value="<?= $row['expiry_date'] ?>" 
style="width:100%;padding:10px;margin-bottom:10px;">

<button class="btn">Update</button>
</form>
</div>

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