<?php

namespace App\Http\Controllers;

use App\Models\AuditLog;
use App\Models\User;
use Illuminate\Http\Request;
use Carbon\Carbon;

class AuditLogController extends Controller
{
    public function index(Request $request)
    {
        $query = AuditLog::with('user');

        // Filter by action
        if ($request->filled('action')) {
            $query->where('action', $request->action);
        }

        // Filter by user
        if ($request->filled('user_id')) {
            $query->where('user_id', $request->user_id);
        }

        // Filter by date range
        if ($request->filled('start_date')) {
            $query->whereDate('log_date', '>=', $request->start_date);
        }

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

        // Search in description
        if ($request->filled('search')) {
            $query->where('description', 'like', '%' . $request->search . '%');
        }

        $auditLogs = $query->orderBy('log_date', 'desc')->paginate(50);

        // Get filter options
        $actions = AuditLog::select('action')->distinct()->pluck('action');
        $user_ids = User::select('user_id', 'name')->get();

        // Get statistics
        $stats = AuditLog::getAuditStats();

        return view('admin.audit-logs.index', compact(
            'auditLogs',
            'actions',
            'user_ids',
            'stats'
        ));
    }

    public function show(AuditLog $auditLog)
    {
        $auditLog->load('user');
        return view('admin.audit-logs.show', compact('auditLog'));
    }

    public function userLogs(User $user_id)
    {
        $auditLogs = AuditLog::getUserLogs($user_id->user_id, 100);
        return view('admin.audit-logs.user-logs', compact('auditLogs', 'user_id'));
    }

    public function actionLogs($action)
    {
        $auditLogs = AuditLog::getLogsByAction($action, 100);
        return view('admin.audit-logs.action-logs', compact('auditLogs', 'action'));
    }

    public function export(Request $request)
    {
        $query = AuditLog::with('user');

        // Apply same filters as index
        if ($request->filled('action')) {
            $query->where('action', $request->action);
        }

        if ($request->filled('user_id')) {
            $query->where('user_id', $request->user_id);
        }

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

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

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

        $auditLogs = $query->orderBy('log_date', 'desc')->get();

        $csvData = [];
        $csvData[] = ['Date', 'User', 'Action', 'Description', 'IP Address', 'Model Type', 'Model ID'];

        foreach ($auditLogs as $log) {
            $csvData[] = [
                $log->log_date->format('Y-m-d H:i:s'),
                $log->user ? $log->user->name : 'Unknown',
                $log->formatted_action,
                $log->description ?? '',
                $log->ip_address ?? '',
                $log->model_type ?? '',
                $log->model_id ?? '',
            ];
        }

        $filename = 'audit_logs_' . now()->format('Y-m-d_H-i-s') . '.csv';

        $callback = function () use ($csvData) {
            $file = fopen('php://output', 'w');
            foreach ($csvData as $row) {
                fputcsv($file, $row);
            }
            fclose($file);
        };

        return response()->stream($callback, 200, [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="' . $filename . '"',
        ]);
    }

    public function statistics()
    {
        $stats = AuditLog::getAuditStats();

        // Get daily logs for the last 30 days
        $dailyLogs = AuditLog::selectRaw('DATE(log_date) as date, COUNT(*) as count')
            ->where('log_date', '>=', Carbon::now()->subDays(30))
            ->groupBy('date')
            ->orderBy('date')
            ->get();

        // Get action distribution
        $actionDistribution = AuditLog::selectRaw('action, COUNT(*) as count')
            ->groupBy('action')
            ->orderBy('count', 'desc')
            ->get();

        // Get top users by activity
        $topUsers = AuditLog::selectRaw('user_id, COUNT(*) as activity_count')
            ->with('user')
            ->groupBy('user_id')
            ->orderBy('activity_count', 'desc')
            ->limit(10)
            ->get();

        return view('admin.audit-logs.statistics', compact(
            'stats',
            'dailyLogs',
            'actionDistribution',
            'topUsers'
        ));
    }
}
