<?php

namespace App\Http\Controllers\SelfPaced\Dashboard;

use App\Http\Controllers\Controller;
use App\Models\SelfPaced\Course;
use App\Models\SelfPaced\CourseCategory;
use App\Models\User;
use App\Services\SelfPacedService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CourseController extends Controller
{
    public function __construct(protected SelfPacedService $selfPacedService)
    {
        //
    }

    public function index(Request $request)
    {
        $query = Course::with(['category', 'instructor'])
            ->withCount(['enrollments', 'topics', 'examQuestions']);

        // Real-time search
        if ($search = $request->get('search')) {
            $query->where(function ($q) use ($search) {
                $q->where('title', 'like', "%{$search}%")
                  ->orWhere('description', 'like', "%{$search}%");
            });
        }

        // Filter by status
        if ($status = $request->get('status')) {
            $query->where('status', $status);
        }

        // Filter by category
        if ($categoryId = $request->get('category_id')) {
            $query->where('category_id', $categoryId);
        }

        $courses    = $query->latest()->paginate(15)->withQueryString();
        $categories = CourseCategory::ordered()->get();

        if ($request->ajax()) {
            return response()->json([
                'html' => view('self-paced.dashboard.courses.partials.table', compact('courses'))->render(),
                'pagination' => view('self-paced.dashboard.courses.partials.pagination', compact('courses'))->render(),
            ]);
        }

        return view('self-paced.dashboard.courses.index', compact('courses', 'categories'));
    }

    public function create()
    {
        $categories = CourseCategory::ordered()->get();
        $instructors = User::role(['Trainers', 'Manager', 'Super Manager'])->orderBy('name')->get();

        return view('self-paced.dashboard.courses.create', compact('categories', 'instructors'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'title'                      => 'required|string|max:191',
            'description'                => 'required|string',
            'objectives'                 => 'nullable|string',
            'prerequisites'              => 'nullable|string',
            'category_id'                => 'nullable|exists:self_paced_categories,id',
            'instructor_id'              => 'nullable|exists:users,id',
            'fee_amount'                 => 'nullable|numeric|min:0',
            'currency'                   => 'nullable|string|max:10',
            'duration_hours'             => 'nullable|integer|min:0',
            'passing_score'              => 'nullable|integer|min:1|max:100',
            'exam_attempts_allowed'      => 'nullable|integer|min:1',
            'exam_time_limit'            => 'nullable|integer|min:1',
            'exam_questions_per_attempt' => 'nullable|integer|min:1',
            'status'                     => 'nullable|in:draft,published,archived',
            'featured_image'             => 'nullable|image|max:2048',
        ]);

        // Handle featured image upload
        if ($request->hasFile('featured_image')) {
            $validated['featured_image'] = $request->file('featured_image')
                ->store('self-paced/course-images', 'public');
        }

        $course = $this->selfPacedService->createCourse($validated, Auth::id());

        return redirect()
            ->route('self-paced.dashboard.courses.show', $course)
            ->with('success', "Course \"{$course->title}\" created successfully.");
    }

    public function show(Course $course)
    {
        $course->load(['category', 'instructor', 'creator', 'topics.subtopics']);
        $course->loadCount(['enrollments', 'topics', 'examQuestions', 'certificates']);

        $activeEnrollments = $course->enrollments()->where('status', 'active')->count();
        $passedResults     = $course->examResults()->where('passed', true)->count();

        return view('self-paced.dashboard.courses.show', compact('course', 'activeEnrollments', 'passedResults'));
    }

    public function edit(Course $course)
    {
        $categories  = CourseCategory::ordered()->get();
        $instructors = User::role(['Trainers', 'Manager', 'Super Manager'])->orderBy('name')->get();

        return view('self-paced.dashboard.courses.edit', compact('course', 'categories', 'instructors'));
    }

    public function update(Request $request, Course $course)
    {
        $validated = $request->validate([
            'title'                      => 'required|string|max:191',
            'description'                => 'required|string',
            'objectives'                 => 'nullable|string',
            'prerequisites'              => 'nullable|string',
            'category_id'                => 'nullable|exists:self_paced_categories,id',
            'instructor_id'              => 'nullable|exists:users,id',
            'fee_amount'                 => 'nullable|numeric|min:0',
            'currency'                   => 'nullable|string|max:10',
            'duration_hours'             => 'nullable|integer|min:0',
            'passing_score'              => 'nullable|integer|min:1|max:100',
            'exam_attempts_allowed'      => 'nullable|integer|min:1',
            'exam_time_limit'            => 'nullable|integer|min:1',
            'exam_questions_per_attempt' => 'nullable|integer|min:1',
            'status'                     => 'nullable|in:draft,published,archived',
            'featured_image'             => 'nullable|image|max:2048',
            // New payment fields
            'payment_mode'               => 'nullable|in:online,cash,both',
            'registration_fee'           => 'nullable|numeric|min:0',
            'application_fee'            => 'nullable|numeric|min:0',
            'certificate_fee'            => 'nullable|numeric|min:0',
            'certificate_collection_mode' => 'nullable|in:self_download,hardcopy',
            'book_fee'                   => 'nullable|numeric|min:0',
            'book_file'                  => 'nullable|file|mimes:pdf|max:10240',
            'exam_failure_fee'           => 'nullable|numeric|min:0',
        ]);

        if ($request->hasFile('featured_image')) {
            $validated['featured_image'] = $request->file('featured_image')
                ->store('self-paced/course-images', 'public');
        }

        // Handle book file upload
        if ($request->hasFile('book_file')) {
            $file = $request->file('book_file');
            $validated['book_path'] = $file->store('self-paced/course-books', 'private');
            $validated['book_file_name'] = $file->getClientOriginalName();
            $validated['book_file_size'] = $file->getSize();
        }

        $course = $this->selfPacedService->updateCourse($course, $validated, Auth::id());

        return redirect()
            ->route('self-paced.dashboard.courses.show', $course)
            ->with('success', "Course \"{$course->title}\" updated successfully.");
    }

    public function destroy(Course $course)
    {
        try {
            $this->selfPacedService->deleteCourse($course);
        } catch (\RuntimeException $e) {
            if (request()->ajax()) {
                return response()->json(['success' => false, 'message' => $e->getMessage()], 422);
            }
            return back()->with('error', $e->getMessage());
        }

        if (request()->ajax()) {
            return response()->json(['success' => true, 'message' => 'Course deleted successfully.']);
        }

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