<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Event;
use App\Models\User;
use App\Models\EventInterest;
use App\Models\EventAttendee;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Carbon\Carbon;

class EventManagementController extends Controller
{
    /**
     * Display a listing of the events.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $query = Event::with(['creator']);

        // Apply filters
        if ($request->filled('status')) {
            if ($request->status === 'upcoming') {
                $query->where('start_date', '>=', Carbon::now());
            } elseif ($request->status === 'past') {
                $query->where('start_date', '<', Carbon::now());
            } elseif ($request->status === 'active') {
                $query->where('active', true);
            } elseif ($request->status === 'inactive') {
                $query->where('active', false);
            }
        }

        if ($request->filled('featured')) {
            $query->where('is_featured', $request->featured === 'yes');
        }

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('title', 'like', "%{$search}%")
                  ->orWhere('description', 'like', "%{$search}%")
                  ->orWhere('location', 'like', "%{$search}%");
            });
        }

        // Apply ordering
        if ($request->filled('order_by')) {
            $direction = $request->filled('order_direction') ? $request->order_direction : 'desc';
            $query->orderBy($request->order_by, $direction);
        } else {
            $query->orderBy('start_date', 'desc');
        }

        $events = $query->paginate(15);

        // Get counts for cards
        $totalEvents = Event::count();
        $upcomingEvents = Event::where('start_date', '>=', Carbon::now())->count();
        $pastEvents = Event::where('start_date', '<', Carbon::now())->count();
        $featuredEvents = Event::where('is_featured', true)->count();

        return view('admin.pages.event_management.index', compact(
            'events', 
            'totalEvents', 
            'upcomingEvents', 
            'pastEvents', 
            'featuredEvents'
        ));
    }

    /**
     * Display the specified event.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $event = Event::with(['creator', 'attendees', 'interests'])->findOrFail($id);
        
        // Get attendees with users
        $attendees = EventAttendee::with('user')
            ->where('event_id', $id)
            ->latest()
            ->get();
            
        // Get interests with users
        $interests = EventInterest::with('user')
            ->where('event_id', $id)
            ->latest()
            ->get();
        
        return view('admin.pages.event_management.show', compact('event', 'attendees', 'interests'));
    }

    /**
     * Toggle the featured status of the specified event.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function toggleFeatured($id)
    {
        $event = Event::findOrFail($id);
        $event->is_featured = !$event->is_featured;
        $event->save();
        
        $status = $event->is_featured ? 'featured' : 'unfeatured';
        
        return back()->with('success', "Event has been {$status}");
    }

    /**
     * Update the status of the specified event.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function updateStatus(Request $request, $id)
    {
        $event = Event::findOrFail($id);
        $event->active = !$event->active;
        $event->save();
        
        $status = $event->active ? 'activated' : 'deactivated';
        
        return back()->with('success', "Event has been {$status}");
    }

    /**
     * Display a listing of featured events.
     *
     * @return \Illuminate\Http\Response
     */
    public function featured()
    {
        $featuredEvents = Event::with(['creator'])
            ->where('is_featured', true)
            ->withCount(['attendees', 'interests'])
            ->latest('start_date')
            ->paginate(12);
            
        // Get suggested events to feature (active, upcoming, not featured, with most attendees)
        $suggestedEvents = Event::with(['creator'])
            ->where('active', true)
            ->where('is_featured', false)
            ->where('start_date', '>=', Carbon::now())
            ->withCount(['attendees', 'interests'])
            ->orderBy('attendees_count', 'desc')
            ->take(5)
            ->get();
            
        return view('admin.pages.event_management.featured', compact('featuredEvents', 'suggestedEvents'));
    }

    /**
     * Display event statistics.
     *
     * @return \Illuminate\Http\Response
     */
    public function statistics()
    {
        // Get basic stats
        $totalEvents = Event::count();
        $upcomingEvents = Event::where('start_date', '>=', Carbon::now())->count();
        $pastEvents = Event::where('start_date', '<', Carbon::now())->count();
        $featuredEvents = Event::where('is_featured', true)->count();
        $totalAttendees = EventAttendee::count();
        $totalInterests = EventInterest::count();
        
        // Events by month (last 12 months)
        $eventsByMonth = [];
        $pastEvents = [];
        $upcomingEvents = [];
        
        for ($i = 11; $i >= 0; $i--) {
            $date = Carbon::now()->subMonths($i);
            $month = $date->format('M Y');
            
            $pastCount = Event::whereYear('start_date', $date->year)
                ->whereMonth('start_date', $date->month)
                ->where('start_date', '<', Carbon::now())
                ->count();
                
            $upcomingCount = Event::whereYear('start_date', $date->year)
                ->whereMonth('start_date', $date->month)
                ->where('start_date', '>=', Carbon::now())
                ->count();
                
            $eventsByMonth[] = $month;
            $pastEvents[] = $pastCount;
            $upcomingEvents[] = $upcomingCount;
        }
        
        // Top events by attendees
        $topEventsByAttendees = Event::withCount('attendees')
            ->orderBy('attendees_count', 'desc')
            ->take(5)
            ->get()
            ->map(function ($event) {
                return [
                    'title' => $event->title,
                    'count' => $event->attendees_count,
                ];
            })
            ->toArray();
            
        // Top events by interests
        $topEventsByInterests = Event::withCount('interests')
            ->orderBy('interests_count', 'desc')
            ->take(5)
            ->get()
            ->map(function ($event) {
                return [
                    'title' => $event->title,
                    'count' => $event->interests_count,
                ];
            })
            ->toArray();
            
        // Events by day of week
        $eventsByDayOfWeek = [
            'Monday' => 0,
            'Tuesday' => 0,
            'Wednesday' => 0,
            'Thursday' => 0,
            'Friday' => 0,
            'Saturday' => 0,
            'Sunday' => 0,
        ];
        
        $events = Event::all();
        foreach ($events as $event) {
            $dayOfWeek = Carbon::parse($event->start_date)->format('l');
            $eventsByDayOfWeek[$dayOfWeek]++;
        }
        
        // Colors for charts
        $chartColors = [
            '#4e73df', '#1cc88a', '#36b9cc', '#f6c23e', '#e74a3b', 
            '#6f42c1', '#5a5c69', '#858796', '#f8f9fc', '#d1d3e2'
        ];
        
        // Top 10 events for table
        $topEvents = Event::with(['creator'])
            ->withCount(['attendees', 'interests'])
            ->orderBy('attendees_count', 'desc')
            ->take(10)
            ->get();
            
        return view('admin.pages.event_management.statistics', compact(
            'totalEvents',
            'upcomingEvents',
            'pastEvents',
            'featuredEvents',
            'totalAttendees',
            'totalInterests',
            'eventsByMonth',
            'pastEvents',
            'upcomingEvents',
            'topEventsByAttendees',
            'topEventsByInterests',
            'eventsByDayOfWeek',
            'chartColors',
            'topEvents'
        ));
    }

    /**
     * Remove the specified event from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $event = Event::findOrFail($id);
        
        // Delete event image if exists
        if ($event->image && Storage::exists('public/' . $event->image)) {
            Storage::delete('public/' . $event->image);
        }
        
        // Delete related records
        EventAttendee::where('event_id', $id)->delete();
        EventInterest::where('event_id', $id)->delete();
        
        $event->delete();
        
        return redirect()->route('admin.events.index')
            ->with('success', 'Event deleted successfully');
    }
} 