<?php

namespace App\Http\Controllers\Instructor;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Course;
use App\Models\CourseChapter;
use App\Models\Enrollment;

class CourseController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware(['auth', 'role:instructor']);
    }

    /**
     * Display a listing of the instructor's courses.
     *
     * @return \Illuminate\View\View
     */
    public function index()
    {
        $instructor = Auth::user();
        
        $courses = Course::where('instructor_id', $instructor->id)
            ->where('is_active', true)
            ->withCount('enrollments')
            ->orderBy('created_at', 'desc')
            ->get();
        
        return view('instructor.courses.index', compact('courses'));
    }

    /**
     * Display the specified course.
     *
     * @param  int  $id
     * @return \Illuminate\View\View
     */
    public function show($id)
    {
        $instructor = Auth::user();
        
        $course = Course::where('id', $id)
            ->where('instructor_id', $instructor->id)
            ->with(['chapters', 'enrollments.student'])
            ->firstOrFail();
        
        // Get enrolled students count
        $enrolledStudents = $course->enrollments->count();
        
        // Get chapters count
        $totalChapters = $course->chapters->count();
        $publishedChapters = $course->chapters->where('is_published', true)->count();
        
        return view('instructor.courses.show', compact('course', 'enrolledStudents', 'totalChapters', 'publishedChapters'));
    }
}

