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

$result = $log_conn->query("SELECT * FROM sponsored_keywords ORDER BY id DESC");
?>

<h1>Sponsored Keywords</h1>

<div class="card">

<div class="table-wrapper">

<table class="responsive-table">
<thead>
<tr>
<th>ID</th>
<th>Keyword</th>
<th>Redirect URL</th>
<th>Clicks</th>
<th>Expiry</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>

<tbody>
<?php while($row = $result->fetch_assoc()): ?>
<tr>
<td><?= $row['id'] ?></td>

<td><?= htmlspecialchars($row['keyword']) ?></td>

<td class="url-cell">
<?= htmlspecialchars($row['redirect_url']) ?>
</td>

<td><?= $row['click_count'] ?></td>

<td><?= $row['expiry_date'] ?? 'No Expiry' ?></td>

<td>
<label class="switch">
<input type="checkbox" <?= $row['is_active'] ? 'checked' : '' ?>
onclick="toggleStatus(<?= $row['id'] ?>)">
<span class="slider"></span>
</label>
</td>

<td class="actions">
<a href="edit_sponsored.php?id=<?= $row['id'] ?>" class="btn">Edit</a>
<a href="delete_sponsored.php?id=<?= $row['id'] ?>" 
class="btn delete-btn">Delete</a>
</td>

</tr>
<?php endwhile; ?>
</tbody>
</table>

</div>
</div>

<style>

/* Scroll wrapper */
.table-wrapper{
    overflow-x:auto;
}

/* Table */
.responsive-table{
    width:100%;
    border-collapse:collapse;
    min-width:900px;
}

/* Header */
.responsive-table thead{
    background:#f8fafc;
}

.responsive-table th{
    padding:12px;
    text-align:left;
    font-weight:600;
    border-bottom:2px solid #eee;
}

/* Body */
.responsive-table td{
    padding:12px;
    border-bottom:1px solid #eee;
    vertical-align:middle;
}

/* URL handling */
.url-cell{
    max-width:200px;
    word-break:break-word;
    font-size:13px;
    color:#555;
}

/* Buttons */
.actions{
    white-space:nowrap;
}

.delete-btn{
    background:#e74c3c;
    margin-left:5px;
}

/* Mobile */
@media(max-width:768px){
    .responsive-table{
        font-size:13px;
    }
}

</style>

<script>
function toggleStatus(id){
    fetch('toggle_status.php?id='+id)
    .then(()=> location.reload());
}
</script>

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