<?php

namespace App\Http\Controllers;

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

class CompanyController extends Controller
{

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

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

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

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

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

    public function show($id) {
        auth()->user()->authorize("company_admin", $id);

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

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

    public function create(Request $request) {
        //1. Query
        $user = $request->owner;
        $email = $user['email'];
        $password = $user['password'];
        $company = $request->company;
        $plan_id = $request->plan_id;
        $box = $request->box;
        if(!$user || !$company || !$plan_id || !$box) return response()->json(["error" => "Please provide a user, a company, a box and a plan_id"], 400);

        //2. Auth --> tothom pot fer

        //3. Create
        try {
            $company = CompanyRepository::create($company, $user, $box, $plan_id);

            $credentials = ["email" => $email, "password" => $password];
            $token = auth()->attempt($credentials);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        try {
            $discounts = CompanyRepository::discounts($id, $request->query("active"));
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

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

    public function users(Request $request,$id) {
        //1. Obtenim query parameters opcionals
        $active = $request->query('active');

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

        try {
            $users = CompanyRepository::users($id,($active==null ? false : $active));
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

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

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

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

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

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

    public function paymentTypes($id) {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        //2. Authorize
        auth()->user()->authorize("company_admin",$id);

        try {
            $invoices = CompanyRepository::exportCSV($id,$request->get('invoices_id'));
            if ($invoices) {
                return response()->stream($invoices, 200, [
                    'Cache-Control'       => 'must-revalidate, post-check=0, pre-check=0'
                    ,   'Content-type'        => 'text/csv'
                    ,   'Content-Disposition' => 'attachment; filename=galleries.csv'
                    ,   'Expires'             => '0'
                    ,   'Pragma'              => 'public'
                ]);
            } else return response()->json(["error" => "No invoices to export"], Response::HTTP_NOT_FOUND);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); }
    }

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

        //2. authorize
        auth()->user()->authorize("company_admin", $id);

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

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

    public function getStripeUser($id, $user_id) {
        //1. parameters

        //2.  authorize
        if(!auth()->user()->itsMe($user_id)) {
            auth()->user()->authorize("coach", $id, ["level" => "all"]); //que sigui box_admin dins aquesta companyia
        }

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

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

    public function userSubscriptionsByUserId($id, $user_id) {
        //1. parameters

        //2. authorize
        auth()->user()->authorize("coach", $id, ["level" => "all"]);

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

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

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

        //2. authorize
        auth()->user()->authorize("company_admin", $id);

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

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

    public function subscriptionsAndOrders($id) {
        //parameters

        //authorize
        auth()->user()->authorize("company_admin", $id, ["company_active" => false]);

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

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

    public function createSetupIntentForUser(Request $request, $id, $user_id) {

        if(!auth()->user()->itsMe($user_id)) return response()->json(["error" => "Unauthorized"], 401);

        try { //aquesta es la unica manera de crear un stripe user
            $data = CompanyRepository::createSetupIntentForUser($id, $user_id);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

        return response()->json(["intent" => $data], 200);

    }
}
