<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Models\Teacher;
use App\Models\Student;
use App\Models\StudentClass;
use App\Models\StudyGuide;
use App\Models\TeacherClass;
use Exception;
use Illuminate\Support\Facades\DB;

class TeacherController extends Controller
{
    /**
     * Display All Teachers.
    */
    public function index()
    {
        try {
            $teachers = Teacher::latest()->get();
            if ($teachers->isEmpty()) {
                return response()->json([
                    // 'validation_errors' => ['not_found' => ['No Data Found!']],
                    'response_status' => 400
                ], 200);
            }
            $data = ['teachers' => $teachers];
            return response()->json([
                'data' => $data,
                'response_status' => 200
            ], 200);
        } catch (Exception $e) {
            return response()->json([
                'validation_errors' => $e->getMessage(),
                'response_status' => 400,
            ], 200);
        }
    }

    /**
     * Update the Allow Teacher
    */
    public function allowTeacher(Request $request, string $id)
    {
        try {

            $teacher = Teacher::select('id','is_allowed')->find($id);
            if(!$teacher){
                return response()->json([
                    'response_status' => 400
                ], 200);
            }
            $teacher->is_allowed = !$teacher->is_allowed;
            $teacher->save();

            $data = ['teacher' => $teacher];
            return response()->json([
                'data' => $data,
                'response_message' => ['success' => ['Teacher Access Updated Successfully!']],
                'response_status' => 200
            ], 200);
        } catch (Exception $e) {
            return response()->json([
                'validation_errors' => $e->getMessage(),
                'response_status' => 400,
            ], 200);
        }
    }

    /**
     * Display all study guides associated with each teacher.
     */
    public function getAllStudyGuide()
    {
        try {
            $studyGuides = StudyGuide::with('teacher')->where('is_active')->latest()->get();

            if ($studyGuides->isEmpty()) {
                return response()->json([
                    'message' => 'No Data Found!',
                    'response_status' => 400
                ], 200);
            }

            $data = ['study_guides' => $studyGuides];

            return response()->json([
                'data' => $data,
                'response_status' => 200
            ], 200);

        } catch (Exception $e) {
            return response()->json([
                'message' => $e->getMessage(),
                'response_status' => 400,
            ], 200);
        }
    }
    
    /**
     * Display All Students.
    */
    public function getStudents()
    {
        try {
            $students = Student::latest()->get();
            if ($students->isEmpty()) {
                return response()->json([
                    // 'validation_errors' => ['not_found' => ['No Data Found!']],
                    'response_status' => 400
                ], 200);
            }
            $data = ['students' => $students];
            return response()->json([
                'data' => $data,
                'response_status' => 200
            ], 200);
        } catch (Exception $e) {
            return response()->json([
                'validation_errors' => $e->getMessage(),
                'response_status' => 400,
            ], 200);
        }
    }

    /**
     * Update the Allow Students
    */
    public function allowStudents(Request $request, string $id)
    {
        try {

            $student = Student::select('id','is_allowed')->find($id);
            if(!$student){
                return response()->json([
                    'response_status' => 400
                ], 200);
            }
            $student->is_allowed = !$student->is_allowed;
            $student->save();

            $data = ['student' => $student];
            return response()->json([
                'data' => $data,
                'response_message' => ['success' => ['Student Access Updated Successfully!']],
                'response_status' => 200
            ], 200);
        } catch (Exception $e) {
            return response()->json([
                'validation_errors' => $e->getMessage(),
                'response_status' => 400,
            ], 200);
        }
    }
    
