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

/* ===============================
   DELETE LOG
================================ */
if(isset($_POST['delete_id'])){

    $delete_id = intval($_POST['delete_id']);

    $stmt = $log_conn->prepare("DELETE FROM search_logs WHERE id=?");
    $stmt->bind_param("i", $delete_id);
    $stmt->execute();
    $stmt->close();

    echo "<script>
            alert('Search log deleted successfully');
            window.location='';
          </script>";
}
/* ===============================
   BULK DELETE
================================ */
if(isset($_POST['bulk_delete']) && !empty($_POST['delete_ids'])){

    $ids = $_POST['delete_ids'];

    // Convert all to integers (security)
    $ids = array_map('intval', $ids);

    $placeholders = implode(',', array_fill(0, count($ids), '?'));
    $types = str_repeat('i', count($ids));

    $stmt = $log_conn->prepare("DELETE FROM search_logs WHERE id IN ($placeholders)");
    $stmt->bind_param($types, ...$ids);
    $stmt->execute();
    $stmt->close();

    header("Location: ".$_SERVER['PHP_SELF']);
    exit;
}

/* ===============================
   DATE FILTER
================================ */
$startDate = $_GET['start_date'] ?? '';
$endDate   = $_GET['end_date'] ?? '';

$where = "WHERE 1";
$params = [];
$types  = "";

if(!empty($startDate) && !empty($endDate)){

    // Validate proper date format (YYYY-MM-DD)
    $startObj = DateTime::createFromFormat('Y-m-d', $startDate);
    $endObj   = DateTime::createFromFormat('Y-m-d', $endDate);

    if($startObj && $endObj){

        $where .= " AND DATE(searched_at) BETWEEN ? AND ?";
        $params[] = $startDate;
        $params[] = $endDate;
        $types .= "ss";
    }
}

/* ===============================
   SUMMARY
================================ */
$totalSearch = $log_conn->query("SELECT COUNT(*) c FROM search_logs")->fetch_assoc()['c'];
$todaySearch = $log_conn->query("SELECT COUNT(*) c FROM search_logs WHERE searched_at >= CURDATE()")->fetch_assoc()['c'];
$zeroResult  = $log_conn->query("SELECT COUNT(*) c FROM search_logs WHERE result_count=0")->fetch_assoc()['c'];

