<?php

namespace App\Http\Controllers;

use App\Repositories\BoxRepository;
use App\Repositories\CompanyRepository;
use App\Repositories\UserRepository;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

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

    public function index(Request $request) {
        //1. Obtenim query parameters opcionals

        //2. Authorize
        //No hi ha autoritzacio perque s'ha de poder buscar a la base de dades d'usuaris. auth()->user()->authorize("super_admin");

        //3. Fetch
        try {
            $users = UserRepository::all($request->query());
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

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

    public function show(Request $request, $id) {
        //1. Params

        //2. Authorize
        //sense autoritzacio tothom loguejat pot veure un usuari

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

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

    //Register in auth controller
    /*public function create(Request $request) {
        auth()->user()->authorize("register-user");

        $user = UserRepository::create($request->all());
        return response()->json($user, 200);
    }*/

    public function update(Request $request, $id) {
        //1. Params

        //2. Authorize
        if(!auth()->user()->itsMe($id)) {
            auth()->user()->authorize("super_admin");
        }

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

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

    public function destroy($id) {
        //1. Params

        //2. Authorize
        if(!auth()->user()->itsMe($id)) {
            auth()->user()->authorize("super_admin");
        }

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

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

    public function sessions(Request $request, $id) {
        //1. Obtenim query parameters opcionals

        //2. Authorize
        if(!auth()->user()->itsMe($id)) {
            auth()->user()->authorize("super_admin");
        }

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

        return response()->json($sessions);
    }

    public function benchmarks(Request $request, $id) {
        //1. Obtenim query parameters opcionals

        //2. Authorize
        //sense autoritzacio

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

        return response()->json($benchmarks);
    }

    public function userSubscriptions(Request $request, $id) {
        //1. Params
        $active = $request->query("active") == "Y";

        //2. Authorize
        if(!auth()->user()->itsMe($id)) {
            auth()->user()->authorize("super_admin");
        }

        try {
            $user_subscriptions = UserRepository::userSubscriptions($id, null, null, ["active" => $active,"company_active" => $active]);
            foreach($user_subscriptions as $sub) {
                if($sub->pricing != null) $sub->company = CompanyRepository::find($sub->pricing->company_id);
            }
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

        return response()->json($user_subscriptions);
    }

    public function boxOrders(Request $request,$id) {
        //1. Obtenim query parameters opcionals

        //2. Authorize
        if(!auth()->user()->itsMe($id)) {
            auth()->user()->authorize("super_admin");
        }

        //3. fetch
        try {
            $orders = UserRepository::boxOrders($id);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

        return response()->json($orders);
    }

    public function favoriteExercises(Request $request,$id) {
        //1. params

        //2. Authorize
        //tothom ho pot veure quins son els meus preferits

        //3. fetch
        try {
            $exercises = UserRepository::favoriteExercises($id);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

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

    public function availableWorkoutSessions(Request $request,$id) {
        //1. Obtenim query parameters opcionals

        try {
            $availableWorkoutSessions = UserRepository::find($id)->availableWorkoutSessions();
            if($availableWorkoutSessions)
                return response()->json($availableWorkoutSessions,200);
            else
                return response()->json(["error" => "No avaliable workouts"], Response::HTTP_NOT_FOUND);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };
    }

    public function availableWorkoutSessionsToLeave($id) {
        try {
            $availableWorkoutSessionsToLeave = UserRepository::find($id)->availableWorkoutSessionsToLeave();
            if($availableWorkoutSessionsToLeave)
                return response()->json($availableWorkoutSessionsToLeave,200);
            else
                return response()->json(["error" => "No avaliable workouts"], Response::HTTP_NOT_FOUND);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };
    }

    public function updateFavoriteWorkout(Request $request,$id,$idWorkout) {

        if(!auth()->user()->itsMe($id)) {
            auth()->user()->authorize("super_admin");
        }

        try {
            $user = UserRepository::find($id)->updateFavoriteWorkout($idWorkout);
            return response()->json($user,200);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };
    }

    public function benchmarksWorkout(Request $request,$id,$idWorkout) {
        try {
            $benchmarks = UserRepository::benchmarksWorkout($id,$idWorkout);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

        return response()->json($benchmarks);
    }

    public function uploadProfileImage(Request $request, $id) {
        //1. parameters

        //2. authorize
        if(!auth()->user()->itsMe($id)) {
            abort(401, "Unauthorized");
        }

        try {
            $user = UserRepository::uploadProfileImage($id, $request->file("photo"));
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

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

    public function updateOneSignalPlayerId(Request $request, $id) {
        try {
            $user = UserRepository::updateOneSignalPlayerId($id,$request->one_signal_player_id);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

        return response()->json($user);
    }
}
