<?php

namespace App\Http\Controllers\SuperAdmin;

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

class UserActivityController extends Controller
{
    /**
     * Display the activity log page.
     */
    public function index(Request $request)
    {
        // Get all users for filter dropdown
        $users = User::orderBy('name')->get();

        // Get activity statistics
        $stats = $this->getActivityStats();

        return view('superadmin.activity.index', compact('users', 'stats'));
    }

    /**
     * Get activities list for DataTable
     */
    public function list(Request $request)
    {
        $query = UserActivity::with('user')
            ->lastDays(30)
            ->orderBy('created_at', 'desc');

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

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

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

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

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

        // Handle DataTables search - it passes search as an array with 'value' key
        $searchValue = $request->input('search.value', '');
        if (!empty($searchValue)) {
            $query->where(function ($q) use ($searchValue) {
                $q->where('url', 'like', "%{$searchValue}%")
                    ->orWhere('page_title', 'like', "%{$searchValue}%")
                    ->orWhere('ip_address', 'like', "%{$searchValue}%")
                    ->orWhereHas('user', function ($uq) use ($searchValue) {
                        $uq->where('name', 'like', "%{$searchValue}%")
                            ->orWhere('email', 'like', "%{$searchValue}%");
                    });
            });
        }

        return datatables($query)
            ->only([
                'id', 'user_name', 'user_role', 'page_title', 'activity_badge',
                'method_badge', 'ip_address', 'device_info', 'response_info', 'time_ago'
            ])
            ->addColumn('user_name', function ($activity) {
                return $activity->user->name ?? 'Unknown';
            })
            ->addColumn('user_role', function ($activity) {
                return ucfirst($activity->user->role ?? 'N/A');
            })
            ->addColumn('page_title', function ($activity) {
                return $activity->page_title ?? 'N/A';
            })
            ->addColumn('activity_badge', function ($activity) {
                $class = $activity->type_badge_class;
                $icon = $activity->type_icon;
                return '<span class="badge ' . $class . '"><i class="fas ' . $icon . ' mr-1"></i>' . ucfirst(str_replace('_', ' ', $activity->activity_type)) . '</span>';
            })
            ->addColumn('method_badge', function ($activity) {
                $class = $activity->method_badge_class;
                return '<span class="badge ' . $class . '">' . $activity->method . '</span>';
            })
            ->addColumn('short_url', function ($activity) {
                $url = $activity->url;
                $shortUrl = strlen($url) > 50 ? substr($url, 0, 50) . '...' : $url;
                return '<span title="' . htmlspecialchars($url) . '">' . htmlspecialchars($shortUrl) . '</span>';
            })
            ->addColumn('device_info', function ($activity) {
                $deviceIcon = match($activity->device) {
                    'Mobile' => 'fa-mobile-alt',
                    'Tablet' => 'fa-tablet-alt',
                    default => 'fa-desktop',
                };
                return '<i class="fas ' . $deviceIcon . ' mr-1"></i>' . ($activity->browser ?? 'Unknown');
            })
            ->addColumn('ip_address', function ($activity) {
                return $activity->ip_address ?? 'N/A';
            })
            ->addColumn('formatted_time', function ($activity) {
                return $activity->created_at->format('M d, Y h:i A');
            })
            ->addColumn('time_ago', function ($activity) {
                return $activity->created_at->diffForHumans();
            })
            ->addColumn('response_info', function ($activity) {
                if ($activity->response_status === null) {
                    return '<span class="text-muted">N/A</span>';
                }
                $statusClass = $activity->response_status >= 400 ? 'text-danger' : 'text-success';
                return '<span class="' . $statusClass . '">' . $activity->response_status . '</span>';
            })
            ->rawColumns(['activity_badge', 'method_badge', 'short_url', 'device_info', 'response_info'])
            ->make(true);
    }

