<?php

namespace App\Http\Controllers;

use App\Models\AuditLog;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Builder;
use Symfony\Component\HttpFoundation\StreamedResponse;

class AuditLogController extends Controller
{
    public function index(Request $request)
    {
        abort_unless(auth()->user()->is_admin, 403, 'Only management can access the system log sheet.');
        $this->useDefaultDateRange($request);
        $request->validate([
            'q'=>['nullable','string','max:100'],'date_from'=>['nullable','date'],
            'date_to'=>['nullable','date','after_or_equal:date_from'],
            'user_id'=>['nullable','integer'], 'action'=>['nullable','string','max:100'],
            'entity_type'=>['nullable','string','max:255'],
        ]);

        $logs = $this->filtered($request)
            ->latest('performed_at')
            ->paginate(50)
            ->withQueryString();

        $employees = User::where('business_id', auth()->user()->business_id)
            ->orderBy('name')
            ->get(['id', 'name', 'email']);

        $actions = AuditLog::where('business_id', auth()->user()->business_id)
            ->distinct()->orderBy('action')->pluck('action');
        $entityTypes = AuditLog::where('business_id', auth()->user()->business_id)
            ->whereNotNull('entity_type')->distinct()->orderBy('entity_type')->pluck('entity_type');

        return view('audit-logs.index', compact('logs', 'employees', 'actions', 'entityTypes'));
    }

    public function export(Request $request): StreamedResponse
    {
        abort_unless($request->user()->is_admin, 403, 'Only management can export audit logs.');

        $file = 'audit-logs-'.now()->format('Ymd-His').'.csv';
        return response()->streamDownload(function () use ($request) {
            $output = fopen('php://output', 'w');
            fputcsv($output, ['Date','Employee','Email','Team','Action','Module','Record','Route','Method',
                'Result','IP Address','Old Values','New Values','Request Data']);
            $this->filtered($request)->orderBy('id')->chunk(500, function ($logs) use ($output) {
                foreach ($logs as $log) {
                    fputcsv($output, [
                        $log->performed_at?->toDateTimeString(), $log->employee_name, $log->employee_email,
                        $log->team_name, $log->action, $log->entity_type, $log->entity_id, $log->route_name,
                        $log->method, $log->response_status, $log->ip_address,
                        json_encode($log->old_values), json_encode($log->new_values), json_encode($log->request_data),
                    ]);
                }
            });
            fclose($output);
        }, $file, ['Content-Type' => 'text/csv']);
    }

    private function filtered(Request $request): Builder
    {
        return AuditLog::where('business_id', $request->user()->business_id)
            ->when($request->filled('q'),fn($query)=>$query->where(function($filter)use($request){
                $search=trim((string)$request->q);
                $filter->where('employee_name','like',"%{$search}%")
                    ->orWhere('employee_email','like',"%{$search}%")
                    ->orWhere('action','like',"%{$search}%")
                    ->orWhere('entity_type','like',"%{$search}%")
                    ->orWhere('route_name','like',"%{$search}%");
            }))
            ->when($request->filled('user_id'), fn ($query) => $query->where('user_id', $request->user_id))
            ->when($request->filled('action'), fn ($query) => $query->where('action', $request->action))
            ->when($request->filled('entity_type'), fn ($query) => $query->where('entity_type', $request->entity_type))
            ->when($request->filled('date_from'), fn ($query) => $query->whereDate('performed_at', '>=', $request->date_from))
            ->when($request->filled('date_to'), fn ($query) => $query->whereDate('performed_at', '<=', $request->date_to));
    }
}
