<?php
declare(strict_types=1);

require_once __DIR__ . '/../system/bootstrap.php';
require_once __DIR__ . '/../system/auth.php';
require_once __DIR__ . '/../system/response.php';

header('Content-Type: application/json');

try {
    /* =========================
       AUTH
       ========================= */
    $user = require_auth($pdo);

    $role = strtolower((string)$user['role_key']);

    if (!in_array($role, ['super_admin', 'platform_admin', 'rsp_admin', 'company_admin'], true)) {
        error_forbidden('Access denied');
    }

    /* =========================
       INPUT (SAFE)
       ========================= */
    $page  = max(1, (int)($_GET['page'] ?? 1));
    $limit = min(100, max(1, (int)($_GET['limit'] ?? 25)));
    $offset = ($page - 1) * $limit;

    $filters = [
        'actor'       => trim((string)($_GET['actor'] ?? '')),
        'action'      => trim((string)($_GET['action'] ?? '')),
        'target_type' => trim((string)($_GET['target_type'] ?? '')),
        'from'        => trim((string)($_GET['from'] ?? '')),
        'to'          => trim((string)($_GET['to'] ?? '')),
    ];

    /* =========================
       BASE QUERY
       ========================= */
    $where = [];
    $params = [];

    /* ---------- Scope enforcement ---------- */
    if ($role === 'rsp_admin') {
        $where[] = 'rsp_id = :rsp_id';
        $params[':rsp_id'] = (int)$user['rsp_id'];
    }

    if ($role === 'company_admin') {
        $where[] = 'company_id = :company_id';
        $params[':company_id'] = (int)$user['company_id'];
    }

    /* ---------- Optional filters ---------- */
    if ($filters['actor'] !== '') {
        $where[] = 'actor_email LIKE :actor';
        $params[':actor'] = '%' . $filters['actor'] . '%';
    }

    if ($filters['action'] !== '') {
        $where[] = 'action = :action';
        $params[':action'] = $filters['action'];
    }

    if ($filters['target_type'] !== '') {
        $where[] = 'target_type = :target_type';
        $params[':target_type'] = $filters['target_type'];
    }

    if ($filters['from'] !== '') {
        $where[] = 'created_at >= :from_date';
        $params[':from_date'] = $filters['from'] . ' 00:00:00';
    }

    if ($filters['to'] !== '') {
        $where[] = 'created_at <= :to_date';
        $params[':to_date'] = $filters['to'] . ' 23:59:59';
    }

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

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

    /* =========================
       DATA QUERY
       ========================= */
    $stmt = $pdo->prepare("
        SELECT
            id,
            actor_id,
            actor_email,
            actor_role,
            action,
            target_type,
            target_id,
            company_name,
            rsp_name,
            ip_address,
            metadata,
            created_at
        FROM audit_logs
        $whereSql
        ORDER BY created_at DESC
        LIMIT :limit OFFSET :offset
    ");

    foreach ($params as $k => $v) {
        $stmt->bindValue($k, $v);
    }

    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);

    $stmt->execute();

    $logs = [];

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $row['metadata'] = $row['metadata']
            ? json_decode($row['metadata'], true, 512, JSON_THROW_ON_ERROR)
            : null;

        $logs[] = $row;
    }

    /* =========================
       RESPONSE
       ========================= */
    success('Audit logs loaded', [
        'logs'  => $logs,
        'total' => $total
    ]);

} catch (Throwable $e) {
    error_internal('Server error');
}
