<?php

namespace App\Http\Controllers\Teacher;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Course;
use App\Models\CourseSession;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;

class TeacherController extends Controller
{
    /**
     * Show teacher dashboard
     */
    public function dashboard()
    {
        $teacher = Auth::user();
        $courses = $teacher->teachingCourses()->with('sessions', 'enrollments')->get();

        $stats = [
            'total_courses' => $courses->count(),
            'total_students' => $courses->sum(function($course) {
                return $course->enrollments()->where('status', 'enrolled')->count();
            }),
            'published_courses' => $courses->where('status', 'published')->count(),
            'draft_courses' => $courses->where('status', 'draft')->count(),
        ];

        return view('teacher.dashboard', compact('courses', 'stats'));
    }

    /**
     * Show all courses for the teacher
     */
    public function courses()
    {
        $teacher = Auth::user();
        $courses = $teacher->teachingCourses()
            ->with('sessions', 'enrollments')
            ->orderBy('created_at', 'desc')
            ->get();

        return view('teacher.courses.index', compact('courses'));
    }

    /**
     * Show form to create a new course
     */
    public function createCourse()
    {
        return view('teacher.courses.create');
    }

    /**
     * Store a new course
     */
    public function storeCourse(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'required|string',
            'level' => 'required|in:beginner,intermediate,advanced',
            'duration_weeks' => 'required|integer|min:1|max:52',
            'price' => 'required|numeric|min:0',
            'max_students' => 'nullable|integer|min:1',
            'start_date' => 'nullable|date|after_or_equal:today',
            'end_date' => 'nullable|date|after:start_date',
            'tags' => 'nullable|string',
            'image' => 'nullable|url',
        ]);

        $validated['teacher_id'] = Auth::id();
        $validated['status'] = 'draft';
        $validated['slug'] = Str::slug($validated['title']);

        if ($request->filled('tags')) {
            $validated['tags'] = array_map('trim', explode(',', $validated['tags']));
        }

        $course = Course::create($validated);

        return redirect()->route('teacher.courses.sessions', $course)
            ->with('success', 'Course created successfully! Now add sessions to your course.');
    }

    /**
     * Show form to edit a course
     */
    public function editCourse(Course $course)
    {
        $this->authorize('update', $course);
        return view('teacher.courses.edit', compact('course'));
    }

    /**
     * Update a course
     */
    public function updateCourse(Request $request, Course $course)
    {
        $this->authorize('update', $course);

        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'required|string',
            'level' => 'required|in:beginner,intermediate,advanced',
            'duration_weeks' => 'required|integer|min:1|max:52',
            'price' => 'required|numeric|min:0',
            'max_students' => 'nullable|integer|min:1',
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date|after:start_date',
            'tags' => 'nullable|string',
            'image' => 'nullable|url',
            'status' => 'required|in:draft,published',
        ]);

        if ($request->filled('tags')) {
            $validated['tags'] = array_map('trim', explode(',', $validated['tags']));
        }

        $course->update($validated);

        return redirect()->route('teacher.courses.index')
            ->with('success', 'Course updated successfully!');
    }

    /**
     * Delete a course
     */
    public function destroyCourse(Course $course)
    {
        $this->authorize('delete', $course);

        $course->delete();

        return redirect()->route('teacher.courses.index')
            ->with('success', 'Course deleted successfully!');
    }

    /**
     * Show sessions for a course
     */
    public function sessions(Course $course)
    {
        $this->authorize('update', $course);

        $sessions = $course->sessions()->orderBy('session_number')->get();

        return view('teacher.courses.sessions', compact('course', 'sessions'));
    }

    /**
     * Show form to create a new session
     */
    public function createSession(Course $course)
    {
        $this->authorize('update', $course);

        $nextSessionNumber = $course->sessions()->max('session_number') + 1;

        return view('teacher.sessions.create', compact('course', 'nextSessionNumber'));
    }

    /**
     * Store a new session
     */
    public function storeSession(Request $request, Course $course)
    {
        $this->authorize('update', $course);

        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'required|string',
            'session_number' => 'required|integer|min:1',
            'content' => 'nullable|string',
            'duration_minutes' => 'required|integer|min:1',
            'is_published' => 'boolean',
        ]);

        $validated['course_id'] = $course->id;
        $validated['is_published'] = $request->has('is_published');

        $session = CourseSession::create($validated);

        return redirect()->route('teacher.courses.sessions', $course)
            ->with('success', 'Session created successfully!');
    }

    /**
     * Show form to edit a session
     */
    public function editSession(CourseSession $session)
    {
        $this->authorize('update', $session->course);

        return view('teacher.sessions.edit', compact('session'));
    }

    /**
     * Update a session
     */
    public function updateSession(Request $request, CourseSession $session)
    {
        $this->authorize('update', $session->course);

        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'required|string',
            'session_number' => 'required|integer|min:1',
            'content' => 'nullable|string',
            'duration_minutes' => 'required|integer|min:1',
            'is_published' => 'boolean',
        ]);

        $validated['is_published'] = $request->has('is_published');

        $session->update($validated);

        return redirect()->route('teacher.courses.sessions', $session->course)
            ->with('success', 'Session updated successfully!');
    }

    /**
     * Delete a session
     */
    public function destroySession(CourseSession $session)
    {
        $this->authorize('update', $session->course);

        $course = $session->course;
        $session->delete();

        return redirect()->route('teacher.courses.sessions', $course)
            ->with('success', 'Session deleted successfully!');
    }

    /**
     * Show materials for a session
     */
    public function materials(CourseSession $session)
    {
        $this->authorize('update', $session->course);

        return view('teacher.sessions.materials', compact('session'));
    }

    /**
     * Store material for a session
     */
    public function storeMaterial(Request $request, CourseSession $session)
    {
        $this->authorize('update', $session->course);

        $validated = $request->validate([
            'type' => 'required|in:text,file,link,video',
            'title' => 'required|string|max:255',
            'content' => 'required|string',
            'order' => 'integer|min:0',
        ]);

        $materials = $session->materials ?? [];
        $materials[] = array_merge($validated, [
            'id' => Str::uuid(),
            'created_at' => now()->toISOString(),
        ]);

        $session->update(['materials' => $materials]);

        return redirect()->route('teacher.sessions.materials', $session)
            ->with('success', 'Material added successfully!');
    }
}
