<?php

namespace App\Http\Controllers;

use App\Models\Member;
use App\Models\Visitor;
use App\Models\MeetingSchedule;
use App\Models\Month;
use App\Models\Payment;
use Illuminate\Http\Request;
use Carbon\Carbon;

class DashboardController extends Controller
{
    /**
     * Show the dashboard with winner stats, meetings, and visitor information
     */
    public function index()
    {
        // Get current month's top referrer
        $topReferrersCurrent = Member::getCurrentMonthTopReferrer();

        // Get all months' top referrers (historical)
        $topReferersByMonth = Member::getTopReferrersByMonth();

        // Get current month details for stats
        $currentMonth = Month::getCurrentMonth();

        // Dashboard statistics
        $dashboardStats = $this->getDashboardStats($currentMonth);

        // Upcoming meetings (next 5 meetings)
        $upcomingMeetings = MeetingSchedule::where('status', 'scheduled')
            ->orderBy('meeting_date', 'asc')
            ->limit(5)
            ->get();

        // Recent visitor activity (last 10 visitors)
        $recentVisitors = Visitor::with(['referredBy', 'paidTo'])
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get();

        // Current month visitor stats
        $visitorStats = $this->getVisitorStats($currentMonth);

        // Top referrer's visitors this month
        $topReferrerVisitors = null;
        if ($topReferrersCurrent) {
            $topReferrerVisitors = $this->getTopReferrerVisitorsThisMonth($topReferrersCurrent, $currentMonth);
        }

        // Monthly comparison data
        $monthlyComparison = $this->getMonthlyComparison();

        return view('dashboard', compact(
            'topReferrersCurrent',
            'topReferersByMonth',
            'currentMonth',
            'dashboardStats',
            'upcomingMeetings',
            'recentVisitors',
            'visitorStats',
            'topReferrerVisitors',
            'monthlyComparison'
        ));
    }

    /**
     * Get dashboard statistics for the current or specified month
     */
    private function getDashboardStats($month = null)
    {
        $month = $month ?? Month::getCurrentMonth();

        // if (!$month) {
        //     return [
        //         'total_visitors' => Visitor::count(),
        //         'paid_by_member' => Visitor::where('paid_by', 'member')->count(),
        //         'paid_by_visitor' => Visitor::where('paid_by', 'visitor')->count(),
        //         'total_referrals' => Visitor::whereNotNull('referred_by_member_id')->count(),
        //         'total_revenue' => Visitor::sum('amount') ?? 0,
        //     ];
        // }

        $startDate = Carbon::createFromDate($month->year, Carbon::parse($month->name)->month, 1);
        $endDate = $startDate->copy()->endOfMonth();

        return [
            'total_visitors' => Visitor::whereBetween('payment_date', [$startDate, $endDate])->count(),
            'total_revenue' => Visitor::sum('amount') ?? 0,
            'current_month_visitrs' => Visitor::whereBetween('payment_date', [$startDate, $endDate])->count(),
            'total_revenue_by_members' => (Payment::sum('amount') ?? 0) + (Payment::sum('penalty') ?? 0),
            'current_month_revenue_by_members' => (Payment::whereBetween('payment_date', [$startDate, $endDate])->sum('amount') ?? 0) + (Payment::whereBetween('payment_date', [$startDate, $endDate])->sum('penalty') ?? 0),
            'paid_by_member' => Visitor::where('paid_by', 'member')->count(),
            'paid_by_visitor' => Visitor::where('paid_by', 'visitor')->count(),
            


            // 'paid_by_member' => Visitor::where('paid_by', 'member')
            //     ->whereBetween('payment_date', [$startDate, $endDate])
            //     ->count(),
            // 'paid_by_visitor' => Visitor::where('paid_by', 'visitor')
            //     ->whereBetween('payment_date', [$startDate, $endDate])
            //     ->count(),
            'total_referrals' => Visitor::whereNotNull('referred_by_member_id')
                ->whereBetween('payment_date', [$startDate, $endDate])
                ->count(),
            // 'total_revenue' => Visitor::whereBetween('payment_date', [$startDate, $endDate])
            //     ->sum('amount') ?? 0,

        ];
    }

    /**
     * Get visitor statistics for current or specified month
     */
    private function getVisitorStats($month = null)
    {
        $month = $month ?? Month::getCurrentMonth();

        if (!$month) {
            return [
                'pending' => Visitor::where('status', 'pending')->count(),
                'paid' => Visitor::where('status', 'paid')->count(),
                'failed' => Visitor::where('status', 'failed')->count(),
            ];
        }

        $startDate = Carbon::createFromDate($month->year, Carbon::parse($month->name)->month, 1);
        $endDate = $startDate->copy()->endOfMonth();

        return [
            'pending' => Visitor::where('status', 'pending')
                ->whereBetween('payment_date', [$startDate, $endDate])
                ->count(),
            'paid' => Visitor::where('status', 'paid')
                ->whereBetween('payment_date', [$startDate, $endDate])
                ->count(),
            'failed' => Visitor::where('status', 'failed')
                ->whereBetween('payment_date', [$startDate, $endDate])
                ->count(),
        ];
    }

    /**
     * Get all visitors referred by the top referrer this month
     */
    private function getTopReferrerVisitorsThisMonth($topReferrer, $month)
    {
        $month = $month ?? Month::getCurrentMonth();

        if (!$month) {
            return $topReferrer->referredVisitors()
                ->orderBy('payment_date', 'desc')
                ->limit(10)
                ->get();
        }

        $startDate = Carbon::createFromDate($month->year, Carbon::parse($month->name)->month, 1);
        $endDate = $startDate->copy()->endOfMonth();

        return Visitor::where('referred_by_member_id', $topReferrer->id)
            ->whereBetween('payment_date', [$startDate, $endDate])
            ->orderBy('payment_date', 'desc')
            ->limit(10)
            ->get();
    }

    /**
     * Get comparison data for last 6 months
     */
    private function getMonthlyComparison()
    {
        $months = Month::orderBy('year', 'desc')
            ->orderBy('name', 'desc')
            ->limit(6)
            ->get();

        $comparison = [];
        foreach ($months as $month) {
            $startDate = Carbon::createFromDate($month->year, Carbon::parse($month->name)->month, 1);
            $endDate = $startDate->copy()->endOfMonth();

            $comparison[] = [
                'month' => $month->name,
                'year' => $month->year,
                'visitors' => Visitor::whereBetween('payment_date', [$startDate, $endDate])->count(),
                'revenue' => Visitor::whereBetween('payment_date', [$startDate, $endDate])->sum('amount') ?? 0,
            ];
        }

        return array_reverse($comparison);
    }
}
