<?php

namespace App\Controllers\Api;

use App\Libraries\ResponseHelper;
use App\Models\AuditLogModel;

class AuditLogController extends BaseApiController
{
    public function index()
    {
        if ($err = $this->requirePermission('system_settings')) return $err;

        $db      = \Config\Database::connect();
        $cid     = $this->churchId();
        $perPage = $this->getPerPage();
        $page    = (int) ($this->request->getGet('page') ?? 1);
        $offset  = ($page - 1) * $perPage;

        $userUuid  = $this->request->getGet('user_uuid');
        $table     = $this->request->getGet('table_name');
        $action    = $this->request->getGet('action');
        $dateFrom  = $this->request->getGet('date_from');
        $dateTo    = $this->request->getGet('date_to');

        $base = $db->table('audit_logs al')
                   ->select('al.id, al.action, al.table_name, al.record_uuid, al.old_values, al.new_values, al.ip_address, al.user_agent, al.created_at, u.uuid AS user_uuid, u.name AS user_name')
                   ->join('users u', 'u.id = al.user_id', 'left')
                   ->where('al.church_id', $cid);

        if ($userUuid) {
            $base->where('u.uuid', $userUuid);
        }
        if ($table) {
            $base->where('al.table_name', $table);
        }
        if ($action) {
            $base->where('al.action', $action);
        }
        if ($dateFrom) {
            $base->where('al.created_at >=', $dateFrom);
        }
        if ($dateTo) {
            $base->where('al.created_at <=', $dateTo);
        }

        $total = $db->table('audit_logs al')
                    ->join('users u', 'u.id = al.user_id', 'left')
                    ->where('al.church_id', $cid)
                    ->countAllResults();

        $rows = $base->orderBy('al.created_at', 'DESC')
                     ->limit($perPage, $offset)
                     ->get()->getResultArray();

        $data = array_map(fn($r) => [
            'action'      => $r['action'],
            'table_name'  => $r['table_name'],
            'record_uuid' => $r['record_uuid'],
            'old_values'  => $r['old_values'] ? json_decode($r['old_values'], true) : null,
            'new_values'  => $r['new_values'] ? json_decode($r['new_values'], true) : null,
            'ip_address'  => $r['ip_address'],
            'user_agent'  => $r['user_agent'],
            'user_uuid'   => $r['user_uuid'],
            'user_name'   => $r['user_name'],
            'created_at'  => $r['created_at'],
        ], $rows);

        return ResponseHelper::paginated([
            'data' => $data,
            'meta' => [
                'total'        => $total,
                'per_page'     => $perPage,
                'current_page' => $page,
                'last_page'    => (int) ceil($total / $perPage),
            ],
        ]);
    }
}
