<?php

require_once __DIR__ . '/../../core/api_bootstrap.php';
require_once __DIR__ . '/../../core/permissions.php';

/* METHOD CHECK */
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    json_response(false, 'Invalid request method.', [], 405);
}

/* AUTH */
$user = authenticate($pdo);

/* RBAC CHECK */
if (!can($user, 'audit_logs', 'view', $pdo)) {
    json_response(false, 'Access denied.', [], 403);
}

/* INPUT */
$breakdown_id = isset($_GET['breakdown_id']) ? (int)$_GET['breakdown_id'] : null;
$company_id   = isset($_GET['company_id']) ? (int)$_GET['company_id'] : null;
$date_from    = $_GET['date_from'] ?? null;
$date_to      = $_GET['date_to'] ?? null;
$limit        = isset($_GET['limit']) ? (int)$_GET['limit'] : 100;

if ($limit <= 0 || $limit > 500) {
    $limit = 100;
}

$dateRegex = '/^\d{4}-\d{2}-\d{2}$/';

$where = [];
$params = [];

/* RSP Isolation — NO ROLE CHECK */
if (!empty($user['rsp_id'])) {
    $where[] = "c.rsp_id = ?";
    $params[] = $user['rsp_id'];
}

if ($breakdown_id) {
    $where[] = "a.breakdown_id = ?";
    $params[] = $breakdown_id;
}

if ($company_id) {
    $where[] = "a.company_id = ?";
    $params[] = $company_id;
}

if ($date_from && preg_match($dateRegex, $date_from)) {
    $where[] = "a.created_at >= ?";
    $params[] = $date_from . " 00:00:00";
}

if ($date_to && preg_match($dateRegex, $date_to)) {
    $where[] = "a.created_at <= ?";
    $params[] = $date_to . " 23:59:59";
}

$where_sql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

$sql = "
SELECT
    a.id,
    a.breakdown_id,
    a.company_id,
    c.company_name,
    a.action,
    a.points,
    a.created_at
FROM audit_logs a
LEFT JOIN companies c ON c.id = a.company_id
{$where_sql}
ORDER BY a.created_at DESC
LIMIT ?
";

$params[] = $limit;

$stmt = $pdo->prepare($sql);
$stmt->execute($params);

$logs = $stmt->fetchAll(PDO::FETCH_ASSOC);

json_response(true, 'Audit logs fetched.', [
    'count' => count($logs),
    'logs'  => $logs
]);