<?php

namespace App\Http\Controllers;

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

class ExerciseController extends Controller
{

    public function __construct() {
        $this->middleware('auth:api', ['except' => []]);
    }

    public function index(Request $request) {
        //1. Obtenim query parameters opcionals
        $params = [
            "sort_dir" => $request->has('sort_dir') ? $request->sort_dir : 'ASC' ,
            "sort_col" => $request->has('sort_col') ? $request->sort_col : 'id',
            "name" => $request->has('name') ? $request->name : '',
            "modality" => $request->has('modality') ? explode('/', $request->modality) : ['M','G','W'],
            "exercise_types" => $request->has('exercise_types') ? explode('/', $request->exercise_types) : null,
            "difficulty" => $request->has('difficulty') ? $request->difficulty : 3,
            "equipment" => $request->has('equipment') ? explode('/', $request->equipment) : null,
        ];

        //2. Autoritzem
        //sense autoritzacio, tothom pot veureho

        //3. Executem acció.
        try {
            $exercises = ExerciseRepository::filter($params);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

        return response()->json($exercises, 200);
    }

    public function show($id) {
        //sense autoritzacio, tothom pot veureho

        try {
            $exercise = ExerciseRepository::find($id);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

        return response()->json($exercise, 200);
    }

    public function create(Request $request) {
        auth()->user()->authorize("super_admin");

        try {
            $exercise = ExerciseRepository::create($request->all());
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

        return response()->json($exercise, 200);
    }

    public function update(Request $request, $id) {
        auth()->user()->authorize("super_admin");

        try {
            $exercise = ExerciseRepository::update($request->all(), $id);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

        return response()->json($exercise, 200);
    }

    public function destroy($id) {
        auth()->user()->authorize("super_admin");

        try {
            ExerciseRepository::delete($id);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

        return response()->json(["message" => "Ok"], 200);
    }

    public function benchmarks($id,$id_user) {
        try {
            $exercise = ExerciseRepository::benchmarks($id,$id_user);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

        return response()->json($exercise, 200);
    }
}
