<?php

namespace App\Http\Controllers;

use App\Models\ActivityLog;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ActivityLogController extends Controller
{
    /**
     * Show all activity logs (Super Admin Dashboard)
     */
    public function index(Request $request)
    {
        // Check if user is super admin
        if (Auth::user()->role !== 'super_admin') {
            abort(403, 'Unauthorized');
        }

        $query = ActivityLog::with('user');

        // Filter by admin user
        if ($request->filled('user_id') && $request->user_id !== 'all') {
            $query->where('user_id', $request->user_id);
        } else {
            // By default, show only admin activities
            $query->adminsOnly();
        }

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

        // Filter by model type
        if ($request->filled('model_type') && $request->model_type !== 'all') {
            $query->modelType($request->model_type);
        }

        // Filter by date range
        if ($request->filled('start_date')) {
            $query->where('created_at', '>=', $request->start_date . ' 00:00:00');
        }
        if ($request->filled('end_date')) {
            $query->where('created_at', '<=', $request->end_date . ' 23:59:59');
        }

        // Get activity logs with pagination
        $activityLogs = $query->orderBy('created_at', 'desc')->paginate(20);

        // Get all admins for filter dropdown
        $admins = User::where('role', 'admin')->get();

        // Get distinct model types
        $modelTypes = ActivityLog::distinct()
            ->pluck('model_type')
            ->filter()
            ->values();

        // Get activity summary
        $summary = $this->getActivitySummary($request);

        return view('admin.activity-logs.index', compact(
            'activityLogs',
            'admins',
            'modelTypes',
            'summary'
        ));
    }

    /**
     * Show activity log for a specific admin
     */
    public function adminActivity(Request $request, User $admin)
    {
        // Check if user is super admin
        if (Auth::user()->role !== 'super_admin') {
            abort(403, 'Unauthorized');
        }

        // Ensure the user is an admin
        if ($admin->role !== 'admin') {
            abort(404);
        }

        $query = ActivityLog::where('user_id', $admin->id);

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

        // Filter by model type
        if ($request->filled('model_type') && $request->model_type !== 'all') {
            $query->modelType($request->model_type);
        }

        // Filter by date range
        if ($request->filled('start_date')) {
            $query->where('created_at', '>=', $request->start_date . ' 00:00:00');
        }
        if ($request->filled('end_date')) {
            $query->where('created_at', '<=', $request->end_date . ' 23:59:59');
        }

        $activityLogs = $query->orderBy('created_at', 'desc')->paginate(20);

        // Get distinct model types
        $modelTypes = ActivityLog::where('user_id', $admin->id)
            ->distinct()
            ->pluck('model_type')
            ->filter()
            ->values();

        // Get admin stats
        $stats = [
            'total_actions' => ActivityLog::where('user_id', $admin->id)->count(),
            'created_count' => ActivityLog::where('user_id', $admin->id)->where('action', 'created')->count(),
            'updated_count' => ActivityLog::where('user_id', $admin->id)->where('action', 'updated')->count(),
            'deleted_count' => ActivityLog::where('user_id', $admin->id)->where('action', 'deleted')->count(),
        ];

        return view('admin.activity-logs.admin-detail', compact(
            'admin',
            'activityLogs',
            'modelTypes',
            'stats'
        ));
    }

    /**
     * Show transaction activity for super admin
     */
    public function transactions(Request $request)
    {
        // Check if user is super admin
        if (Auth::user()->role !== 'super_admin') {
            abort(403, 'Unauthorized');
        }

        $query = ActivityLog::where('model_type', 'Transaction')
            ->with('user')
            ->adminsOnly();

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

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

        // Filter by date range
        if ($request->filled('start_date')) {
            $query->where('created_at', '>=', $request->start_date . ' 00:00:00');
        }
        if ($request->filled('end_date')) {
            $query->where('created_at', '<=', $request->end_date . ' 23:59:59');
        }

        $transactionLogs = $query->orderBy('created_at', 'desc')->paginate(25);

        // Get all admins for filter dropdown
        $admins = User::where('role', 'admin')->get();

        // Get transaction summary
        $summary = [
            'total' => ActivityLog::where('model_type', 'Transaction')
                ->adminsOnly()
                ->count(),
            'created' => ActivityLog::where('model_type', 'Transaction')
                ->where('action', 'created')
                ->adminsOnly()
                ->count(),
            'updated' => ActivityLog::where('model_type', 'Transaction')
                ->where('action', 'updated')
                ->adminsOnly()
                ->count(),
            'deleted' => ActivityLog::where('model_type', 'Transaction')
                ->where('action', 'deleted')
                ->adminsOnly()
                ->count(),
        ];

        return view('admin.activity-logs.transactions', compact(
            'transactionLogs',
            'admins',
            'summary'
        ));
    }

    /**
     * Export activity logs (CSV)
     */
    public function export(Request $request)
    {
        // Check if user is super admin
        if (Auth::user()->role !== 'super_admin') {
            abort(403, 'Unauthorized');
        }

        $query = ActivityLog::with('user')->adminsOnly();

        // Apply filters
        if ($request->filled('user_id') && $request->user_id !== 'all') {
            $query->where('user_id', $request->user_id);
        }
        if ($request->filled('action')) {
            $query->action($request->action);
        }
        if ($request->filled('model_type') && $request->model_type !== 'all') {
            $query->modelType($request->model_type);
        }
        if ($request->filled('start_date')) {
            $query->where('created_at', '>=', $request->start_date . ' 00:00:00');
        }
        if ($request->filled('end_date')) {
            $query->where('created_at', '<=', $request->end_date . ' 23:59:59');
        }

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

        // Generate CSV
        $filename = 'activity-logs-' . now()->format('Y-m-d-His') . '.csv';
        $headers = [
            'Content-Type' => 'text/csv; charset=utf-8',
            'Content-Disposition' => 'attachment; filename="' . $filename . '"',
        ];

        $callback = function () use ($logs) {
            $file = fopen('php://output', 'w');
            fputcsv($file, ['Admin', 'Action', 'Model Type', 'Model ID', 'Description', 'Date', 'Time']);

            foreach ($logs as $log) {
                fputcsv($file, [
                    $log->user->name,
                    ucfirst($log->action),
                    $log->model_type,
                    $log->model_id,
                    $log->description,
                    $log->created_at->format('Y-m-d'),
                    $log->created_at->format('H:i:s'),
                ]);
            }

            fclose($file);
        };

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

    /**
     * Get activity summary
     */
    private function getActivitySummary(Request $request)
    {
        $query = ActivityLog::query();

        if ($request->filled('user_id') && $request->user_id !== 'all') {
            $query->where('user_id', $request->user_id);
        } else {
            $query->adminsOnly();
        }

        if ($request->filled('start_date')) {
            $query->where('created_at', '>=', $request->start_date . ' 00:00:00');
        }
        if ($request->filled('end_date')) {
            $query->where('created_at', '<=', $request->end_date . ' 23:59:59');
        }

        return [
            'total' => $query->count(),
            'created' => (clone $query)->where('action', 'created')->count(),
            'updated' => (clone $query)->where('action', 'updated')->count(),
            'deleted' => (clone $query)->where('action', 'deleted')->count(),
        ];
    }
}
