<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use App\Models\VendorUsers;
use App\Services\FirestoreRestService;
use App\Services\StripeStatusService;
use Stripe\Stripe;
use Stripe\Account;
use Stripe\AccountLink;

class StripeConnectController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
        
        // Initialize Stripe
        $stripeSecret = env('STRIPE_SECRET');
        if ($stripeSecret) {
            Stripe::setApiKey($stripeSecret);
        }
    }
    
    /**
     * Show business type selection (for backward compatibility with GET requests)
     * Redirects to dashboard with instruction to use the modal
     */
    public function showOnboardingModal()
    {
        return redirect()->route('dashboard')
            ->with('info', trans('lang.stripe_use_connect_button'));
    }

    /**
     * Start Stripe Connect onboarding with selected business type
     * Data is stored ONLY in Firebase (no MySQL)
     */
    public function startOnboarding(Request $request)
    {
        try {
            $user = Auth::user();
            $vendorUser = VendorUsers::where('user_id', $user->id)->firstOrFail();
            
            // Validate business_type from request
            $validated = $request->validate([
                'business_type' => 'required|in:individual,company'
            ]);
            
            $businessType = $validated['business_type'];
            
            // Check if already connected (from Firebase)
            $stripeStatus = StripeStatusService::getStripeStatus($vendorUser->uuid);
            if ($stripeStatus['connected']) {
                return response()->json([
                    'success' => false,
                    'error' => trans('lang.stripe_already_connected')
                ], 400);
            }
            
            // DEMO MODE: Simulate Stripe Connect for testing UI
            $demoMode = config('app.stripe_demo_mode', env('STRIPE_DEMO_MODE', false));
            
            if ($demoMode) {
                Log::info('DEMO MODE: Simulating Stripe onboarding', [
                    'user_id' => $user->id,
                    'vendor_uuid' => $vendorUser->uuid,
                    'business_type' => $businessType
                ]);
                
                // Generate demo account ID and store in session
                $demoAccountId = 'acct_demo_' . uniqid();
                session(['stripe_demo_account_id' => $demoAccountId]);
                
                // Return demo redirect URL
                return response()->json([
                    'success' => true,
                    'redirect_url' => route('stripe.onboarding.complete', ['demo' => 1]),
                    'demo_mode' => true
                ]);
            }
            
            // PRODUCTION MODE: Real Stripe API
            Log::info('Creating new Stripe Connected Account', [
                'user_id' => $user->id,
                'vendor_uuid' => $vendorUser->uuid,
                'business_type' => $businessType
            ]);
            
            // Create new Stripe Connected Account with selected business type
            $account = Account::create([
                'type' => 'express', // Express for easier onboarding
                'country' => 'DE',
                'email' => $user->email,
                'capabilities' => [
                    'card_payments' => ['requested' => true],
                    'transfers' => ['requested' => true],
                ],
                'business_type' => $businessType, // FROM MODAL SELECTION
                'metadata' => [
                    'vendor_id' => $vendorUser->uuid,
                    'restaurant_name' => $vendorUser->restaurant_name ?? 'Restaurant',
                    'selected_business_type' => $businessType, // Store for reference
                ]
            ]);
            
            // Store account ID in session temporarily (will be saved to Firebase after completion)
            session(['stripe_pending_account_id' => $account->id]);
            
            Log::info('Stripe Account created', [
                'account_id' => $account->id,
                'vendor_uuid' => $vendorUser->uuid,
                'business_type' => $businessType
            ]);
            
            // Create Account Link (onboarding URL)
            $accountLink = AccountLink::create([
                'account' => $account->id,
                'refresh_url' => route('stripe.onboarding.refresh'),
                'return_url' => route('stripe.onboarding.complete'),
                'type' => 'account_onboarding',
            ]);
            
            Log::info('Redirecting to Stripe onboarding', [
                'account_id' => $account->id,
                'business_type' => $businessType,
                'url' => $accountLink->url
            ]);
            
            // Return JSON with redirect URL
            return response()->json([
                'success' => true,
                'redirect_url' => $accountLink->url,
                'demo_mode' => false
            ]);
            
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'error' => trans('lang.business_type_required')
            ], 422);
            
        } catch (\Exception $e) {
            Log::error('Failed to start Stripe onboarding', [
                'error' => $e->getMessage(),
                'user_id' => Auth::id()
            ]);
            
            return response()->json([
                'success' => false,
                'error' => trans('lang.stripe_onboarding_error')
            ], 500);
        }
    }
    
    /**
     * Handle onboarding completion (return from Stripe)
     * Saves stripe_connect_id to Firebase ONLY
     */
    public function onboardingComplete(Request $request)
    {
        try {
            $user = Auth::user();
            $vendorUser = VendorUsers::where('user_id', $user->id)->firstOrFail();
            
            // DEMO MODE: Simulate successful onboarding
            $demoMode = config('app.stripe_demo_mode', env('STRIPE_DEMO_MODE', false)) || $request->has('demo');
            
            if ($demoMode) {
                $demoAccountId = session('stripe_demo_account_id', 'acct_demo_' . uniqid());
                
                Log::info('DEMO MODE: Simulating successful onboarding', [
                    'account_id' => $demoAccountId,
                    'vendor_uuid' => $vendorUser->uuid
                ]);
                
                // Save to Firebase ONLY
                $this->saveStripeToFirebase($vendorUser->uuid, $demoAccountId);
                
                // Clear session and cache
                session()->forget('stripe_demo_account_id');
                StripeStatusService::clearCache($vendorUser->uuid);
                
                return redirect()->route('dashboard')
                    ->with('success', 'DEMO: Stripe-Konto erfolgreich verbunden! (Demo-Modus)');
            }
            
            // PRODUCTION MODE: Check real Stripe account status
            $pendingAccountId = session('stripe_pending_account_id');
            
            if (!$pendingAccountId) {
                return redirect()->route('dashboard')
                    ->with('error', 'Kein Stripe-Konto gefunden. Bitte versuchen Sie es erneut.');
            }
            
            $account = Account::retrieve($pendingAccountId);
            
            Log::info('Stripe onboarding return', [
                'account_id' => $account->id,
                'details_submitted' => $account->details_submitted,
                'charges_enabled' => $account->charges_enabled,
                'payouts_enabled' => $account->payouts_enabled
            ]);
            
            if ($account->charges_enabled && $account->payouts_enabled) {
                // Account fully active - save to Firebase ONLY
                $this->saveStripeToFirebase($vendorUser->uuid, $account->id);
                
                // Clear session and cache
                session()->forget('stripe_pending_account_id');
                StripeStatusService::clearCache($vendorUser->uuid);
                
                return redirect()->route('dashboard')
                    ->with('success', 'Stripe-Konto erfolgreich verbunden! Sie können jetzt Zahlungen empfangen.');
            } else {
                // Requires additional information - still save to Firebase
                // The account exists but is pending verification
                $this->saveStripeToFirebase($vendorUser->uuid, $account->id);
                
                // Clear session and cache
                session()->forget('stripe_pending_account_id');
                StripeStatusService::clearCache($vendorUser->uuid);
                
                return redirect()->route('dashboard')
                    ->with('warning', 'Stripe-Verifizierung läuft. Sie werden benachrichtigt, wenn Ihr Konto aktiv ist.');
            }
            
        } catch (\Exception $e) {
            Log::error('Failed to complete Stripe onboarding', [
                'error' => $e->getMessage(),
                'user_id' => Auth::id()
            ]);
            
            return redirect()->route('dashboard')
                ->with('error', 'Fehler beim Abschluss des Onboardings. Bitte kontaktieren Sie den Support.');
        }
    }
    
    /**
     * Handle onboarding refresh (when link expires)
     */
    public function onboardingRefresh()
    {
        return $this->startOnboarding();
    }
    
    /**
     * Get Stripe Express Dashboard login link
     */
    public function getDashboardLink()
    {
        try {
            $vendorUser = VendorUsers::where('user_id', Auth::id())->firstOrFail();
            
            // Get Stripe status from Firebase
            $stripeStatus = StripeStatusService::getStripeStatus($vendorUser->uuid);
            
            if (!$stripeStatus['connected'] || empty($stripeStatus['account_id'])) {
                return redirect()->route('dashboard')
                    ->with('error', 'Kein Stripe-Konto verbunden.');
            }
            
            $stripeAccountId = $stripeStatus['account_id'];
            
            // DEMO MODE: Show info message
            $demoMode = config('app.stripe_demo_mode', env('STRIPE_DEMO_MODE', false));
            
            if ($demoMode) {
                return redirect()->route('dashboard')
                    ->with('info', 'DEMO MODE: Stripe Dashboard würde hier geöffnet. Account ID: ' . $stripeAccountId);
            }
            
            // PRODUCTION MODE: Create real login link
            $loginLink = Account::createLoginLink($stripeAccountId);
            
            Log::info('Opening Stripe Dashboard', [
                'account_id' => $stripeAccountId,
                'source' => $stripeStatus['source'],
                'user_id' => Auth::id()
            ]);
            
            return redirect($loginLink->url);
            
        } catch (\Exception $e) {
            Log::error('Failed to create Stripe Dashboard link', [
                'error' => $e->getMessage(),
                'user_id' => Auth::id()
            ]);
            
            return redirect()->route('dashboard')
                ->with('error', 'Fehler beim Öffnen des Stripe-Dashboards.');
        }
    }
    
    /**
     * Get Stripe Dashboard URL as JSON (for modal)
     */
    public function getDashboardUrl()
    {
        try {
            $vendorUser = VendorUsers::where('user_id', Auth::id())->firstOrFail();
            
            // Get Stripe status from Firebase
            $stripeStatus = StripeStatusService::getStripeStatus($vendorUser->uuid);
            
            if (!$stripeStatus['connected'] || empty($stripeStatus['account_id'])) {
                return response()->json([
                    'success' => false,
                    'error' => trans('lang.stripe_not_connected')
                ], 400);
            }
            
            $stripeAccountId = $stripeStatus['account_id'];
            
            // DEMO MODE
            $demoMode = config('app.stripe_demo_mode', env('STRIPE_DEMO_MODE', false));
            
            if ($demoMode) {
                return response()->json([
                    'success' => true,
                    'demo_mode' => true,
                    'account_id' => $stripeAccountId,
                    'message' => 'DEMO MODE: Stripe Dashboard would open here.'
                ]);
            }
            
            // PRODUCTION MODE: Create real login link
            $loginLink = Account::createLoginLink($stripeAccountId);
            
            Log::info('Generated Stripe Dashboard URL', [
                'account_id' => $stripeAccountId,
                'source' => $stripeStatus['source'],
                'user_id' => Auth::id()
            ]);
            
            return response()->json([
                'success' => true,
                'demo_mode' => false,
                'url' => $loginLink->url,
                'account_id' => $stripeAccountId
            ]);
            
        } catch (\Exception $e) {
            Log::error('Failed to get Stripe Dashboard URL', [
                'error' => $e->getMessage(),
                'user_id' => Auth::id()
            ]);
            
            return response()->json([
                'success' => false,
                'error' => trans('lang.stripe_dashboard_error')
            ], 500);
        }
    }
    
    /**
     * Save stripe_connect_id to Firebase vendors collection
     * 
     * @param string $vendorUuid - UUID of the vendor (author field in Firebase, not document ID)
     * @param string $stripeAccountId - Stripe Connected Account ID (acct_xxx)
     * @return bool
     */
    private function saveStripeToFirebase(string $vendorUuid, string $stripeAccountId): bool
    {
        try {
            $firestore = new FirestoreRestService();
            
            // Find vendor document by 'author' field (UUID is stored there, not as doc ID)
            $vendors = $firestore->queryCollection('vendors', 'author', '==', $vendorUuid);
            
            if (empty($vendors)) {
                Log::warning('Vendor document not found in Firebase', [
                    'vendor_uuid' => $vendorUuid
                ]);
                return false;
            }
            
            $vendorDocId = $vendors[0]['id'] ?? null;
            
            if (!$vendorDocId) {
                Log::warning('Vendor document has no ID', [
                    'vendor_uuid' => $vendorUuid
                ]);
                return false;
            }
            
            // Update the vendor document with stripe_connect_id
            $result = $firestore->updateDocument('vendors', $vendorDocId, [
                'stripe_connect_id' => $stripeAccountId
            ]);
            
            if ($result) {
                Log::info('Stripe Connect ID saved to Firebase', [
                    'vendor_uuid' => $vendorUuid,
                    'vendor_doc_id' => $vendorDocId,
                    'stripe_connect_id' => $stripeAccountId
                ]);
                return true;
            }
            
            Log::warning('Failed to save Stripe Connect ID to Firebase (no result)', [
                'vendor_uuid' => $vendorUuid,
                'vendor_doc_id' => $vendorDocId,
                'stripe_connect_id' => $stripeAccountId
            ]);
            return false;
            
        } catch (\Exception $e) {
            Log::error('Exception saving Stripe Connect ID to Firebase', [
                'vendor_uuid' => $vendorUuid,
                'stripe_connect_id' => $stripeAccountId,
                'error' => $e->getMessage()
            ]);
            return false;
        }
    }
}
