<?php

namespace App\Http\Controllers;

use App\Repositories\BoxProductRepository;
use App\Repositories\BoxRepository;
use App\Repositories\BusinessIntelligenceRepository;
use App\Repositories\UserSubscriptionRepository;
use Carbon\Carbon;
use Illuminate\Http\Request;

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

    public function dashboard(Request $request) {
        try {
            //1. Query params
            $box_id = ($request->box_id) ? $request->box_id : null;
            $company_id = $request->company_id;

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

            //3. Retrieve
            $params = [
                "company_id" => $request->company_id,
                "box_id" => $request->box_id,
                "data_ini" => $request->has('data_ini') ? $request->data_ini : Carbon::createFromFormat('Y-m-d', '1990-01-01')->toDateString(),
                "data_fi" => $request->has('data_fi') ? Carbon::create($request->data_fi)->addDay()->toDateString() : Carbon::tomorrow()->format('Y-m-d')
            ];
            $result = BusinessIntelligenceRepository::getDashboardInfo(auth()->user()->id,$params);

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

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

    public function billing(Request $request) {
        try {
            //1. Query params
            $box_id = ($request->box_id) ? $request->box_id : null;
            $company_id = $request->company_id;

            //2. Authorize
            if ($box_id) auth()->user()->authorize("box_admin", $box_id);
            auth()->user()->authorize("company_admin", $company_id);

            //3. Retrieve
            $params = [
                "company_id" => $request->company_id,
                "box_id" => $request->box_id,
                "data_ini" => $request->has('data_ini') ? $request->data_ini : Carbon::createFromFormat('Y-m-d', '1990-01-01')->toDateString(),
                "data_fi" => $request->has('data_fi') ? Carbon::create($request->data_fi)->addDay()->toDateString() : Carbon::tomorrow()->format('Y-m-d')
            ];
            $result = BusinessIntelligenceRepository::getBillingInfo(auth()->user()->id,$params);

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

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

    public function orders(Request $request) {
        try {
            //1. Query params
            $box_id = ($request->box_id) ? $request->box_id : null;
            $company_id = $request->company_id;

            //2. Authorize
            if ($box_id) auth()->user()->authorize("box_admin", $box_id);
            else auth()->user()->authorize("company_admin", $company_id);

            //3. Retrieve
            $params = [
                "company_id" => $request->company_id,
                "box_id" => $request->box_id,
                "data_ini" => $request->has('data_ini') ? $request->data_ini : Carbon::createFromFormat('Y-m-d', '1990-01-01')->toDateString(),
                "data_fi" => $request->has('data_fi') ? Carbon::create($request->data_fi)->addDay()->toDateString() : Carbon::tomorrow()->format('Y-m-d'),
                "sort_dir" => $request->has('sort_dir') ? $request->sort_dir : 'id' ,
                "sort_col" => $request->has('sort_col') ? $request->sort_col : 'desc',
                "paid_filter" => $request->has('paid_filter') ? $request->paid_filter : false
            ];
            $result = BusinessIntelligenceRepository::getBoxOrdersInfo(auth()->user()->id,$params);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

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

    public function assists(Request $request) {
        try {
            //1. Query params
            $box_id = ($request->box_id) ? $request->box_id : null;
            $company_id = $request->company_id;

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

            //3. Retrieve
            $params = [
                "company_id" => $request->company_id,
                "box_id" => $request->box_id,
                "user_id" => $request->user_id,
                "data_ini" => $request->has('data_ini') ? $request->data_ini : Carbon::createFromFormat('Y-m-d', '1990-01-01')->toDateString(),
                "data_fi" => $request->has('data_fi') ? Carbon::create($request->data_fi)->addDay()->toDateString() : Carbon::tomorrow()->format('Y-m-d'),
            ];
            $result = BusinessIntelligenceRepository::getAssists(auth()->user()->id,$params);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

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

    public function workout(Request $request) {
        try {
            //1. Query params
            $box_id = ($request->box_id) ? $request->box_id : null;
            $company_id = $request->company_id;

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

            //3. Retrieve
            $params = [
                "company_id" => $request->company_id,
                "box_id" => $request->box_id,
                "workout_id" => $request->workout_id
            ];
            $result = BusinessIntelligenceRepository::getWorkout(auth()->user()->id,$params);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

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

    public function workouts(Request $request) {
        try {
            //1. Query params
            $box_id = ($request->box_id) ? $request->box_id : null;
            $company_id = $request->company_id;

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

            //3. Retrieve
            $params = [
                "company_id" => $request->company_id,
                "box_id" => $request->box_id,
                "user_id" => $request->user_id,
                "sort_dir" => $request->has('sort_dir') ? $request->sort_dir : 'id' ,
                "sort_col" => $request->has('sort_col') ? $request->sort_col : 'desc',
                "name_filter" => $request->has('name_filter') ? $request->name_filter : '',
                "category_filter" => $request->has('category_filter') ? $request->category_filter : '',
                "box_filter" => $request->has('box_filter') ? $request->box_filter : false
            ];
            $result = BusinessIntelligenceRepository::getWorkouts(auth()->user()->id,$params);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

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

    public function trainingSessions(Request $request) {
        try {
            //1. Query params
            $box_id = $request->box_id;

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

            //3. Retrieve
            $params = [
                "box_id" => $request->box_id,
                "data" => $request->has('data') ? $request->data : Carbon::now()->toDateString(),
            ];

            $result = BusinessIntelligenceRepository::getTrainingSessions(auth()->user()->id,$params);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

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

    public function trainingSessionsUser($user_id, Request $request) {
        try {
            //1. Query params
            $box_id = $request->box_id;

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

            //3. Retrieve
            $params = [
                "box_id" => $request->box_id,
                "sort_dir" => $request->has('sort_dir') ? $request->sort_dir : 'ASC' ,
                "sort_col" => $request->has('sort_col') ? $request->sort_col : 'id',
                "data_ini" => $request->has('data_ini') ? $request->data_ini : Carbon::createFromFormat('Y-m-d', '1990-01-01')->toDateString(),
                "data_fi" => $request->has('data_fi') ? Carbon::create($request->data_fi)->addDay()->toDateString() : Carbon::tomorrow()->format('Y-m-d'),
            ];

            $result = BusinessIntelligenceRepository::getTrainingSessionsUser(auth()->user()->id,$params);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

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

    public function exercisesUser($user_id, Request $request) {
        try {
            //1. Query params
            $box_id = $request->box_id;

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

            //3. Retrieve
            $params = [
                "box_id" => $request->box_id,
                "sort_dir" => $request->has('sort_dir') ? $request->sort_dir : 'ASC' ,
                "sort_col" => $request->has('sort_col') ? $request->sort_col : 'name',
                "name" => $request->has('name') ? $request->name : null,
                "lvl" => $request->has('lvl') ? $request->lvl : null,
                "data_ini" => $request->has('data_ini') ? $request->data_ini : Carbon::createFromFormat('Y-m-d', '1990-01-01')->toDateString(),
                "data_fi" => $request->has('data_fi') ? Carbon::create($request->data_fi)->addDay()->toDateString() : Carbon::tomorrow()->format('Y-m-d'),
            ];

            $result = BusinessIntelligenceRepository::getExercisesUser(auth()->user()->id,$params);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

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

    public function workoutsUser($user_id, Request $request) {
        try {
            //1. Query params
            $box_id = $request->box_id;

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

            //3. Retrieve
            $params = [
                "box_id" => $request->box_id,
                "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 : null,
                "data_ini" => $request->has('data_ini') ? $request->data_ini : Carbon::createFromFormat('Y-m-d', '1990-01-01')->toDateString(),
                "data_fi" => $request->has('data_fi') ? Carbon::create($request->data_fi)->addDay()->toDateString() : Carbon::tomorrow()->format('Y-m-d'),
            ];

            $result = BusinessIntelligenceRepository::getWorkoutsUser(auth()->user()->id,$params);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

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

    public function categories() {
        try {
            $result = BusinessIntelligenceRepository::getCategories();
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

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

    public function mobileAppHome(Request $request) {
        //1. params
        $user_id = $request->query("user_id");
        $box_id = $request->query("box_id");
        $user_subscription_id = $request->query("user_subscription_id");

        //2. authorize
        if(!auth()->user()->itsMe($user_id)) {
            auth()->user()->authorize("coach", $box_id);
        }

        //3. get
        try {
            $status = UserSubscriptionRepository::status($user_subscription_id); //integer
            $last_new = BoxRepository::getLastNew($box_id);
            $last_session_benchmark = BoxRepository::lastSessionBenchmark($box_id, $user_id, ["days" => 2]);
            $next_training_session = BoxRepository::nextTrainingSession($box_id, $user_id, ["days" => 2]);
            $should_train_more = BoxRepository::shouldTrainMore($box_id, $user_id); //bool
            $birthdays = BoxRepository::birthdays($box_id);

            $data = [
                "status" => $status,
                "last_new" => $last_new,
                "last_session_benchmark" => $last_session_benchmark,
                "next_training_session" => $next_training_session,
                "should_train_more" => $should_train_more,
                "birthdays" => $birthdays
            ];
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

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