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

/* Security Check (optional but recommended) */
if(!isset($_SESSION['admin_id'])){
    die("Unauthorized Access");
}

/* Set CSV Headers */
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="search_logs.csv"');

/* Open output stream */
$output = fopen('php://output', 'w');

/* Column headers */
fputcsv($output, ['ID', 'Keyword', 'Result Count', 'IP Address', 'Date']);

/* Fetch data */
$result = $log_conn->query("SELECT * FROM search_logs ORDER BY id DESC");

while($row = $result->fetch_assoc()){
    fputcsv($output, [
        $row['id'],
        $row['keyword'],
        $row['result_count'],
        $row['ip_address'],
        $row['searched_at']
    ]);
}

fclose($output);
exit;
?>