    /**
     * Get activity statistics
     */
    protected function getActivityStats(): array
    {
        $now = now();
        $thirtyDaysAgo = $now->copy()->subDays(30);

        // Total activities in last 30 days
        $totalActivities = UserActivity::lastDays(30)->count();

        // Active users in last 30 days
        $activeUsers = UserActivity::lastDays(30)
            ->distinct('user_id')
            ->count('user_id');

        // Today's activities
        $todayActivities = UserActivity::whereDate('created_at', today())->count();

        // Activity by type
        $activityByType = UserActivity::lastDays(30)
            ->select('activity_type', DB::raw('count(*) as count'))
            ->groupBy('activity_type')
            ->pluck('count', 'activity_type')
            ->toArray();

        // Activity by method
        $activityByMethod = UserActivity::lastDays(30)
            ->select('method', DB::raw('count(*) as count'))
            ->groupBy('method')
            ->pluck('count', 'method')
            ->toArray();

        // Most active users
        $mostActiveUsers = UserActivity::lastDays(30)
            ->select('user_id', DB::raw('count(*) as activity_count'))
            ->groupBy('user_id')
            ->orderByDesc('activity_count')
            ->limit(5)
            ->with('user:id,name,role')
            ->get();

        // Activity trend (last 7 days)
        $activityTrend = UserActivity::lastDays(7)
            ->select(DB::raw('DATE(created_at) as date'), DB::raw('count(*) as count'))
            ->groupBy('date')
            ->orderBy('date')
            ->pluck('count', 'date')
            ->toArray();

        // Most visited pages
        $mostVisitedPages = UserActivity::lastDays(30)
            ->where('activity_type', 'page_visit')
            ->select('page_title', 'route_name', DB::raw('count(*) as visit_count'))
            ->groupBy('page_title', 'route_name')
            ->orderByDesc('visit_count')
            ->limit(10)
            ->get();

        return [
            'total_activities' => $totalActivities,
            'active_users' => $activeUsers,
            'today_activities' => $todayActivities,
            'activity_by_type' => $activityByType,
            'activity_by_method' => $activityByMethod,
            'most_active_users' => $mostActiveUsers,
            'activity_trend' => $activityTrend,
            'most_visited_pages' => $mostVisitedPages,
        ];
    }

    /**
     * Show activity details
     */
    public function show($id)
    {
        $activity = UserActivity::with('user')->findOrFail($id);

        return response()->json([
            'success' => true,
            'activity' => [
                'id' => $activity->id,
                'user' => [
                    'name' => $activity->user->name,
                    'email' => $activity->user->email,
                    'role' => $activity->user->role,
                ],
                'activity_type' => $activity->activity_type,
                'page_title' => $activity->page_title,
                'url' => $activity->url,
                'route_name' => $activity->route_name,
                'method' => $activity->method,
                'ip_address' => $activity->ip_address,
                'user_agent' => $activity->user_agent,
                'browser' => $activity->browser,
                'platform' => $activity->platform,
                'device' => $activity->device,
                'request_data' => $activity->request_data,
                'response_status' => $activity->response_status,
                'response_time' => $activity->response_time,
                'created_at' => $activity->created_at->format('F d, Y h:i:s A'),
                'time_ago' => $activity->created_at->diffForHumans(),
            ],
        ]);
    }

    /**
     * Get user activity timeline
     */
    public function userTimeline($userId)
    {
        $user = User::findOrFail($userId);

        $activities = UserActivity::where('user_id', $userId)
            ->lastDays(30)
            ->orderBy('created_at', 'desc')
            ->limit(50)
            ->get();

        return response()->json([
            'success' => true,
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'role' => $user->role,
            ],
            'activities' => $activities->map(function ($activity) {
                return [
                    'id' => $activity->id,
                    'type' => $activity->activity_type,
                    'page_title' => $activity->page_title,
                    'url' => $activity->url,
                    'method' => $activity->method,
                    'ip_address' => $activity->ip_address,
                    'device' => $activity->device,
                    'browser' => $activity->browser,
                    'created_at' => $activity->created_at->format('M d, Y h:i A'),
                    'time_ago' => $activity->created_at->diffForHumans(),
                ];
            }),
        ]);
    }

    /**
     * Export activities to Excel
     */
    public function export(Request $request)
    {
        $query = UserActivity::with('user')
            ->lastDays(30)
            ->orderBy('created_at', 'desc');

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

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

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

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

        $activities = $query->get();

        $filename = 'user_activities_' . date('Y-m-d_H-i-s') . '.csv';

        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="' . $filename . '"',
        ];

        $callback = function () use ($activities) {
            $file = fopen('php://output', 'w');

            // Headers
            fputcsv($file, [
                'ID',
                'User Name',
                'User Email',
                'User Role',
                'Activity Type',
                'Page Title',
                'URL',
                'Method',
                'IP Address',
                'Browser',
                'Platform',
                'Device',
                'Response Status',
                'Response Time (ms)',
                'Date/Time',
            ]);

            // Data
            foreach ($activities as $activity) {
                fputcsv($file, [
                    $activity->id,
                    $activity->user->name ?? 'Unknown',
                    $activity->user->email ?? 'N/A',
                    $activity->user->role ?? 'N/A',
                    $activity->activity_type,
                    $activity->page_title,
                    $activity->url,
                    $activity->method,
                    $activity->ip_address,
                    $activity->browser,
                    $activity->platform,
                    $activity->device,
                    $activity->response_status,
                    $activity->response_time,
                    $activity->created_at->format('Y-m-d H:i:s'),
                ]);
            }

            fclose($file);
        };

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

    /**
     * Delete old activities (cleanup)
     */
    public function cleanup(Request $request)
    {
        $days = $request->input('days', 30);

        $deleted = UserActivity::deleteOlderThan($days);

        return response()->json([
            'success' => true,
            'message' => "Successfully deleted {$deleted} activities older than {$days} days.",
            'deleted_count' => $deleted,
        ]);
    }
}
