<?php

namespace App\Livewire;

use Livewire\Component;
use Illuminate\Support\Facades\Log;
use App\Models\Subscription;
use Illuminate\Support\Facades\Auth;

class License extends Component
{
    /**
     * License code input
     * @var string
     */
    public string $licence_code = '';

    /**
     * Whether license can be activated
     * @var bool
     */
    public bool $can_license = false;

    /**
     * Loading state
     * @var bool
     */
    public bool $loading = false;

    /**
     * Initialize component data
     * @return void
     */
    public function mount(): void
    {
        // Check for active subscription and save to DB if found
        $this->checkAndSaveActiveSubscription();
    }

    /**
     * Check for active subscription and save to database if found
     * @return void
     */
    private function checkAndSaveActiveSubscription(): void
    {
        try {
            // Only try API call if we have a valid token
            $response = getSubscriptions();
            
            // If no auth token available, skip API call and continue with local data
            if (!$response['success'] && str_contains($response['error'] ?? '', 'No authentication token available')) {
                return; // Skip API sync, use local data only
            }
            
            if ($response['success'] && $response['has_active_subscription'] && isset($response['subscription'])) {
                $subscriptionData = $response['subscription'];
                
                // Check if subscription already exists in local database
                $existingSubscription = Subscription::where('code', $subscriptionData['code'])->first();
                
                if (!$existingSubscription) {
                    // Create new subscription in local database
                    $startDate = \Carbon\Carbon::parse($subscriptionData['start_date']);
                    $endDate = $startDate->copy()->addDays($subscriptionData['duration_in_days']);
                    
                    $subscription = Subscription::create([
                        'slug' => \Illuminate\Support\Str::orderedUuid(),
                        'category' => $subscriptionData['category'] ?? 'Premium',
                        'code' => $subscriptionData['code'],
                        'start_date' => $startDate,
                        'end_date' => $endDate,
                        'duration_in_days' => $subscriptionData['duration_in_days'],
                        'status' => Subscription::STATUS_ACTIVE,
                        'activated_at' => now(),
                    ]);
                    
                    // Store subscription ID in session for quick access
                    session(['active_subscription_id' => $subscription->id]);
                    
                    Log::info('Active subscription found and saved to database', [
                        'subscription_id' => $subscription->id,
                        'user_id' => Auth::id(),
                        'code' => $subscriptionData['code'],
                        'category' => $subscriptionData['category'],
                    ]);
                } else {
                    // Update existing subscription if needed
                    $existingSubscription->update([
                        'status' => Subscription::STATUS_ACTIVE,
                        'activated_at' => now(),
                    ]);
                    
                    session(['active_subscription_id' => $existingSubscription->id]);
                    
                    Log::info('Active subscription updated in database', [
                        'subscription_id' => $existingSubscription->id,
                        'user_id' => Auth::id(),
                        'code' => $subscriptionData['code'],
                    ]);
                }
                
                // Redirect to home since user has an active subscription
                $this->redirect(route('home'), true);
            } else {
                Log::info('No active subscription found for user', [
                    'user_id' => Auth::id(),
                    'response' => $response,
                ]);
            }
        } catch (\Exception $e) {
            Log::error('Failed to check active subscription', [
                'error' => $e->getMessage(),
                'user_id' => Auth::id(),
            ]);
        }
    }

    /**
     * Updated when licence_code changes
     * @return void
     */
    public function updatedLicenceCode(): void
    {
        $this->can_license = $this->licence_code && strlen($this->licence_code) === 14;
    }

    /**
     * Submit license for activation
     * @return void
     */
    public function submitLicense(): void
    {
        $this->loading = true;

        // Validate license code length
        if (!$this->licence_code || strlen($this->licence_code) !== 14) {
            $this->addError('licence_code', 'Le code de licence doit contenir exactement 14 caractères.');
            $this->loading = false;
            return;
        }
        
        $response = submitAppLicensed($this->licence_code);
        
        if ($response['success']) {
            // Save subscription to local database
            try {
                $subscriptionData = $response['subscription'] ?? $response['data'] ?? [];
                
                // Ensure we have the required data
                if (empty($subscriptionData)) {
                    throw new \Exception('Données de souscription manquantes');
                }
                
                // Create or update subscription in local database
                $subscription = Subscription::createOrUpdate([
                    'api_id' => $subscriptionData['id'] ?? null,
                    'category' => $subscriptionData['category'] ?? 'premium',
                    'code' => $this->licence_code,
                    'start_date' => $subscriptionData['start_date'] ?? now(),
                    'duration_in_days' => $subscriptionData['duration_days'] ?? $subscriptionData['duration_in_days'] ?? 30,
                    'status' => Subscription::STATUS_ACTIVE,
                    'activated_at' => now(),
                ]);
                
                // Store subscription ID in session for quick access
                session(['active_subscription_id' => $subscription->id]);
                
                // Log successful activation for debugging
                Log::info('Subscription activated successfully', [
                    'subscription_id' => $subscription->id,
                    'user_id' => Auth::id(),
                    'code' => $this->licence_code,
                ]);
                
                $this->loading = false;
                session()->flash('success', $response['message'] ?? 'Licence activée avec succès!');
                $this->redirect(route('home'), true);
                
            } catch (\Exception $e) {
                Log::error('Failed to save subscription locally', [
                    'error' => $e->getMessage(),
                    'response' => $response,
                    'user_id' => Auth::id(),
                ]);
                
                $this->loading = false;
                $this->addError('licence_code', 'Erreur lors de la sauvegarde locale. Veuillez réessayer.');
            }
        } else {
            // Show more user-friendly error messages
            $errorMessage = $response['error'];
            
            // Handle specific backend errors
            if (str_contains($errorMessage, 'status code 500')) {
                $errorMessage = 'Erreur du serveur. Veuillez contacter le support technique.';
            } elseif (str_contains($errorMessage, 'status code 404')) {
                $errorMessage = 'Code de licence invalide.';
            } elseif (str_contains($errorMessage, 'status code 401')) {
                $errorMessage = 'Session expirée. Veuillez vous reconnecter.';
            }
            
            $this->addError('licence_code', $errorMessage);
            $this->loading = false;
        }
    }

    /**
     * Render the component
     * @return \Illuminate\Contracts\View\View
     */
    public function render(): \Illuminate\Contracts\View\View
    {
        return view('livewire.license');
    }
}
