<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Services\BraintreeService;

class PaymentController extends Controller
{
    public function showPayment($planId)
    {
        return view('payment', compact('planId'));
    }

    public function token()
    {
        $gateway = BraintreeService::gateway();
        $token = $gateway->clientToken()->generate();

        return response()->json(['clientToken' => $token]);
    }

    public function checkout(Request $request)
    {
        $request->validate([
            'firstName' => 'required|string',
            'email' => 'required|email',
            'paymentMethodNonce' => 'required|string',
            'planId' => 'required|string'
        ]);

        $gateway = BraintreeService::gateway();

        $customerResult = $gateway->customer()->create([
            'firstName' => $request->firstName,
            'email' => $request->email,
            'paymentMethodNonce' => $request->paymentMethodNonce,
        ]);

        if (!$customerResult->success) {
            return response()->json([
                'success' => false,
                'message' => $customerResult->message
            ], 422);
        }

        $paymentMethodToken =
            $customerResult->customer->paymentMethods[0]->token;

        $subscriptionResult = $gateway->subscription()->create([
            'paymentMethodToken' => $paymentMethodToken,
            'planId' => $request->planId,
        ]);

        if (!$subscriptionResult->success) {
            return response()->json([
                'success' => false,
                'message' => $subscriptionResult->message
            ], 422);
        }

        return response()->json([
            'success' => true,
            'subscriptionId' => $subscriptionResult->subscription->id,
            'status' => $subscriptionResult->subscription->status
        ]);
    }
}
