<?php

namespace App\Http\Controllers;

use App\Models\Country;
use App\Models\Registration;
use Carbon\Carbon;
use Illuminate\Http\Request;

class HomeController extends Controller
{
    public function index(Request $request)
    {
        $user = auth()->user();

        return match ($user->role) {
            'admin'     => $this->adminDashboard($request),
            'counselor' => $this->counselorDashboard($request),
            default     => abort(403, 'Unauthorized action.'),
        };
    }

    public function adminDashboard(Request $request)
    {
        $today  = Carbon::today();
        $search = trim($request->input('search', ''));

        $query = Registration::with([
            'sessions' => function ($q) use ($today) {
                $q->whereDate('play_date', $today)->with('shots');
            }
        ])
        ->whereHas('sessions', function ($q) use ($today) {
            $q->whereDate('play_date', $today);
        });

        if ($search) {
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('phone', 'like', "%{$search}%")
                  ->orWhere('email', 'like', "%{$search}%");
            });
        }

        $query = $query->orderBy('created_at', 'desc')->paginate(10)->withQueryString();

        $registrations = $query->getCollection()->map(function ($student) {
            $todaySession = $student->sessions->first();
            $todayGoals   = null;
            if ($todaySession) {
                $todayGoals = $todaySession->shots
                    ->sortBy('shot_number')
                    ->map(fn($shot) => (bool) $shot->result)
                    ->values()
                    ->toArray();
            }
            return [
                'id'          => $student->id,
                'name'        => $student->name,
                'phone'       => $student->phone,
                'email'       => $student->email,
                'today_goals' => $todayGoals,
                'total_score' => $student->total_score,
                'session_id'  => $todaySession?->id,
                'country_id'  => $student->country_id,
            ];
        });

        $query->setCollection($registrations);

        $data['registrations'] = $query;
        $data['search']        = $search;
        $data['total']         = Registration::count();
        $data['played']        = $registrations->filter(fn($r) => !empty($r['today_goals']) && count($r['today_goals']) >= 3)->count();
        $data['topScore']      = $registrations->max('total_score') ?? 0;
        $data['countries']     = Country::where('status', 1)->orderBy('title')->get(['id','title','country_flag']);

        return view('dashboard.admin', $data);
    }

    public function counselorDashboard(Request $request)
    {
        $today  = Carbon::today();
        $search = trim($request->input('search', ''));

        $query = Registration::with([
            'sessions' => function ($q) use ($today) {
                $q->whereDate('play_date', $today)->with('shots');
            },
            'comments',
            'country'
        ])
        ->whereHas('sessions', function ($q) use ($today) {
            $q->whereDate('play_date', $today);
        });

        if ($search) {
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('phone', 'like', "%{$search}%")
                  ->orWhere('email', 'like', "%{$search}%");
            });
        }

        $query = $query->orderBy('created_at', 'desc')->paginate(10)->withQueryString();

        $registrations = $query->getCollection()->map(function ($student) {
            $todaySession = $student->sessions->first();
            $todayGoals   = null;
            if ($todaySession) {
                $todayGoals = $todaySession->shots
                    ->sortBy('shot_number')
                    ->map(fn($shot) => (bool) $shot->result)
                    ->values()
                    ->toArray();
            }
            return [
                'id'            => $student->id,
                'name'          => $student->name,
                'phone'         => $student->phone,
                'email'         => $student->email,
                'today_goals'   => $todayGoals,
                'total_score'   => $student->total_score,
                'session_id'    => $todaySession?->id,
                'country_id'    => $student->country_id,
                'country_title' => $student->country?->title ?? '',       // add
                'country_flag'  => $student->country?->country_flag ?? '', // add
                'status'        => $student->status ?? 'warm',             // add if not there
                'comment_count' => $student->comments->count(),
            ];
        });

        $query->setCollection($registrations);

        $data['registrations'] = $query;
        $data['search']        = $search;
        $data['total']         = Registration::count();
        $data['played']        = $registrations->filter(fn($r) => !empty($r['today_goals']) && count($r['today_goals']) >= 3)->count();
        $data['topScore']      = $registrations->max('total_score') ?? 0;
        $data['countries']     = Country::where('status', 1)->orderBy('title')->get(['id','title','country_flag']);

        return view('dashboard.counselor', $data);
    }
}