<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Traits\UserTraits;
use App\Services\Payments\PaymentMethodService;
use Illuminate\Validation\ValidationException;
use Exception;

/**
 * PaymentMethodController
 *
 * Handles HTTP requests related to payment methods for a user's company.
 */
class PaymentMethodController extends Controller
{
    use UserTraits;

    protected PaymentMethodService $paymentMethodService;

    /**
     * Inject the PaymentMethodService.
     */
    public function __construct(PaymentMethodService $paymentMethodService)
    {
        $this->paymentMethodService = $paymentMethodService;
    }

    /**
     * Updates the default payment method for the authenticated user's company.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request)
    {
        $request->validate([
            'payment_method_id' => 'required|string',
        ]);

        $user = $this->getCurrentUser();
        $companyId = $user->company_id ?? null;

        if (!$companyId) {
            return response()->json([
                'success' => false,
                'message' => 'Missing company ID for authenticated user.',
            ], 422);
        }

        try {
            $message = $this->paymentMethodService->updateDefaultPaymentMethod(
                $companyId,
                $request->payment_method_id
            );

            return response()->json([
                'success' => true,
                'message' => $message,
            ]);
        } catch (ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
                'errors' => $e->errors(),
            ], 422);
        } catch (Exception $e) {
            Log::error('Payment method update failed.', [
                'company_id' => $companyId,
                'error' => $e->getMessage(),
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Unable to update payment method.',
            ], 400);
        }
    }

    /**
     * Retrieves the current default payment method for the authenticated user's company.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function current(Request $request)
    {
        $user = $this->getCurrentUser();
        $companyId = $user->company_id ?? null;

        if (!$companyId) {
            return response()->json([
                'success' => false,
                'message' => 'Missing company ID.',
            ], 422);
        }

        try {
            $card = $this->paymentMethodService->getCurrentPaymentMethod($companyId);

            return response()->json([
                'success' => true,
                'card' => $card,
            ]);
        } catch (Exception $e) {
            Log::error('Failed to fetch current payment method.', [
                'company_id' => $companyId,
                'error' => $e->getMessage(),
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Unable to retrieve current payment method.',
            ], 500);
        }
    }

    public function createSetupIntent(Request $request)
    {
        $user = $this->getCurrentUser();
        
        $companyId = $user->company_id ?? null;

        if (!$companyId) {
            return response()->json([
                'success' => false,
                'message' => 'Missing company ID.',
            ], 422);
        }

        try {
            $intent = $this->paymentMethodService->createSetupIntent($companyId);

            return response()->json([
                'success' => true,
                'client_secret' => $intent['client_secret'],
            ]);
        } catch (\Exception $e) {
            \Log::error('SetupIntent creation failed: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to create SetupIntent.',
            ], 500);
        }
    }

}
