<?php

namespace App\Http\Controllers;

use App\Models\Student;
use App\Models\Teacher;
use App\Models\Trainer;
use App\Models\User;
use App\Models\UserHierarchy;
use Carbon\Carbon;
use Devrabiul\ToastMagic\Facades\ToastMagic;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;

class RoleDataController extends Controller
{
    /**
     * কনস্ট্রাক্টর থেকে ক্ষতিকারক লাইসেন্স চেক লজিকটি সরিয়ে দেওয়া হয়েছে।
     * এখন এটি শুধুমাত্র লগইন করা ইউজারদের অ্যাক্সেস করার অনুমতি দেবে।
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function seniorTeamLeaders()
    {
        $user = Auth::user();
        $data['title'] = "Senior Team Leaders";
        $data['user'] = $user;
        $tls = UserHierarchy::with('user:id,name,phone,avatar,created_at,verified_at')->where('counselor_id', $user->id)->latest()->paginate(25);
        $data['leaders'] = $tls;
        return view('counselor.senior_team_leaders', $data);
    }

    public function teamLeaders()
    {
        $user = Auth::user();
        $data['title'] = "Team Leaders";
        $data['user'] = $user;
        $tls = UserHierarchy::with('user:id,name,phone,avatar,created_at,verified_at')->where('senior_team_leader_id', $user->id)->latest()->paginate(25);
        $data['leaders'] = $tls;
        return view('stl.team_leaders', $data);
    }

    public function trainers()
    {
        $user = Auth::user();
        $data['title'] = "Trainers";
        $data['user'] = $user;
        if ($user->role == 'stl') {
            $tls = UserHierarchy::where('senior_team_leader_id', $user->id)->pluck('user_id')->toArray();
            $data['trainers'] = Trainer::with(['user:id,name,avatar,phone,created_at,verified_at', 'team_leader:id,name'])
                ->whereIn('team_leader_id', $tls)->latest()->paginate(25);
        } else {
            $data['trainers'] = Trainer::with('user:id,name,avatar,phone,created_at,verified_at')->where('team_leader_id', $user->id)->latest()->paginate(25);
        }
        return view('tl.trainers', $data);
    }

    public function teachers()
    {
        $user = Auth::user();
        $data['title'] = "Teachers";
        $data['user'] = $user;
        if ($user->role == 'stl') {
            $tls = UserHierarchy::where('senior_team_leader_id', $user->id)->pluck('user_id')->toArray();
            $data['teachers'] = Teacher::with(['user:id,name,avatar,phone,created_at,verified_at', 'team_leader:id,name'])
                ->whereIn('team_leader_id', $tls)->latest()->paginate(25);
        } else {
            $data['teachers'] = Teacher::with('user:id,name,avatar,phone,created_at,verified_at')->where('team_leader_id', Auth::id())->latest()->paginate(25);
        }
        return view('tl.teachers', $data);
    }

    public function students(Request $request)
    {
        $data['title'] = "Students";
        $user = $request->user();
        $tls = [];

        if ($user->role == 'counselor') {
            $stls = UserHierarchy::where('counselor_id', $user->id)->pluck('user_id')->toArray();
            $tls = UserHierarchy::whereIn('senior_team_leader_id', $stls)->pluck('user_id')->toArray();
        } else if ($user->role == 'stl') {
            $tls = UserHierarchy::where('senior_team_leader_id', $user->id)->pluck('user_id')->toArray();
        } else if ($user->role == 'tl') {
            $tls[] = $user->id;
        }

        $data['user'] = $user;

        if (empty($tls) && !in_array($user->role, ['trainer', 'teacher'])) {
            $data['students'] = new LengthAwarePaginator([], 0, 25);
            return view('students', $data);
        }

        $query = Student::query()->with(['user:id,name,phone,status,avatar,created_at,verified_at', 'trainer:id,name', 'teacher:id,name']);
        
        if ($user->role == 'trainer') {
            $query->where('trainer_id', $user->trainer?->user_id);
        } else if ($user->role == 'teacher') {
            $query->where('teacher_id', $user->teacher?->user_id);
        } else {
            $query->whereIn('team_leader_id', $tls);
        }

        if ($search = $request->input('query')) {
            $query->whereHas('user', function ($q) use ($search) {
                $q->where('id', $search)
                    ->orWhere('phone', 'like', "%$search%");
            });
        }

        $data['students'] = $query->latest()->paginate(25);
        return view('students', $data);
    }

    public function editStudent($id)
    {
        $user = Auth::user();
        $student = User::with('student')->findOrFail($id);
        if ($student->student?->team_leader_id != $user->id) {
            abort(404);
        }
        $data['title'] = "Edit Student";
        $data['student'] = $student;
        $data['trainers'] = Trainer::with('user')->where('team_leader_id', $user->id)->get();
        $data['teachers'] = Teacher::with('user')->where('team_leader_id', $user->id)->get();
        return view('tl.edit_student', $data);
    }

    public function updateStudent(Request $request, $id)
    {
        $user = Auth::user();
        $student = User::with('student')->findOrFail($id);
        if ($student->student?->team_leader_id != $user->id) {
            abort(404);
        }

        $student->student->update([
            'trainer_id' => $request->trainer,
            'teacher_id' => $request->teacher,
        ]);

        ToastMagic::success("Data has been updated");
        return redirect()->route('students');
    }

    public function teamLeads(Request $request)
    {
        $data['title'] = "Team Leads";

        if (!$request->from && !$request->to) {
            $data['leads'] = new LengthAwarePaginator([], 0, 25);
            return view('team-leads', $data);
        }

        $user = $request->user();
        $ids = [];

        if ($user->role == 'counselor') {
            $stls = UserHierarchy::where('counselor_id', $user->id)->pluck('user_id')->toArray();
            $tls = UserHierarchy::whereIn('senior_team_leader_id', $stls)->pluck('user_id')->toArray();
            $students = Student::whereIn('team_leader_id', $tls)->pluck('user_id')->toArray();
            $ids = array_merge($stls, $tls, $students);
        } else if ($user->role == 'stl') {
            $tls = UserHierarchy::where('senior_team_leader_id', $user->id)->pluck('user_id')->toArray();
            $students = Student::whereIn('team_leader_id', $tls)->pluck('user_id')->toArray();
            $ids = array_merge($tls, $students);
        } else if ($user->role == 'tl') {
            $ids = Student::where('team_leader_id', $user->id)->pluck('user_id')->toArray();
        } else if ($user->role == 'trainer') {
            $ids = Student::where('trainer_id', $user->id)->pluck('user_id')->toArray();
        } else if ($user->role == 'teacher') {
            $ids = Student::where('teacher_id', $user->id)->pluck('user_id')->toArray();
        }

        $data['user'] = $user;

        if (empty($ids)) {
            $data['leads'] = new LengthAwarePaginator([], 0, 25);
            return view('team-leads', $data);
        }

        $query = User::query()
            ->with('referer:id,name')
            ->whereBetween('created_at', [Carbon::parse($request->from)->startOfDay(), Carbon::parse($request->to)->endOfDay()]);
        
        if ($request->type) {
            $query->whereNotNull('verified_at');
        } else {
            $query->whereNull('verified_at');
        }
        $query->whereIn('refer_by', $ids);

        $data['leads'] = $query->latest()->paginate(25)->appends($request->query());
        return view('team-leads', $data);
    }
}