<?php

namespace App\Http\Controllers\Courses;

use Illuminate\Http\Request;
use App\Models\Courses\Course;
use App\Http\Controllers\Controller;
use App\Models\Courses\CourseReview;
use App\Models\Courses\CourseCategory;
use App\Models\Courses\CourseEnrollment;
use Illuminate\Support\Facades\Validator;
use Barryvdh\Debugbar\Controllers\BaseController;

class AdminController extends BaseController
{
    /**
     * Constructor to add middleware
     */
    public function __construct()
    {
        $this->middleware(['auth', 'admin']);
    }

    /**
     * Courses overview
     */
    public function courses()
    {
        $totalCourses = Course::count();
        $publishedCourses = Course::where('is_published', true)->count();
        $totalStudents = CourseEnrollment::count();
        $totalRevenue = CourseEnrollment::sum('price_paid');

        $recentCourses = Course::with('instructor', 'category')
            ->orderBy('created_at', 'desc')
            ->limit(5)
            ->get();

        $popularCourses = Course::where('is_published', true)
            ->with('instructor', 'category')
            ->orderBy('total_students', 'desc')
            ->limit(5)
            ->get();

        return view('admin.courses.index', compact(
            'totalCourses',
            'publishedCourses',
            'totalStudents',
            'totalRevenue',
            'recentCourses',
            'popularCourses'
        ));
    }

    /**
     * Course list
     */
    public function courseList()
    {
        $courses = Course::with('instructor', 'category')
            ->orderBy('created_at', 'desc')
            ->paginate(10);

        return view('admin.courses.list', compact('courses'));
    }

    /**
     * Approve/unapprove course
     */
    public function toggleCourse($id)
    {
        $course = Course::findOrFail($id);

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

        $status = $course->is_published ? 'approved' : 'unapproved';

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

    /**
     * Feature/unfeature course
     */
    public function toggleFeature($id)
    {
        $course = Course::findOrFail($id);

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

        $status = $course->is_featured ? 'featured' : 'unfeatured';

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

    /**
     * View course details
     */
    public function viewCourse($id)
    {
        $course = Course::with([
            'instructor',
            'category',
            'sections.lessons',
            'enrollments',
            'reviews',
            'coupons'
        ])->findOrFail($id);

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

    /**
     * Categories list
     */
    public function categories()
    {
        $categories = CourseCategory::withCount('courses')
            ->orderBy('name')
            ->paginate(10);

        return view('admin.courses.categories', compact('categories'));
    }

    /**
     * Add category
     */
    public function addCategory(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|min:2|max:255|unique:course_categories,name',
            'icon' => 'nullable|string|max:50',
            'description' => 'nullable|string'
        ]);

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

        CourseCategory::create([
            'name' => $request->input('name'),
            'icon' => $request->input('icon'),
            'description' => $request->input('description'),
            'is_active' => true
        ]);

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

    /**
     * Update category
     */
    public function updateCategory(Request $request, $id)
    {
        $category = CourseCategory::findOrFail($id);

        $validator = Validator::make($request->all(), [
            'name' => 'required|min:2|max:255|unique:course_categories,name,' . $id,
            'icon' => 'nullable|string|max:50',
            'description' => 'nullable|string'
        ]);

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

        $category->update([
            'name' => $request->input('name'),
            'icon' => $request->input('icon'),
            'description' => $request->input('description')
        ]);

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

    /**
     * Toggle category active status
     */
    public function toggleCategory($id)
    {
        $category = CourseCategory::findOrFail($id);

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

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

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

    /**
     * Reviews list
     */
    public function reviews()
    {
        $reviews = CourseReview::with(['enrollment.user', 'enrollment.course'])
            ->orderBy('created_at', 'desc')
            ->paginate(10);

        return view('admin.courses.reviews', compact('reviews'));
    }

    /**
     * Toggle review approval
     */
    public function toggleReview($id)
    {
        $review = CourseReview::findOrFail($id);

        $review->is_approved = !$review->is_approved;
        $review->save();

        $status = $review->is_approved ? 'approved' : 'disapproved';

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

    /**
     * Delete review
     */
    public function deleteReview($id)
    {
        $review = CourseReview::findOrFail($id);
        $review->delete();

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