<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Contracts\PaymentGatewayInterface;
use App\Models\Company;
use App\Traits\UserTraits;
use App\Models\PaymentProfile;
class StripeConnectController extends Controller
{
    use UserTraits;
    
    protected PaymentGatewayInterface $gateway;

    public function __construct(PaymentGatewayInterface $gateway)
    {
        $this->gateway = $gateway;
    }

    /**
     * Initiate onboarding process (Account + AccountLink)
     */
    public function startOnboarding(Request $request)
    {
        $user = $this->getCurrentUser();
        $companyId = $user->company_id ?? null;

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

        $url = $this->gateway->createConnectOnboardingLink($companyId);
        return response()->json(['url' => $url]);
    }

    /**
     * Check if onboarding is complete
     */
    public function verifyOnboarding(string $accountId)
    {
        $result = $this->gateway->verifyConnectAccount($accountId);
        return response()->json($result);
    }

    /**
     * Generate a one-time login link to the Stripe Express dashboard
     */
    public function getExpressDashboardLink(Request $request)
    {
        $user = $this->getCurrentUser();
        $companyId = $user->company_id ?? null;

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

        $profile = PaymentProfile::where('company_id', $companyId)
            ->where('provider', 'stripe')
            ->first();

        if (!$profile || !$profile->provider_account_id) {
            return response()->json([
                'success' => false,
                'message' => 'No Stripe connected account found for this company.',
            ], 404);
        }

        $url = $this->gateway->createExpressDashboardLoginLink($profile->provider_account_id);
        return response()->json(['url' => $url]);
    }

}
