<?php

namespace App\Http\Controllers;

use App\Repositories\BoxRepository;
use App\Repositories\CompanyRepository;
use Illuminate\Http\Request;
use App\Repositories\CalendarTemplateRepository;

class CalendarTemplateController extends Controller{

    /**
     * Pre: --
     * Post: Injecta les dependències de BoxRepository
     */
    public function __construct() {
        $this->middleware('auth:api', ['except' => []]);
    }

    public function index(){
        //1. Query params

        //2. Authorize
        auth()->user()->authorize("super_admin");

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

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

    public function show($id){
        //1. params
        $box_id = CalendarTemplateRepository::box($id)->id;

        //2. Authorize
        auth()->user()->authorize("coach", $box_id);

        //3. Retrieve
        try {
            $calendar = CalendarTemplateRepository::find($id);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

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

    public function update($id,Request $request){
        //1. Params
        $box_id = CalendarTemplateRepository::box($id)->id;

        //2. Authorize
        auth()->user()->authorize("coach", $box_id);

        //3. Retrieve
        try {
            $calendar = CalendarTemplateRepository::update($request->all(), $id);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

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

    public function create(Request $request){
        //1. Params
        $box_id = $request->box_id;

        //2. Authorize
        auth()->user()->authorize("coach", $box_id);

        //3. Retrieve
        try {
            $calendar = CalendarTemplateRepository::create($request->all());
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

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

    public function destroy($id){
        //1. Params
        $box_id = CalendarTemplateRepository::box($id)->id;

        //2. Authorize
        auth()->user()->authorize("coach", $box_id);

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

        return response()->json("Ok",200);
    }

    public function box($id){
        try {
            $box = CalendarTemplateRepository::box($id); //Hem d'obtenir el box igualment, tant per autoritzacio com per resultat JSOn.
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

        auth()->user()->authorize("coach", $box->id);

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