<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AuditLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\StreamedResponse;

final class AuditLogController extends Controller
{
    public function index(Request $request): View
    {
        abort_unless($request->user()->hasPermission('audit_logs.view'),403);
        $query=$this->query($request);
        $logs=$query->latest('occurred_at')->paginate(50)->withQueryString();
        $modules=AuditLog::query()->whereHas('user',fn($q)=>$q->where('company_id',$request->user()->company_id))->distinct()->orderBy('module')->pluck('module');
        return view('admin.audit.index',compact('logs','modules'));
    }

    public function show(Request $request, AuditLog $audit): View
    {
        abort_unless($request->user()->hasPermission('audit_logs.view'),403);
        abort_unless($audit->user_id && (int)$audit->user()->value('company_id')===(int)$request->user()->company_id,404);
        $audit->load('user');
        return view('admin.audit.show',compact('audit'));
    }

    public function export(Request $request): StreamedResponse
    {
        abort_unless($request->user()->hasPermission('audit_logs.export'),403);
        $query=$this->query($request)->latest('occurred_at');
        return Response::streamDownload(function()use($query):void{
            $out=fopen('php://output','wb');fputcsv($out,['Date/Time','User','Action','Module','Record Type','Record ID','Reason','IP Address']);
            $query->with('user')->chunkById(500,function($logs)use($out):void{foreach($logs as $log)fputcsv($out,[$log->occurred_at?->format('Y-m-d H:i:s'),$log->user?->email,$log->action,$log->module,$log->record_type,$log->record_id,$log->reason,$log->ip_address]);});fclose($out);
        },'audit-log-'.now()->format('Ymd-His').'.csv',['Content-Type'=>'text/csv']);
    }

    private function query(Request $request)
    {
        return AuditLog::query()->with('user')->whereHas('user',fn($q)=>$q->where('company_id',$request->user()->company_id))
            ->when($request->filled('module'),fn($q)=>$q->where('module',$request->query('module')))
            ->when($request->filled('action'),fn($q)=>$q->where('action',$request->query('action')))
            ->when($request->filled('from'),fn($q)=>$q->whereDate('occurred_at','>=',$request->query('from')))
            ->when($request->filled('to'),fn($q)=>$q->whereDate('occurred_at','<=',$request->query('to')))
            ->when($request->filled('search'),function($q)use($request):void{$s=trim((string)$request->query('search'));$q->where(fn($q)=>$q->where('reason','like',"%{$s}%")->orWhere('record_type','like',"%{$s}%")->orWhereHas('user',fn($u)=>$u->where('name','like',"%{$s}%")->orWhere('email','like',"%{$s}%")));});
    }
}
