<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\LoginLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class LoginLogController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $query = LoginLog::with('user');

        // Filtros
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        if ($request->filled('email')) {
            $query->where('email', 'like', '%' . $request->email . '%');
        }

        if ($request->filled('ip')) {
            $query->where('ip_address', 'like', '%' . $request->ip . '%');
        }

        if ($request->filled('date_from')) {
            $query->whereDate('attempted_at', '>=', $request->date_from);
        }

        if ($request->filled('date_to')) {
            $query->whereDate('attempted_at', '<=', $request->date_to);
        }

        // Ordenação
        $sortBy = $request->get('sort_by', 'attempted_at');
        $sortOrder = $request->get('sort_order', 'desc');
        $query->orderBy($sortBy, $sortOrder);

        // Paginação
        $logs = $query->paginate(20)->withQueryString();

        // Estatísticas
        $stats = $this->getStats($request);

        return view('admin.login-logs.index', compact('logs', 'stats'));
    }

    /**
     * Mostra estatísticas dos logs
     */
    public function stats(Request $request)
    {
        $stats = $this->getStats($request);
        
        return view('admin.login-logs.stats', compact('stats'));
    }

    /**
     * Exporta logs para CSV
     */
    public function export(Request $request)
    {
        $query = LoginLog::with('user');

        // Aplicar mesmos filtros do index
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        if ($request->filled('email')) {
            $query->where('email', 'like', '%' . $request->email . '%');
        }

        if ($request->filled('ip')) {
            $query->where('ip_address', 'like', '%' . $request->ip . '%');
        }

        if ($request->filled('date_from')) {
            $query->whereDate('attempted_at', '>=', $request->date_from);
        }

        if ($request->filled('date_to')) {
            $query->whereDate('attempted_at', '<=', $request->date_to);
        }

        $logs = $query->orderBy('attempted_at', 'desc')->get();

        $filename = 'login-logs-' . now()->format('Y-m-d-H-i-s') . '.csv';
        
        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="' . $filename . '"',
        ];

        $callback = function() use ($logs) {
            $file = fopen('php://output', 'w');
            
            // Cabeçalho
            fputcsv($file, [
                'ID', 'E-mail', 'IP', 'Status', 'Motivo da Falha', 
                'Usuário', 'User Agent', 'Data/Hora'
            ]);

            // Dados
            foreach ($logs as $log) {
                fputcsv($file, [
                    $log->id,
                    $log->email,
                    $log->ip_address,
                    $log->status,
                    $log->failure_reason,
                    $log->user ? $log->user->name : 'N/A',
                    $log->user_agent,
                    $log->attempted_at->format('d/m/Y H:i:s')
                ]);
            }

            fclose($file);
        };

        return response()->stream($callback, 200, $headers);
    }

    /**
     * Limpa logs antigos
     */
    public function clear(Request $request)
    {
        $days = $request->get('days', 30);
        
        $deleted = LoginLog::where('attempted_at', '<', now()->subDays($days))->delete();
        
        return redirect()->back()->with('success', "{$deleted} logs antigos foram removidos.");
    }

    /**
     * Obtém estatísticas dos logs
     */
    private function getStats(Request $request)
    {
        $query = LoginLog::query();

        // Aplicar filtros de data se fornecidos
        if ($request->filled('date_from')) {
            $query->whereDate('attempted_at', '>=', $request->date_from);
        }

        if ($request->filled('date_to')) {
            $query->whereDate('attempted_at', '<=', $request->date_to);
        }

        $stats = [
            'total' => $query->count(),
            'success' => (clone $query)->where('status', 'success')->count(),
            'failed' => (clone $query)->where('status', 'failed')->count(),
            'blocked' => (clone $query)->where('status', 'blocked')->count(),
            'unique_ips' => (clone $query)->distinct('ip_address')->count('ip_address'),
            'unique_emails' => (clone $query)->distinct('email')->count('email'),
        ];

        // Top IPs com mais tentativas
        $stats['top_ips'] = (clone $query)
            ->select('ip_address', DB::raw('count(*) as attempts'))
            ->groupBy('ip_address')
            ->orderBy('attempts', 'desc')
            ->limit(10)
            ->get();

        // Top e-mails com mais tentativas
        $stats['top_emails'] = (clone $query)
            ->select('email', DB::raw('count(*) as attempts'))
            ->groupBy('email')
            ->orderBy('attempts', 'desc')
            ->limit(10)
            ->get();

        // Tentativas por hora (últimas 24h)
        $stats['hourly_attempts'] = (clone $query)
            ->where('attempted_at', '>=', now()->subHours(24))
            ->select(DB::raw('HOUR(attempted_at) as hour'), DB::raw('count(*) as attempts'))
            ->groupBy('hour')
            ->orderBy('hour')
            ->get();

        return $stats;
    }
}
