<?php

namespace App\Http\Controllers;

use App\Models\Course;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;

class CourseController extends Controller
{
    public function show(Request $request, Course $course): View
    {
        $user = $request->user();

        $course->load(['chapters' => fn ($q) => $q->withCount('cards')]);
        $totalCards = $course->chapters->sum('cards_count');

        $chapterStats = $user->progress()
            ->where('course_id', $course->id)
            ->whereNotNull('chapter_id')
            ->select('chapter_id')
            ->selectRaw('count(*) as total')
            ->selectRaw("sum(case when result = 'correct' then 1 else 0 end) as correct")
            ->groupBy('chapter_id')
            ->get()
            ->keyBy('chapter_id');

        $courseStat = $user->courseStats()->where('course_id', $course->id)->first();
        $coursePercent = $courseStat && $courseStat->total_answered > 0
            ? (int) round($courseStat->correct_answered / $courseStat->total_answered * 100)
            : 0;

        return view('courses.show', compact(
            'course',
            'totalCards',
            'chapterStats',
            'courseStat',
            'coursePercent',
        ));
    }
}
