<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\Courses\Course;
use App\Models\Courses\CourseCategory;
use App\Models\Courses\CourseEnrollment;
use App\Models\Courses\CourseReview;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class CourseController extends Controller
{
    /**
     * Display a listing of the courses for management.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $courses = Course::with('instructor', 'category')
            ->latest()
            ->paginate(15);
        return view('admin.pages.courses.index', compact('courses'));
    }

    /**
     * Display the specified course details.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $course = Course::with(['instructor', 'category', 'sections.lessons', 'enrollments.user', 'reviews.enrollment.user'])
            ->findOrFail($id);
        
        $enrollments = CourseEnrollment::where('course_id', $id)
            ->with('user')
            ->latest()
            ->paginate(10);
            
        return view('admin.pages.courses.show', compact('course', 'enrollments'));
    }

    /**
     * Show the form for creating a new course.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $categories = CourseCategory::where('is_active', true)->get();
        return view('admin.pages.courses.create', compact('categories'));
    }

    /**
     * Store a newly created course.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'category_id' => 'required|exists:course_categories,id',
            'description' => 'required|string',
            'price' => 'required|numeric|min:0',
            'discount_price' => 'nullable|numeric|min:0',
            'discount_ends_at' => 'nullable|date',
            'level' => 'required|in:beginner,intermediate,advanced',
            'language' => 'required|string|max:50',
            'thumbnail' => 'nullable|image|max:2048',
            'preview_video' => 'nullable|url',
            'requirements' => 'nullable|string',
            'what_you_will_learn' => 'nullable|string',
            'target_audience' => 'nullable|string',
        ]);

        $data = $request->except(['is_featured', 'is_published']);
        $data['user_id'] = auth()->id();
        $data['slug'] = Str::slug($request->title);
        $data['is_featured'] = $request->has('is_featured');
        $data['is_published'] = $request->has('is_published');
        
        // Fix discount_price validation - if price is 0, discount_price should be null
        if ($data['price'] == 0) {
            $data['discount_price'] = null;
        } elseif ($data['discount_price'] && $data['discount_price'] >= $data['price']) {
            return redirect()->back()->withInput()->withErrors(['discount_price' => 'Discount price must be less than the regular price.']);
        }
        
        if ($request->hasFile('thumbnail')) {
            $data['thumbnail'] = $request->file('thumbnail')->store('courses/thumbnails', 'public');
        }

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

        return redirect()->route('admin.courses.index')
            ->with('success', 'Course created successfully.');
    }

    /**
     * Show the form for editing the specified course.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $course = Course::findOrFail($id);
        $categories = CourseCategory::where('is_active', true)->get();
        return view('admin.pages.courses.edit', compact('course', 'categories'));
    }

    /**
     * Update the specified course.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $course = Course::findOrFail($id);
        
        $request->validate([
            'title' => 'required|string|max:255',
            'category_id' => 'required|exists:course_categories,id',
            'description' => 'required|string',
            'price' => 'required|numeric|min:0',
            'discount_price' => 'nullable|numeric|min:0',
            'discount_ends_at' => 'nullable|date',
            'level' => 'required|in:beginner,intermediate,advanced',
            'language' => 'required|string|max:50',
            'thumbnail' => 'nullable|image|max:2048',
            'preview_video' => 'nullable|url',
            'requirements' => 'nullable|string',
            'what_you_will_learn' => 'nullable|string',
            'target_audience' => 'nullable|string',
        ]);
        
        $data = $request->except(['is_featured', 'is_published']);
        $data['slug'] = Str::slug($request->title);
        $data['is_featured'] = $request->has('is_featured');
        $data['is_published'] = $request->has('is_published');
        
        // Fix discount_price validation - if price is 0, discount_price should be null
        if ($data['price'] == 0) {
            $data['discount_price'] = null;
        } elseif (isset($data['discount_price']) && $data['discount_price'] >= $data['price']) {
            return redirect()->back()->withInput()->withErrors(['discount_price' => 'Discount price must be less than the regular price.']);
        }
        
        if ($request->hasFile('thumbnail')) {
            // Delete old thumbnail
            if ($course->thumbnail) {
                Storage::disk('public')->delete($course->thumbnail);
            }
            $data['thumbnail'] = $request->file('thumbnail')->store('courses/thumbnails', 'public');
        }

        $course->update($data);

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

    /**
     * Remove the specified course from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $course = Course::findOrFail($id);
        
        // Delete thumbnail if exists
        if ($course->thumbnail) {
            Storage::disk('public')->delete($course->thumbnail);
        }
        
        $course->delete();
        
        return redirect()->route('admin.courses.index')
            ->with('success', 'Course deleted successfully.');
    }

    /**
     * Toggle course published status.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function toggleStatus($id)
    {
        $course = Course::findOrFail($id);
        $course->is_published = !$course->is_published;
        $course->save();

        $statusText = $course->is_published ? 'published' : 'unpublished';
        
        return redirect()->back()
            ->with('success', "Course {$statusText} successfully.");
    }

    /**
     * Toggle course featured status.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function toggleFeatured($id)
    {
        $course = Course::findOrFail($id);
        $course->is_featured = !$course->is_featured;
        $course->save();

        $statusText = $course->is_featured ? 'featured' : 'unfeatured';
        
        return redirect()->back()
            ->with('success', "Course {$statusText} successfully.");
    }

    /**
     * Display course enrollments.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function enrollments($id)
    {
        $course = Course::findOrFail($id);
        $enrollments = CourseEnrollment::where('course_id', $id)
            ->with('user')
            ->latest()
            ->paginate(15);
            
        return view('admin.pages.courses.enrollments', compact('course', 'enrollments'));
    }

    /**
     * Show course statistics for admin dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function stats()
    {
        $totalCourses = Course::count();
        $publishedCourses = Course::where('is_published', true)->count();
        $featuredCourses = Course::where('is_featured', true)->count();
        $totalStudents = CourseEnrollment::count();
        $totalRevenue = CourseEnrollment::sum('price_paid');
        
        // Top categories
        $topCategories = CourseCategory::withCount('courses')
            ->orderByDesc('courses_count')
            ->limit(5)
            ->get();

        // Popular courses
        $popularCourses = Course::where('is_published', true)
            ->with('instructor', 'category')
            ->orderByDesc('total_students')
            ->limit(5)
            ->get();

        return view('admin.pages.courses.stats', compact(
            'totalCourses', 
            'publishedCourses',
            'featuredCourses',
            'totalStudents',
            'totalRevenue',
            'topCategories',
            'popularCourses'
        ));
    }
}

