<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Course;
use App\Models\Enrollment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Validation\Rule;
use App\Mail\StudentWelcomeMail;

class StudentController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware(['auth', 'role:admin']);
    }

    /**
     * Display a listing of students.
     *
     * @return \Illuminate\View\View
     */
    public function index(Request $request)
    {
        $query = User::where('role', 'student');

        // Search functionality
        if ($request->has('search') && $request->search) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('email', 'like', "%{$search}%")
                  ->orWhere('school_id', 'like', "%{$search}%")
                  ->orWhere('phone', 'like', "%{$search}%");
            });
        }

        $students = $query->orderBy('created_at', 'desc')->paginate(15);

        return view('admin.students.index', compact('students'));
    }

    /**
     * Show the form for creating a new student.
     *
     * @return \Illuminate\View\View
     */
    public function create()
    {
        $courses = Course::where('is_active', true)->orderBy('name')->get();
        return view('admin.students.create', compact('courses'));
    }

    /**
     * Store a newly created student.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'school_id' => 'required|string|max:255|unique:users',
            'phone' => 'nullable|string|max:20',
            'address' => 'nullable|string|max:500',
            'password' => 'required|string|min:8|confirmed',
            'courses' => 'nullable|array',
            'courses.*' => 'exists:courses,id',
        ]);

        $student = null;
        $password = $validated['password'];
        
        DB::transaction(function () use ($validated, &$student) {
            // Create the student user
            $student = User::create([
                'name' => $validated['name'],
                'email' => $validated['email'],
                'school_id' => $validated['school_id'],
                'phone' => $validated['phone'] ?? null,
                'address' => $validated['address'] ?? null,
                'password' => Hash::make($validated['password']),
                'role' => 'student',
                'email_verified_at' => now(),
            ]);

            // Enroll student in selected courses
            if (!empty($validated['courses'])) {
                foreach ($validated['courses'] as $courseId) {
                    Enrollment::create([
                        'student_id' => $student->id,
                        'course_id' => $courseId,
                        'enrollment_date' => now(),
                        'status' => 'active',
                    ]);
                }
            }
        });

        // Send welcome email
        try {
            Mail::to($student->email)->send(new StudentWelcomeMail($student, $password));
        } catch (\Exception $e) {
            // Log error but don't fail the request
            \Log::error('Failed to send welcome email to student: ' . $e->getMessage());
        }

        return redirect()->route('admin.students.index')
            ->with('success', 'Student created successfully with course enrollments! Welcome email sent.');
    }

    /**
     * Display the specified student.
     *
     * @param  int  $id
     * @return \Illuminate\View\View
     */
    public function show($id)
    {
        // Refresh the model to ensure we get the latest data from database
        $student = User::where('role', 'student')->findOrFail($id);
        $student->refresh(); // Reload from database to get latest changes
        $enrollments = Enrollment::where('student_id', $student->id)
            ->with('course.instructor')
            ->orderBy('enrollment_date', 'desc')
            ->get();
        return view('admin.students.show', compact('student', 'enrollments'));
    }

    /**
     * Show the form for editing the specified student.
     *
     * @param  int  $id
     * @return \Illuminate\View\View
     */
    public function edit($id)
    {
        $student = User::where('role', 'student')->findOrFail($id);
        $courses = Course::where('is_active', true)->orderBy('name')->get();
        $enrolledCourseIds = Enrollment::where('student_id', $student->id)
            ->where('status', 'active')
            ->pluck('course_id')
            ->toArray();
        return view('admin.students.edit', compact('student', 'courses', 'enrolledCourseIds'));
    }
    
    /**
     * Update student delivery status.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function updateDeliveryStatus(Request $request, $id)
    {
        $student = User::where('role', 'student')->findOrFail($id);
        
        $validated = $request->validate([
            'item' => 'required|in:t_shirt,cap,id_card,handout_book',
            'status' => 'required|in:pending,on_the_way,delivered,canceled,returned',
            'notes' => 'nullable|string|max:1000',
        ]);
        
        $item = $validated['item'];
        $status = $validated['status'];
        $notes = $validated['notes'] ?? null;
        
        // Update the specific item status
        $student->{$item . '_status'} = $status;
        $student->{$item . '_updated_at'} = now();
        if ($notes !== null) {
            $student->{$item . '_notes'} = $notes;
        }
        
        $student->save();
        
        return redirect()->route('admin.students.show', $student->id)
            ->with('success', ucfirst(str_replace('_', ' ', $item)) . ' status updated successfully!');
    }

    /**
     * Update the specified student.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, $id)
    {
        $student = User::where('role', 'student')->findOrFail($id);

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => ['required', 'string', 'email', 'max:255', Rule::unique('users')->ignore($student->id)],
            'school_id' => ['required', 'string', 'max:255', Rule::unique('users')->ignore($student->id)],
            'phone' => 'nullable|string|max:20',
            'address' => 'nullable|string|max:500',
            'password' => 'nullable|string|min:8|confirmed',
            'courses' => 'nullable|array',
            'courses.*' => 'exists:courses,id',
        ]);

        DB::transaction(function () use ($validated, $student) {
            // Update student information
            $student->name = $validated['name'];
            $student->email = $validated['email'];
            $student->school_id = $validated['school_id'];
            $student->phone = $validated['phone'] ?? null;
            $student->address = $validated['address'] ?? null;

            if (!empty($validated['password'])) {
                $student->password = Hash::make($validated['password']);
            }

            $student->save();

            // Update course enrollments
            $selectedCourses = $validated['courses'] ?? [];
            $currentEnrollments = Enrollment::where('student_id', $student->id)
                ->where('status', 'active')
                ->pluck('course_id')
                ->toArray();

            // Remove enrollments that are no longer selected
            $coursesToRemove = array_diff($currentEnrollments, $selectedCourses);
            if (!empty($coursesToRemove)) {
                Enrollment::where('student_id', $student->id)
                    ->whereIn('course_id', $coursesToRemove)
                    ->update(['status' => 'dropped']);
            }

            // Add new enrollments
            $coursesToAdd = array_diff($selectedCourses, $currentEnrollments);
            foreach ($coursesToAdd as $courseId) {
                // Check if enrollment already exists (even if dropped)
                $existing = Enrollment::where('student_id', $student->id)
                    ->where('course_id', $courseId)
                    ->first();

                if ($existing) {
                    $existing->update([
                        'status' => 'active',
                        'enrollment_date' => now(),
                    ]);
                } else {
                    Enrollment::create([
                        'student_id' => $student->id,
                        'course_id' => $courseId,
                        'enrollment_date' => now(),
                        'status' => 'active',
                    ]);
                }
            }
        });

        return redirect()->route('admin.students.index')
            ->with('success', 'Student updated successfully with course enrollments!');
    }

    /**
     * Remove the specified student.
     *
     * @param  int  $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy($id)
    {
        $student = User::where('role', 'student')->findOrFail($id);
        $student->delete();

        return redirect()->route('admin.students.index')
            ->with('success', 'Student deleted successfully!');
    }
}

