<?php

namespace App\Http\Controllers;

use App\Repositories\BoxRepository;
use App\Repositories\CompanyRepository;
use App\Repositories\PricingRepository;
use App\Repositories\UserSubscriptionRepository;
use App\Repositories\UserRepository;
use App\UserSubscription;
use Carbon\Carbon;
use Illuminate\Http\Request;

class UserSubscriptionController extends Controller {

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

    public function index(Request $request) {
        //1. Query params

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

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

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

    public function show($id) {
        //1. Retrieve
        try {
            $sub = UserSubscriptionRepository::find($id);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

        //2. Params
        $user_id = $sub->user_id;
        $box_ids = $sub->box_ids;

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

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

    public function create(Request $request) {
        //1. Params

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

        try {
            $data = [
                "pricing_id" => $request->query("pricing_id"),
                "box_id" => $request->query("box_id"),
                "role_id" => $request->query("role_id"),
                "user_id" => $request->query("user_id"),
                "renew" => $request->query("renew"),
                "start_date" => $request->query("start_date"),
                "discount_id" => $request->query("discount_id"),
                "matricula" => $request->query("matricula")
            ];
            //3. Retrieve
            $sub = UserSubscriptionRepository::create($data);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

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

    public function renew(Request $request, $id) {
        //1. query
        $override = $request->query("override") ? (bool)$request->query("override") : false;
        $user_id = UserSubscription::findOrFail($id)->user_id;

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

        //3. renew
        try {
            $data = [
                "pricing_id" => $request->query("pricing_id"),
                "box_id" => $request->query("box_id"),
                "renew" => $request->query("renew"),
                "discount_id" => $request->query("discount_id") ? $request->query("discount_id") : null,
                "override" => $override
            ];
            $pla = UserSubscriptionRepository::renew($id, $data);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

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

    public function update(Request $request, $id) {
        //1. Params
        $user_id = $request->user_id;

        //2. Authorize
        if(!auth()->user()->itsMe($user_id)) {
            $box_id = $request->query("box_id");
            if(!$box_id) return response()->json(["error" => "Please specify box_id."], 400);
            auth()->user()->authorize("box_admin", $box_id);
        }

        //3.  Retrieve
        try {
            $s = UserSubscriptionRepository::update($request->all(), $id);
        }
        catch(\Exception $e) { return $e; };

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

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

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

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

    public function boxOrders(Request $request, $id){
        //1. Params
        $user_id = UserSubscriptionRepository::find($id)->user_id;

        //2. Authorize
        $authorized = false;
        if(!auth()->user()->itsMe($user_id)) {
            foreach(UserSubscriptionRepository::find($id)->box_ids as $id) {
                try {
                    auth()->user()->authorize("box_admin", $id);
                    $authorized = true;
                }
                catch(\Exception $e) {  }

                if($authorized) break;
            }
        }
        else {
            $authorized = true;
        }

        if(!$authorized) return response()->json(["error" => "Not authorized"], 401);

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

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

    public function payUserSubscription(Request $request, $id) {
        //1. Params
        $user_id = UserSubscriptionRepository::find($id)->user_id;
        $payment_type_slug = $request->query('payment_type_slug');
        $start_date = $request->query('start_date');
        $box_id = $request->query('box_id');
        if($start_date!=null) $start_date = Carbon::createFromFormat("Y-m-d H:i:s", $start_date);

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

        try {
            return response()->json(UserSubscriptionRepository::payUserSubscription($id,$payment_type_slug,$box_id,$start_date),200);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); }
    }

    public function cancelUserSubscription(Request $request, $id) {
        //1. params
        $us = UserSubscriptionRepository::find($id);
        $user_id = $us->user_id;
        $company_id = $us->pricing->company_id;

        //2. authorize
        if(!auth()->user()->itsMe($user_id)) {
            auth()->user()->authorize("box_admin", $company_id, ["level" => "all"]);
        }

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

        return response()->json(["message" => $response]);
    }

    public function getUserSubscriptionStatus(Request $request, $id) {
        $us = UserSubscriptionRepository::find($id);
        $user_id = $us->user_id;
        $company_id = $us->pricing->company_id;

        //2. authorize
        if(!auth()->user()->itsMe($user_id)) {
            auth()->user()->authorize("coach", $company_id, ["level" => "all"]);
        }

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

        return response()->json(["status" => $status]);
    }
}
