<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Auditoria;
use Illuminate\Http\Request;

class AuditoriaController extends Controller
{
    public function index(Request $request)
    {
        $query = Auditoria::with(['usuario', 'sucursal']);

        // Aislamiento Multi-Tenant Crítico
        if (!auth()->user()->hasRole('superadmin')) {
            $query->where('sucursal_id', session('sucursal_id'));
        } else {
            $query->when($request->sucursal_id, fn($q) => $q->where('sucursal_id', $request->sucursal_id));
        }

        $registros = $query->when($request->usuario, function($q) use ($request) {
                $q->whereHas('usuario', function($q2) use ($request) {
                    $q2->where('name', 'like', "%{$request->usuario}%")
                       ->orWhere('dni', 'like', "%{$request->usuario}%");
                });
            })
            ->when($request->modelo,   fn($q) => $q->where('modelo', $request->modelo))
            ->when($request->accion,   fn($q) => $q->where('accion', $request->accion))
            ->when($request->desde,    fn($q) => $q->whereDate('created_at', '>=', $request->desde))
            ->when($request->hasta,    fn($q) => $q->whereDate('created_at', '<=', $request->hasta))
            ->latest()
            ->paginate(30)
            ->withQueryString();

        $modelos = Auditoria::select('modelo')->distinct()->pluck('modelo')->filter()->sort();
        $acciones = ['crear', 'actualizar', 'eliminar', 'login', 'logout'];
        $sucursales = auth()->user()->hasRole('superadmin') ? \App\Models\Sucursal::orderBy('nombre')->get() : collect();

        return view('admin.auditoria.index', compact('registros', 'modelos', 'acciones', 'sucursales'));
    }

    public function show(Auditoria $auditoria)
    {
        $auditoria->load(['usuario', 'sucursal']);
        return view('admin.auditoria.show', compact('auditoria'));
    }
}