<?php

namespace App\Http\Controllers\Courses;

use App\Http\Controllers\Controller;
use App\Models\Courses\Course;
use App\Models\Courses\CourseCategory;
use App\Models\Courses\CourseSection;
use App\Models\Courses\CourseLesson;
use App\Models\Courses\CourseEnrollment;
use App\Models\Courses\CourseReview;
use App\Models\Courses\CourseQuestion;
use App\Models\Courses\CourseCoupon;
use App\Models\Courses\CourseAnnouncement;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class InstructorController extends Controller
{
    /**
     * Constructor to add middleware
     */
    public function __construct()
    {
       // parent::__construct();
    }

    /**
     * Display instructor dashboard
     */
    public function dashboard()
    {
        $userId = Auth::id();

        $courses = Course::where('user_id', $userId)
            ->withCount('enrollments')
            ->get();

        $totalCourses = $courses->count();
        $totalStudents = $courses->sum('total_students');
        $totalRevenue = CourseEnrollment::whereIn('course_id', $courses->pluck('id'))
            ->sum('price_paid');

        $recentEnrollments = CourseEnrollment::whereIn('course_id', $courses->pluck('id'))
            ->with(['user', 'course'])
            ->orderBy('created_at', 'desc')
            ->limit(5)
            ->get();

        $recentReviews = CourseReview::whereHas('enrollment', function ($query) use ($courses) {
            $query->whereIn('course_id', $courses->pluck('id'));
        })
            ->with(['enrollment.user', 'enrollment.course'])
            ->orderBy('created_at', 'desc')
            ->limit(5)
            ->get();

        return view('front_end.pages.courses.instructor.dashboard', compact(
            'courses',
            'totalCourses',
            'totalStudents',
            'totalRevenue',
            'recentEnrollments',
            'recentReviews'
        ));
    }

    /**
     * List all instructor courses
     */
    public function courses()
    {
        $courses = Course::where('user_id', Auth::id())
            ->withCount('enrollments')
            ->orderBy('created_at', 'desc')
            ->paginate(10);

        return view('front_end.pages.courses.instructor.courses', compact('courses'));
    }

    /**
     * Create new course form
     */
    public function createCourse()
    {
        $categories = CourseCategory::where('is_active', true)->get();

        return view('front_end.pages.courses.instructor.create', compact('categories'));
    }

    /**
     * Store new course
     */
    public function storeCourse(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|min:5|max:255',
            'category_id' => 'required|exists:course_categories,id',
            'description' => 'required|min:20',
            'price' => 'required|numeric|min:0',
            'level' => 'required|in:beginner,intermediate,advanced',
            'language' => 'required|string',
            'thumbnail' => 'nullable|image|max:2048',
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        $course = new Course($request->all());
        $course->user_id = Auth::id();
        $course->is_published = false;

        // Handle thumbnail upload
        if ($request->hasFile('thumbnail')) {
            $thumbnailPath = $request->file('thumbnail')->store('courses/thumbnails', 'public');
            $course->thumbnail = $thumbnailPath;
        }

        $course->save();

        return redirect()->route('instructor.courses.edit', $course->id)
            ->with('success', 'Course created successfully. Now you can add sections and lessons.');
    }

    /**
     * Edit course form
     */
    public function editCourse($id)
    {
        $course = Course::where('id', $id)
            ->where('user_id', Auth::id())
            ->with('sections.lessons')
            ->firstOrFail();

        $categories = CourseCategory::where('is_active', true)->get();

        return view('front_end.pages.courses.instructor.edit', compact('course', 'categories'));
    }

    /**
     * Update course
     */
    public function updateCourse(Request $request, $id)
    {
        $course = Course::where('id', $id)
            ->where('user_id', Auth::id())
            ->firstOrFail();

        $validator = Validator::make($request->all(), [
            'title' => 'required|min:5|max:255',
            'category_id' => 'required|exists:course_categories,id',
            'description' => 'required|min:20',
            'price' => 'required|numeric|min:0',
            'discount_price' => 'nullable|numeric|min:0|lt:price',
            'discount_ends_at' => 'nullable|date|after:now',
            'level' => 'required|in:beginner,intermediate,advanced',
            'language' => 'required|string',
            'thumbnail' => 'nullable|image|max:2048',
            'preview_video' => 'nullable|url',
            'requirements' => 'nullable|string',
            'what_you_will_learn' => 'nullable|string',
            'target_audience' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        $course->fill($request->all());

        // Handle thumbnail upload
        if ($request->hasFile('thumbnail')) {
            // Delete old thumbnail
            if ($course->thumbnail) {
                Storage::disk('public')->delete($course->thumbnail);
            }

            $thumbnailPath = $request->file('thumbnail')->store('courses/thumbnails', 'public');
            $course->thumbnail = $thumbnailPath;
        }

        $course->save();

        return back()->with('success', 'Course updated successfully.');
    }

    /**
     * Toggle course published status
     */
    public function togglePublish($id)
    {
        $course = Course::where('id', $id)
            ->where('user_id', Auth::id())
            ->firstOrFail();

        $course->is_published = !$course->is_published;
        $course->save();

        $status = $course->is_published ? 'published' : 'unpublished';

        return back()->with('success', "Course {$status} successfully.");
    }

    /**
     * Add course section
     */
    public function addSection(Request $request, $courseId)
    {
        $course = Course::where('id', $courseId)
            ->where('user_id', Auth::id())
            ->firstOrFail();

        $validator = Validator::make($request->all(), [
            'title' => 'required|min:3|max:255',
            'description' => 'nullable|string'
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        // Get max sort order
        $maxSortOrder = CourseSection::where('course_id', $course->id)
            ->max('sort_order') ?? 0;

        CourseSection::create([
            'course_id' => $course->id,
            'title' => $request->input('title'),
            'description' => $request->input('description'),
            'sort_order' => $maxSortOrder + 1
        ]);

        return back()->with('success', 'Section added successfully.');
    }

    /**
     * Update course section
     */
    public function updateSection(Request $request, $sectionId)
    {
        $section = CourseSection::findOrFail($sectionId);

        // Ensure section belongs to instructor's course
        $course = Course::where('id', $section->course_id)
            ->where('user_id', Auth::id())
            ->firstOrFail();

        $validator = Validator::make($request->all(), [
            'title' => 'required|min:3|max:255',
            'description' => 'nullable|string'
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        $section->update([
            'title' => $request->input('title'),
            'description' => $request->input('description')
        ]);

        return back()->with('success', 'Section updated successfully.');
    }

    /**
     * Delete course section
     */
    public function deleteSection($sectionId)
    {
        $section = CourseSection::findOrFail($sectionId);

        // Ensure section belongs to instructor's course
        $course = Course::where('id', $section->course_id)
            ->where('user_id', Auth::id())
            ->firstOrFail();

        // Check if section has lessons
        if ($section->lessons()->count() > 0) {
            return back()->with('error', 'Cannot delete section with lessons. Please delete lessons first.');
        }

        $section->delete();

        return back()->with('success', 'Section deleted successfully.');
    }

    /**
     * Add lesson form
     */
    public function createLesson($courseId, $sectionId)
    {
        $course = Course::where('id', $courseId)
            ->where('user_id', Auth::id())
            ->firstOrFail();

        $section = CourseSection::where('id', $sectionId)
            ->where('course_id', $course->id)
            ->firstOrFail();

        return view('front_end.pages.courses.instructor.create_lesson', compact('course', 'section'));
    }

    /**
     * Store new lesson
     */
    public function storeLesson(Request $request, $courseId, $sectionId)
    {
        $course = Course::where('id', $courseId)
            ->where('user_id', Auth::id())
            ->firstOrFail();

        $section = CourseSection::where('id', $sectionId)
            ->where('course_id', $course->id)
            ->firstOrFail();

        $validator = Validator::make($request->all(), [
            'title' => 'required|min:3|max:255',
            'description' => 'nullable|string',
            'duration' => 'required|integer|min:1',
            'video_url' => 'nullable|url',
            'content' => 'nullable|string',
            'attachment' => 'nullable|file|max:10240', // 10MB max
            'is_free' => 'boolean',
            'is_published' => 'boolean'
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        // Get max sort order
        $maxSortOrder = CourseLesson::where('section_id', $section->id)
            ->max('sort_order') ?? 0;

        $lesson = new CourseLesson($request->all());
        $lesson->section_id = $section->id;
        $lesson->sort_order = $maxSortOrder + 1;

        // Handle attachment upload
        if ($request->hasFile('attachment')) {
            $attachmentPath = $request->file('attachment')->store('courses/attachments', 'public');
            $lesson->attachment = $attachmentPath;
        }

        $lesson->save();

        // Update course stats
        $course->updateCourseStats();

        return redirect()->route('instructor.courses.edit', $course->id)
            ->with('success', 'Lesson added successfully.');
    }

    /**
     * Edit lesson form
     */
    public function editLesson($courseId, $lessonId)
    {
        $course = Course::where('id', $courseId)
            ->where('user_id', Auth::id())
            ->firstOrFail();

        $lesson = CourseLesson::findOrFail($lessonId);

        // Ensure lesson belongs to instructor's course
        $section = CourseSection::where('id', $lesson->section_id)
            ->where('course_id', $course->id)
            ->firstOrFail();

        return view('front_end.pages.courses.instructor.edit_lesson', compact('course', 'section', 'lesson'));
    }

    /**
     * Update lesson
     */
    public function updateLesson(Request $request, $courseId, $lessonId)
    {
        $course = Course::where('id', $courseId)
            ->where('user_id', Auth::id())
            ->firstOrFail();

        $lesson = CourseLesson::findOrFail($lessonId);

        // Ensure lesson belongs to instructor's course
        $section = CourseSection::where('id', $lesson->section_id)
            ->where('course_id', $course->id)
            ->firstOrFail();

        $validator = Validator::make($request->all(), [
            'title' => 'required|min:3|max:255',
            'description' => 'nullable|string',
            'duration' => 'required|integer|min:1',
            'video_url' => 'nullable|url',
            'content' => 'nullable|string',
            'attachment' => 'nullable|file|max:10240', // 10MB max
            'is_free' => 'boolean',
            'is_published' => 'boolean'
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        $lesson->fill($request->all());

        // Handle attachment upload
        if ($request->hasFile('attachment')) {
            // Delete old attachment
            if ($lesson->attachment) {
                Storage::disk('public')->delete($lesson->attachment);
            }

            $attachmentPath = $request->file('attachment')->store('courses/attachments', 'public');
            $lesson->attachment = $attachmentPath;
        }

        $lesson->save();

        // Update course stats
        $course->updateCourseStats();

        return back()->with('success', 'Lesson updated successfully.');
    }

    /**
     * Delete lesson
     */
    public function deleteLesson($courseId, $lessonId)
    {
        $course = Course::where('id', $courseId)
            ->where('user_id', Auth::id())
            ->firstOrFail();

        $lesson = CourseLesson::findOrFail($lessonId);

        // Ensure lesson belongs to instructor's course
        $section = CourseSection::where('id', $lesson->section_id)
            ->where('course_id', $course->id)
            ->firstOrFail();

        // Delete attachment if exists
        if ($lesson->attachment) {
            Storage::disk('public')->delete($lesson->attachment);
        }

        $lesson->delete();

        // Update course stats
        $course->updateCourseStats();

        return back()->with('success', 'Lesson deleted successfully.');
    }

    /**
     * Reorder sections
     */
    public function reorderSections(Request $request, $courseId)
    {
        $course = Course::where('id', $courseId)
            ->where('user_id', Auth::id())
            ->firstOrFail();

        $sectionOrder = $request->input('sections');

        if (!is_array($sectionOrder)) {
            return response()->json(['error' => 'Invalid data'], 400);
        }

        foreach ($sectionOrder as $index => $sectionId) {
            CourseSection::where('id', $sectionId)
                ->where('course_id', $course->id)
                ->update(['sort_order' => $index]);
        }

        return response()->json(['success' => true]);
    }

    /**
     * Reorder lessons
     */
    public function reorderLessons(Request $request, $sectionId)
    {
        $section = CourseSection::findOrFail($sectionId);

        // Ensure section belongs to instructor's course
        $course = Course::where('id', $section->course_id)
            ->where('user_id', Auth::id())
            ->firstOrFail();

        $lessonOrder = $request->input('lessons');

        if (!is_array($lessonOrder)) {
            return response()->json(['error' => 'Invalid data'], 400);
        }

        foreach ($lessonOrder as $index => $lessonId) {
            CourseLesson::where('id', $lessonId)
                ->where('section_id', $section->id)
                ->update(['sort_order' => $index]);
        }

        return response()->json(['success' => true]);
    }

    /**
     * Manage course announcements
     */
    public function announcements($courseId)
    {
        $course = Course::where('id', $courseId)
            ->where('user_id', Auth::id())
            ->with('announcements')
            ->firstOrFail();

        return view('front_end.pages.courses.instructor.announcements', compact('course'));
    }

    /**
     * Add course announcement
     */
    public function addAnnouncement(Request $request, $courseId)
    {
        $course = Course::where('id', $courseId)
            ->where('user_id', Auth::id())
            ->firstOrFail();

        $validator = Validator::make($request->all(), [
            'title' => 'required|min:3|max:255',
            'content' => 'required|min:10'
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        CourseAnnouncement::create([
            'course_id' => $course->id,
            'title' => $request->input('title'),
            'content' => $request->input('content')
        ]);

        return back()->with('success', 'Announcement added successfully.');
    }

    /**
     * Delete announcement
     */
    public function deleteAnnouncement($id)
    {
        $announcement = CourseAnnouncement::findOrFail($id);

        // Ensure announcement belongs to instructor's course
        $course = Course::where('id', $announcement->course_id)
            ->where('user_id', Auth::id())
            ->firstOrFail();

        $announcement->delete();

        return back()->with('success', 'Announcement deleted successfully.');
    }

    /**
     * Course reviews
     */
    public function reviews($courseId)
    {
        $course = Course::where('id', $courseId)
            ->where('user_id', Auth::id())
            ->firstOrFail();

        $reviews = CourseReview::whereHas('enrollment', function ($query) use ($courseId) {
            $query->where('course_id', $courseId);
        })
            ->with('enrollment.user')
            ->orderBy('created_at', 'desc')
            ->paginate(10);

        return view('front_end.pages.courses.instructor.reviews', compact('course', 'reviews'));
    }

    /**
     * Course questions
     */
    public function questions($courseId)
    {
        $course = Course::where('id', $courseId)
            ->where('user_id', Auth::id())
            ->firstOrFail();

        $questions = CourseQuestion::where('course_id', $courseId)
            ->with(['user', 'lesson', 'answers'])
            ->orderBy('created_at', 'desc')
            ->paginate(10);

        return view('front_end.pages.courses.instructor.questions', compact('course', 'questions'));
    }

    /**
     * Course students
     */
    public function students($courseId)
    {
        $course = Course::where('id', $courseId)
            ->where('user_id', Auth::id())
            ->firstOrFail();

        $enrollments = CourseEnrollment::where('course_id', $courseId)
            ->with('user')
            ->orderBy('created_at', 'desc')
            ->paginate(10);

        return view('front_end.pages.courses.instructor.students', compact('course', 'enrollments'));
    }

    /**
     * Course coupons
     */
    public function coupons($courseId)
    {
        $course = Course::where('id', $courseId)
            ->where('user_id', Auth::id())
            ->with('coupons')
            ->firstOrFail();

        return view('front_end.pages.courses.instructor.coupons', compact('course'));
    }

    /**
     * Add course coupon
     */
    public function addCoupon(Request $request, $courseId)
    {
        $course = Course::where('id', $courseId)
            ->where('user_id', Auth::id())
            ->firstOrFail();

        $validator = Validator::make($request->all(), [
            'code' => 'required|min:3|max:20|unique:course_coupons,code',
            'discount_type' => 'required|in:percentage,fixed',
            'discount_amount' => 'required|numeric|min:1',
            'usage_limit' => 'nullable|integer|min:1',
            'expires_at' => 'nullable|date|after:today',
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        // Validate discount amount based on type
        if ($request->input('discount_type') == 'percentage' && $request->input('discount_amount') > 100) {
            return back()->withErrors(['discount_amount' => 'Percentage discount cannot exceed 100%'])->withInput();
        }

        if ($request->input('discount_type') == 'fixed' && $request->input('discount_amount') > $course->price) {
            return back()->withErrors(['discount_amount' => 'Fixed discount cannot exceed course price'])->withInput();
        }

        CourseCoupon::create([
            'course_id' => $course->id,
            'code' => strtoupper($request->input('code')),
            'discount_type' => $request->input('discount_type'),
            'discount_amount' => $request->input('discount_amount'),
            'usage_limit' => $request->input('usage_limit'),
            'expires_at' => $request->input('expires_at'),
            'is_active' => true
        ]);

        return back()->with('success', 'Coupon added successfully.');
    }

    /**
     * Toggle coupon active status
     */
    public function toggleCoupon($id)
    {
        $coupon = CourseCoupon::findOrFail($id);

        // Ensure coupon belongs to instructor's course
        $course = Course::where('id', $coupon->course_id)
            ->where('user_id', Auth::id())
            ->firstOrFail();

        $coupon->is_active = !$coupon->is_active;
        $coupon->save();

        $status = $coupon->is_active ? 'activated' : 'deactivated';

        return back()->with('success', "Coupon {$status} successfully.");
    }

    /**
     * Delete coupon
     */
    public function deleteCoupon($id)
    {
        $coupon = CourseCoupon::findOrFail($id);

        // Ensure coupon belongs to instructor's course
        $course = Course::where('id', $coupon->course_id)
            ->where('user_id', Auth::id())
            ->firstOrFail();

        $coupon->delete();

        return back()->with('success', 'Coupon deleted successfully.');
    }
}
