<?php
include __DIR__ . '/../database/search_log_config.php';

/* Get filters */
$search = $_GET['search'] ?? '';
$from   = $_GET['from'] ?? '';
$to     = $_GET['to'] ?? '';

$where = "WHERE 1=1";

if($search){
    $searchSafe = $log_conn->real_escape_string($search);
    $where .= " AND (
        u.admin_name LIKE '%$searchSafe%' OR
        a.activity LIKE '%$searchSafe%' OR
        a.ip_address LIKE '%$searchSafe%'
    )";
}

if($from){
    $where .= " AND DATE(a.created_at) >= '$from'";
}

if($to){
    $where .= " AND DATE(a.created_at) <= '$to'";
}

header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=filtered_activity_logs.xls");

$result = $log_conn->query("
SELECT u.admin_name, a.activity, a.ip_address, a.created_at
FROM admin_activity_logs a
LEFT JOIN admin_users u ON a.admin_id = u.id
$where
ORDER BY a.created_at DESC
");

echo "Admin\tActivity\tIP Address\tDate\n";

while($row = $result->fetch_assoc()){
    echo $row['admin_name']."\t";
    echo $row['activity']."\t";
    echo $row['ip_address']."\t";
    echo $row['created_at']."\n";
}

exit;