<?php

namespace App\Http\Controllers;

use App\Repositories\CompanyRepository;
use App\Repositories\StripeRepository;
use App\StripeUser;
use Illuminate\Http\Request;

use Laravel\Cashier\Payment;
use Stripe\PaymentIntent as StripePaymentIntent;

class StripeController extends Controller {

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

    /**
     * API CONTROLLER METHODS
     */
    public function updateCompanyPaymentMethod(Request $request, $id) {
        //autoritzem l'ús de la ruta
        auth()->user()->authorize("company_admin", $id, ["active" => true, "company_active" => false]);

        try {
            $company = StripeRepository::fromWebhookUpdateCompanyPaymentMethod($id, $request->all());
        }
        catch(\Exception $e) {
            return response()->json(["error" => "Se ha producido un error: " . $e->getMessage()], 400);
        }

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

    public function updateStripeUserPaymentMethod(Request $request, $company_id, $user_id) {
        //autoritzem l'ús de la ruta
        if(!auth()->user()->itsMe($user_id)) {
            auth()->user()->authorize("company_admin", $user_id);
        }

        try {
            $stripe_user_id = CompanyRepository::getStripeIdByUserId($company_id, $user_id);
            $stripe_user = StripeRepository::fromWebhookUpdateStripeUserPaymentMethod($stripe_user_id, $request->all());
        }
        catch(\Exception $e) {
            return response()->json(["error" => "Se ha producido un error: " . $e->getMessage()], 400);
        }

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


    /**
     * WEB VIEW CONTROLLER METHOD
     */
    public function paymentMethodsView(Request $request, $company_id) {
        //autoritzem l'ús de la ruta
        auth()->user()->authorize("company_admin", $company_id, ["active" => true, "company_active" => false]);

        //obtenim parametres
        $company = CompanyRepository::find($company_id);
        $token = $request->query("token");
        if(!$token) return response()->json(["error" => "Please provide token via query parameter."], 401);

        return view('secure.paymentMethods', [
            'intent' => $company->createSetupIntent(),
            'company_id' => $company_id,
            'token' => $token,
            "card_last_four" => $company->card_last_four,
            "card_brand" => $company->card_brand
        ]);
    }

    public function paymentActionRequiredView(Request $request, $payment_id, $api_key) {

        return view("secure.paymentActionRequired", [
            'stripeKey' => $api_key,
            'payment' => new Payment(
                StripePaymentIntent::retrieve($payment_id, StripeRepository::stripeOptions())
            ),
            'redirect' => request('redirect'),
        ]);
    }


}
