<?php

namespace App\Http\Controllers;

use App\Models\Course;
use App\Models\CourseCategory;
use App\Models\Teacher;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class CourseController extends Controller
{
    public function index()
    {
        $courses = Course::with(['category', 'teacher'])->latest()->paginate(10);
        return view('admin.courses.index', compact('courses'));
    }

    public function create()
    {
        $categories = CourseCategory::where('is_active', true)->get();
        $teachers = Teacher::where('is_active', true)->get();
        return view('admin.courses.create', compact('categories', 'teachers'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'required|string',
            'meta_title' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string',
            'meta_keywords' => 'nullable|string',
            'category_id' => 'required|exists:course_categories,id',
            'teacher_id' => 'required|exists:teachers,id',
            'level' => 'required|in:beginner,intermediate,advanced',
            'duration_value' => 'required|integer|min:1',
            'duration_type' => 'required|in:hours,days,weeks,months',
            'price_type' => 'required|in:free,paid',
            'price' => 'nullable|required_if:price_type,paid|numeric|min:0',
            'label' => 'nullable|in:new,popular,featured',
            'has_certificate' => 'boolean',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:4048',
            'ratings' => 'nullable|numeric|min:0|max:5',
            'total_students' => 'nullable|integer|min:0',
            'requirements' => 'nullable|string',
            'what_you_learn' => 'nullable|string',
            'is_active' => 'boolean',
            'is_featured' => 'boolean',
        ]);

        $data = $request->all();
  $data['has_certificate'] = $request->has('has_certificate');
    $data['is_active'] = $request->has('is_active');
    $data['is_featured'] = $request->has('is_featured');
        // ✅ Generate unique slug for course
        $slug = Str::slug($request->title);
        $count = Course::where('slug', 'LIKE', "{$slug}%")->count();
        if ($count > 0) {
            $slug .= '-' . ($count + 1);
        }
        $data['slug'] = $slug;

        // ✅ Handle image upload to /public/courses
        if ($request->hasFile('image')) {
            $image = $request->file('image');
            $imageName = time() . '_' . $image->getClientOriginalName();
            $image->move(public_path('courses'), $imageName);
            $data['image'] = 'courses/' . $imageName;
        }

        if ($request->price_type === 'free') {
            $data['price'] = 0;
        }

        Course::create($data);

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

    public function show(Course $course)
    {
        $course->load(['category', 'teacher']);
        return view('admin.courses.show', compact('course'));
    }

    public function edit(Course $course)
    {
        $categories = CourseCategory::where('is_active', true)->get();
        $teachers = Teacher::where('is_active', true)->get();
        return view('admin.courses.edit', compact('course', 'categories', 'teachers'));
    }

    public function update(Request $request, Course $course)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'required|string',
            'meta_title' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string',
            'meta_keywords' => 'nullable|string',
            'category_id' => 'required|exists:course_categories,id',
            'teacher_id' => 'required|exists:teachers,id',
            'level' => 'required|in:beginner,intermediate,advanced',
            'duration_value' => 'required|integer|min:1',
            'duration_type' => 'required|in:hours,days,weeks,months',
            'price_type' => 'required|in:free,paid',
            'price' => 'nullable|required_if:price_type,paid|numeric|min:0',
            'label' => 'nullable|in:new,popular,featured',
            'has_certificate' => 'boolean',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:4048',
            'ratings' => 'nullable|numeric|min:0|max:5',
            'total_students' => 'nullable|integer|min:0',
            'requirements' => 'nullable|string',
            'what_you_learn' => 'nullable|string',
            'is_active' => 'boolean',
            'is_featured' => 'boolean',
        ]);

        $data = $request->all();
  $data['has_certificate'] = $request->has('has_certificate');
    $data['is_active'] = $request->has('is_active'); 
    $data['is_featured'] = $request->has('is_featured');
        // ✅ Update slug only if title changed
        if ($request->title !== $course->title) {
            $slug = Str::slug($request->title);
            $count = Course::where('slug', 'LIKE', "{$slug}%")
                ->where('id', '!=', $course->id)
                ->count();
            if ($count > 0) {
                $slug .= '-' . ($count + 1);
            }
            $data['slug'] = $slug;
        }

        // ✅ Handle image upload to /public/courses
        if ($request->hasFile('image')) {
            if ($course->image && file_exists(public_path($course->image))) {
                unlink(public_path($course->image));
            }

            $image = $request->file('image');
            $imageName = time() . '_' . $image->getClientOriginalName();
            $image->move(public_path('courses'), $imageName);
            $data['image'] = 'courses/' . $imageName;
        }

        if ($request->price_type === 'free') {
            $data['price'] = 0;
        }

        $course->update($data);

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

    public function destroy(Course $course)
    {
        if ($course->image && file_exists(public_path($course->image))) {
            unlink(public_path($course->image));
        }

        $course->delete();

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