<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/auth_admin.php';

apply_cors();
require_admin();
$pdo = getDbConnection();

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    send_error('Method not allowed.', 405);
}

[$page, $perPage, $offset] = paginate_params();
$adminEmail = clean_str($_GET['admin_email'] ?? '');
$action = clean_str($_GET['action_type'] ?? '');

$where = ['1=1'];
$params = [];
if ($adminEmail !== '') { $where[] = 'admin_email = :admin_email'; $params[':admin_email'] = $adminEmail; }
if ($action !== '') { $where[] = 'action = :action'; $params[':action'] = $action; }
$whereSql = implode(' AND ', $where);

$count = $pdo->prepare("SELECT COUNT(*) FROM audit_logs WHERE $whereSql");
$count->execute($params);
$total = (int) $count->fetchColumn();

$stmt = $pdo->prepare(
    "SELECT * FROM audit_logs WHERE $whereSql ORDER BY created_at DESC LIMIT :limit OFFSET :offset"
);
foreach ($params as $k => $v) $stmt->bindValue($k, $v);
$stmt->bindValue(':limit', $perPage, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();

send_success([
    'logs' => $stmt->fetchAll(),
    'pagination' => ['page' => $page, 'per_page' => $perPage, 'total' => $total, 'total_pages' => (int) ceil($total / $perPage)],
]);