    // Display All Subscriptions of Students in Admin Panel
    public function studentSubscriptions(Request $request)
    {
        try {
            // Validate incoming request
            $validation = Validator::make($request->all(), [
                'user_id' => 'required',
                'user_role' => 'required',
            ]);

            if ($validation->fails()) {
                return response()->json([
                    'validation_errors' => $validation->messages(),
                    'response_status' => 400,
                ], 200);
            }

            // Extract request data
            $userId = $request->user_id;
            $userRole = $request->user_role;

            // Determine the appropriate table based on user_role
            $userTable = $userRole === 'student' ? 'students' : 'schools';

            // Check if user exists in the corresponding table
            $user = DB::table($userTable)
                ->where('id', $userId)
                ->first();

            if (!$user) {
                return response()->json([
                    'validation_errors' => ['user_not_found' => ['User not found.']],
                    'response_status' => 400,
                ], 200);
            }

            // Fetch subscriptions from the Order table where is_active = 1
            $orders = Order::with('subscription.features')
                ->where('user_id', $userId)
                ->where('role', $userRole)
                ->where('is_active', 1)
                ->get();

            // Check if any orders were found
            if ($orders->isEmpty()) {
                return response()->json([
                    // 'validation_errors' => ['no_active_orders' => ['No active orders found.']],
                    'response_status' => 400,
                ], 200);
            }

            // Now, we need to match the userSubscription table based on user_id and role
            $userSubscriptions = DB::table('user_subscriptions')
                ->where('user_id', $userId)
                ->where('role', $userRole)
                ->get();

            // Add start_date and end_date to the orders from userSubscriptions
            // $orders = $orders->map(function ($order) use ($userSubscriptions) {
            //     // Find matching subscription for this order
            //     $matchingSubscription = $userSubscriptions->firstWhere('user_id', $order->user_id);

            //     if ($matchingSubscription) {
            //         // Add the start_date and end_date from userSubscription
            //         $order->start_date = $matchingSubscription->start_date ?? null;
            //         $order->end_date = $matchingSubscription->end_date ?? null;
            //     } else {
            //         $order->start_date = null;
            //         $order->end_date = null;
            //     }

            //     return $order;
            // });
            
            // Add start_date and end_date to the orders from userSubscriptions
            $orders = $orders->map(function ($order) use ($userSubscriptions) {
                // Find matching subscriptions for this order
                $matchingSubscriptions = $userSubscriptions->where('user_id', $order->user_id);

                // Check if there are any matching subscriptions
                if ($matchingSubscriptions->isNotEmpty()) {
                    // Sort the subscriptions by start_date in descending order (latest first)
                    $latestSubscription = $matchingSubscriptions->sortByDesc('created_at')->first();

                    // Add the start_date and end_date from the latest userSubscription
                    $order->start_date = $latestSubscription->start_date ?? null;
                    $order->end_date = $latestSubscription->end_date ?? null;
                } else {
                    $order->start_date = null;
                    $order->end_date = null;
                }

                return $order;
            });


            $subscriptionHistory = Order::select('is_active', 'subscription_id', 'status')
                ->with(['subscription.userSubscription' => function ($query) use ($userId, $userRole) {
                    // UserSubscription ko filter karein user_id, role, aur email ke hisaab se
                    $query->where('user_id', $userId)
                        ->where('role', $userRole);
                }])
                ->where('user_id', $userId)
                ->where('role', $userRole)
                ->where('status', 'success')
                ->get()
                ->map(function ($order) {
                    return [
                        'subscription_id' => $order->subscription_id,
                        'is_active' => $order->is_active,
                        'payment_status' => $order->status === 'success' ? 'paid' : 'unpaid',
                        'subscription' => [
                            'id' => $order->subscription->id ?? null,
                            'title' => $order->subscription->title ?? null,
                            'duration' => $order->subscription->duration ?? null,
                            'price' => $order->subscription->price ?? null,
                        ],
                        'user_subscription' => [
                            'purchased_at' => $order->subscription->userSubscription->start_date ?? null,
                            'expiry' => $order->subscription->userSubscription->end_date ?? null,
                            'cancelation' => $order->subscription->userSubscription->cancelled_at ?? null,
                            'id' => $order->subscription->userSubscription->id ?? null,
                        ],
                    ];
            });

            // User Details
            $userDetails = StudentClass::select('id','student_id','teacher_id','teacher_class_id','class_id','section','subject_id')->with('teacher:id,first_name,last_name','teacherClass:id,teacher_id,class_id,year,section,subject_id','subject:id,subject_name','classRelation:id,class_name')->where('student_id', $userId)->get();
            // Return the subscriptions and their features
            return response()->json([
                'data' => [
                    'subscriptions' => $orders,
                    'subscriptionHistory' => $subscriptionHistory,
                    'userDetails' => $userDetails
                ],
                'response_status' => 200,
            ], 200);
        } catch (Exception $e) {
            return response()->json([
                'error' => $e->getMessage(),
                'response_status' => 500,
            ], 200);
        }
    }
    
    // Teacher Details with Class,Student Relation
    public function getTeahcherClassesDetails(Request $request)
    {
        try {
            // Validate incoming request
            $validation = Validator::make($request->all(), [
                'teacher_id' => 'required',
            ]);

            if ($validation->fails()) {
                return response()->json([
                    'validation_errors' => $validation->messages(),
                    'response_status' => 400,
                ], 200);
            }

            // Teacher Details
            $teacherDetails = TeacherClass::with(['classRelation:id,class_name', 'subject:id,subject_name'])
                ->where('teacher_id', $request->teacher_id)
                ->get();

            // Count students for each teacher class
            foreach ($teacherDetails as $teacherDetail) {
                $teacherDetail->student_count = $teacherDetail->students()->count();
                unset($teacherDetail->students); // Remove students array.
            }

            return response()->json([
                'data' => [
                    'teacherDetails' => $teacherDetails
                ],
                'response_status' => 200,
            ], 200);
        } catch (Exception $e) {
            return response()->json([
                'error' => $e->getMessage(),
                'response_status' => 500,
            ], 200);
        }
    }

}
