<?php

namespace App\Http\Controllers;

use App\Services\ExerciseService;
use App\Repositories\ExerciseRepository;
use Illuminate\Http\Request;

class ExerciseController extends Controller
{
    protected $exerciseService;
    protected $exerciseRepo;

    public function __construct(ExerciseService $exerciseService, ExerciseRepository $exerciseRepo)
    {
        $this->exerciseService = $exerciseService;
        $this->exerciseRepo = $exerciseRepo;
    }

    public function index(Request $request)
    {
        $category = $request->get('category');
        $exercises = $category
            ? $this->exerciseRepo->findByField('category', $category)
            : $this->exerciseService->getAllExercises();

        return view('exercises.index', compact('exercises', 'category'));
    }

    public function show($slug)
    {
        $exercise = $this->exerciseService->getExerciseBySlug($slug);
        if ($exercise->is_premium && !auth()->user()->isPremium()) {
            return redirect()->route('subscription')->with('error', 'This is a premium exercise.');
        }
        return view('exercises.show', compact('exercise'));
    }
}
