<?php

namespace App\Controllers\Api\V1;

use App\Controllers\BaseController;
use Config\Database;

/**
 * Super Admin only — the centralized Audit Log requested in the
 * activity-tracking spec: filterable by date range, user, role, action
 * type. Browses activity_logs (the richer of the two log tables) rather
 * than audit_logs (record-level before/after changes, used elsewhere).
 */
class AdminAuditLogController extends BaseController
{
    public function index()
    {
        $db = Database::connect();
        $builder = $db->table('activity_logs al')
            ->select('al.id, al.user_id, al.agency_id, al.role, al.action, al.ip_address, al.device, al.browser, al.metadata, al.created_at, u.name as user_name, a.company_name')
            ->join('users u', 'u.id = al.user_id', 'left')
            ->join('agencies a', 'a.id = al.agency_id', 'left');

        $dateFrom = $this->request->getGet('date_from');
        $dateTo   = $this->request->getGet('date_to');
        $userId   = $this->request->getGet('user_id');
        $role     = $this->request->getGet('role');
        $action   = $this->request->getGet('action');

        if ($dateFrom) {
            $builder->where('al.created_at >=', $dateFrom . ' 00:00:00');
        }
        if ($dateTo) {
            $builder->where('al.created_at <=', $dateTo . ' 23:59:59');
        }
        if ($userId) {
            $builder->where('al.user_id', $userId);
        }
        if ($role) {
            $builder->where('al.role', $role);
        }
        if ($action) {
            $builder->where('al.action', $action);
        }

        $page = max(1, (int) ($this->request->getGet('page') ?? 1));
        $perPage = 50;
        $total = $builder->countAllResults(false);

        $rows = $builder->orderBy('al.created_at', 'DESC')->limit($perPage, ($page - 1) * $perPage)->get()->getResultArray();

        $actionTypes = $db->table('activity_logs')->select('action')->distinct()->orderBy('action', 'ASC')->get()->getResultArray();

        return $this->jsonSuccess($rows, [
            'page' => $page, 'per_page' => $perPage, 'total' => $total,
            'action_types' => array_column($actionTypes, 'action'),
        ]);
    }
}
