<?php

namespace App\Http\Controllers;

use App\Repositories\CompanyRepository;
use App\Repositories\StripeRepository;
use Laravel\Cashier\Http\Controllers\WebhookController as CashierController;


class WebhookController extends CashierController {
    //Aquesta funció és per quan ha renovat una subscripció
    public function handleInvoicePaymentSucceeded(array $payload) {
        $data = $payload["data"]["object"];
        if(isset($data["subscription"])) {
            try {
                StripeRepository::fromWebhookSubscriptionRenewed($data);
            }
            catch(\Exception $e) { return response()->json(["error" => "Error: " . $e->getMessage()], 400); }

            return response()->json(["message" => "Subscription payed"], 200);
        }
        return response()->json(["message" => "Subscription not found"], 400);
    }

    //Aquesta funció es per quan un pagament ha fallat i hem d'avisar
    public function handleInvoicePaymentFailed(array $payload) {
        $data = $payload["data"]["object"];
        if(isset($data["subscription"])) {
            try {
                StripeRepository::fromWebhookSubscriptionPaymentFailed($data);
            }
            catch(\Exception $e) { return response()->json(["error" => "Error: " . $e->getMessage()], 400); }

            return response()->json(["message" => "Subscription found. We have notified the user."], 200);
        }

        return response()->json(["message" => "Subscription not found"], 400);
    }

    //Aquesta funció es per quan un pagament ha fallat perquè necessita una acció
    public function handleInvoicePaymentActionRequired(array $payload) {
        $data = $payload["data"]["object"];
        if(isset($data["subscription"])) {
            try {
                StripeRepository::fromWebhookSubscriptionPaymentActionRequired($data);
            }
            catch(\Exception $e) { return response()->json(["error" => "Error: " . $e->getMessage()], 400); }

            return response()->json(["message" => "Subscription found. We have notified the user."], 200);
        }

        return response()->json(["message" => "Subscription not found"], 400);
    }

    public function handleCustomerSubscriptionUpdated(array $payload) {
        //return parent::handleCustomerSubscriptionUpdated($payload);
        //que no faci res
        return response()->json(["message" => "Ok, nothing done"], 200);
    }

    public function handleCustomerSubscriptionDeleted(array $payload) {
        $data = $payload["data"]["object"];
        try {
            StripeRepository::fromWebhookSubscriptionDeleted($data);
        }
        catch(\Exception $e) { return response()->json(["error" => "Error: " . $e->getMessage()], 400); }

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

    public function handleCustomerUpdated(array $payload) {
        $data = $payload["data"]["object"];

        try {
            if(isset($data["metadata"]["company_id"])) {
                //es un company
                CompanyRepository::update(StripeRepository::stripeToCompanyFormat($data), $data["metadata"]["company_id"]);
            }
            elseif(isset($data["metadata"]["stripe_user_id"])) {
                //es un user
                throw new \Exception("You can not update a user from Stripe.");
            }
            else throw new \Exception("Customer not found. Provide stripe_user_id or company_id inside metadata.");
        }
        catch(\Exception $e) { return response()->json(["error" => "Error: " . $e->getMessage()], 400); }

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

    public function handleCustomerDeleted(array $payload) {
        $data = $payload["data"]["object"];
        try {
            StripeRepository::fromWebhookCustomerDeleted($data);
        }
        catch(\Exception $e) { return response()->json(["error" => "Error: " . $e->getMessage()], 400); }

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

    //per quan els users fan attach dun payment method a les companyies. De les companyies no.
    public function handlePaymentMethodAttached(array $payload) {
        $data = $payload["data"]["object"];

        if(isset($data["customer"])) {
            $stripe_customer_id = $data["customer"];
            $payment_method_id = $data["id"];
            $brand = $data["card"]["brand"];
            $last_four = $data["card"]["last4"];
            try {
               CompanyRepository::attachPaymentMethodToCustomer($stripe_customer_id, $payment_method_id, $brand, $last_four);
            }
            catch(\Exception $e) { return response()->json(["error" => "Error: " . $e->getMessage()], 400); }
        }
        else return response()->json(["error" => "Error: proper metadata not found."], 400);

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

    public function handlePaymentMethodDetached(array $payload) {
        $data = $payload["data"]["object"];

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

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

}