/* ===============================
   TREND GRAPH DATA (7 DAYS)
================================ */
$trendQuery = $log_conn->query("
    SELECT DATE(searched_at) d, COUNT(*) c
    FROM search_logs
    WHERE searched_at >= NOW() - INTERVAL 7 DAY
    GROUP BY DATE(searched_at)
    ORDER BY d ASC
");

$dates = [];
$counts = [];

while($row = $trendQuery->fetch_assoc()){
    $dates[] = $row['d'];
    $counts[] = $row['c'];
}

/* ===============================
   TOP 10 KEYWORDS
================================ */
$topKeywords = $log_conn->query("
    SELECT keyword, COUNT(*) c
    FROM search_logs
    WHERE searched_at >= NOW() - INTERVAL 7 DAY
    GROUP BY keyword
    ORDER BY c DESC
    LIMIT 10
");

/* ===============================
   FETCH LOGS
================================ */
$query = "
    SELECT * FROM search_logs
    $where
    ORDER BY id DESC
    LIMIT 200
";

$stmt = $log_conn->prepare($query);

if(!empty($params)){
    $stmt->bind_param($types, ...$params);
}

$stmt->execute();
$result = $stmt->get_result();
?>

<h1>Search Analytics</h1>
<div style="margin-bottom:15px;">
    <a href="export_search_logs.php" class="btn">Export CSV</a>
</div>
<!-- SUMMARY CARDS -->
<div style="display:flex;gap:15px;flex-wrap:wrap;margin-bottom:20px;">
    <div class="summary-card">
        <h3>Total Searches</h3>
        <p><?= $totalSearch ?></p>
    </div>
    <div class="summary-card">
        <h3>Today</h3>
        <p><?= $todaySearch ?></p>
    </div>
    <div class="summary-card">
        <h3>Zero Results</h3>
        <p><?= $zeroResult ?></p>
    </div>
</div>

<!-- DATE FILTER -->
<div class="card" style="margin-bottom:20px;">
<form method="GET">
    <input type="date" name="start_date" value="<?= $startDate ?>">
    <input type="date" name="end_date" value="<?= $endDate ?>">
    <button class="btn">Filter</button>
</form>
</div>

<!-- TREND CHART -->
<div class="card" style="margin-bottom:20px;">
<canvas id="trendChart" height="100"></canvas>
</div>

<div style="display:flex;gap:20px;flex-wrap:wrap;width:100%;align-items:flex-start;">

<!-- SEARCH TABLE -->
<div class="card" style="flex:3;min-width:0;">
<input type="text" id="liveSearch" placeholder="Live Search..."
style="width:100%;padding:10px;margin-bottom:10px;border:1px solid #ddd;border-radius:6px;">

<form method="POST" onsubmit="return confirm('Delete selected logs?');">
<div class="table-wrapper">
<table class="responsive-table">
<thead>
<tr>
<th>
<input type="checkbox" id="selectAll">
</th>
<th>ID</th>
<th>Keyword</th>
<th>Results</th>
<th>IP</th>
<th>Date</th>
<th>Action</th>
</tr>
</thead>

<tbody id="searchBody">
<?php while($row = $result->fetch_assoc()): ?>
<tr style="<?= $row['result_count']==0?'background:#fff3f3':'' ?>">
<td>
<input type="checkbox" name="delete_ids[]" value="<?= $row['id'] ?>">
</td>
<td><?= $row['id'] ?></td>
<td><?= htmlspecialchars($row['keyword']) ?></td>
<td><?= $row['result_count'] ?></td>
<td>
    <?= htmlspecialchars($row['ip_address']) ?>
    <br>
    <a href="block_ip.php?ip=<?= urlencode($row['ip_address']) ?>" 
       class="btn" 
       style="background:#000;color:#fff;font-size:12px;padding:3px 6px;"
       onclick="return confirm('Block this IP permanently?');">
       Block IP
    </a>
</td>
<td><?= date("d M Y", strtotime($row['searched_at'])) ?></td>
<td>

<a href="add_sponsored.php?keyword=<?= urlencode($row['keyword']) ?>" 
   class="btn">Sponsor</a>

<form method="POST" 
      style="display:inline;"
      onsubmit="return confirm('Are you sure you want to delete this log?');">

    <input type="hidden" name="delete_id" value="<?= $row['id'] ?>">

    <button type="submit" 
        name="delete_id" 
        value="<?= $row['id'] ?>" 
        class="btn"
        style="background:#d9534f;color:#fff;"
        onclick="return confirm('Are you sure you want to delete this log?');">
    Delete
</button>

</form>

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

<button type="submit" 
        name="bulk_delete" 
        class="btn" 
        style="background:#d9534f;color:white;margin-top:10px;">
    Delete Selected
</button>

</form>
</div>

<!-- TOP KEYWORDS -->
<div class="card" style="flex:1;min-width:250px;">
<h3>🔥 Top 10 (7 Days)</h3>
<?php while($tk = $topKeywords->fetch_assoc()): ?>
<p>
<?= htmlspecialchars($tk['keyword']) ?>
<span style="float:right;font-weight:bold;"><?= $tk['c'] ?></span>
</p>
<?php endwhile; ?>
</div>

</div>

<style>
.summary-card{
background:#fff;
padding:15px 20px;
border-radius:10px;
box-shadow:0 2px 8px rgba(0,0,0,0.05);
min-width:180px;
}
.summary-card h3{
margin:0;font-size:14px;color:#555;
}
.summary-card p{
font-size:24px;font-weight:bold;color:#007185;margin:5px 0 0;
}
.table-wrapper{overflow-x:auto;}
.responsive-table{width:100%;border-collapse:collapse;}
.responsive-table th,
.responsive-table td{
padding:10px;border-bottom:1px solid #eee;
}

</style>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
/* Chart */
new Chart(document.getElementById("trendChart"), {
    type: 'line',
    data: {
        labels: <?= json_encode($dates) ?>,
        datasets: [{
            label: "Searches",
            data: <?= json_encode($counts) ?>,
            borderColor: "#007185",
            fill: false,
            tension: 0.3
        }]
    }
});

/* Live Search */
document.getElementById("liveSearch").addEventListener("keyup", function(){
    let filter = this.value.toLowerCase();
    let rows = document.querySelectorAll("#searchBody tr");

    rows.forEach(row=>{
        let keyword = row.cells[1].innerText.toLowerCase();
        row.style.display = keyword.includes(filter) ? "" : "none";
    });
});
/* Select All */
document.getElementById("selectAll").addEventListener("change", function() {
    let checkboxes = document.querySelectorAll("input[name='delete_ids[]']");
    checkboxes.forEach(cb => cb.checked = this.checked);
});
</script>
<?php
$stmt->close();
$log_conn->close();
include "includes/footer.php";
?>