<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Crypt;

class AiKey extends Model
{
    use HasFactory;

    protected $fillable = [
        'travel_agent_id',
        'gemini_api_key',
        'is_active',
        'free_credits_used',
        'paid_credits_used',
        'total_credits_used',
        'free_words_used',
        'paid_words_used',
        'top_up_words',
        'total_words_used',
        'free_words_reset_date',
        'subscription_start_date',
        'subscription_end_date'
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'free_words_reset_date' => 'datetime',
        'subscription_start_date' => 'datetime',
        'subscription_end_date' => 'datetime',
    ];

    // Relationship with TravelAgent
    public function travelAgent()
    {
        return $this->belongsTo(TravelAgent::class);
    }

    // Get active subscription
    public function activeSubscription()
    {
        return AiSubscription::where('travel_agent_id', $this->travel_agent_id)
            ->where('status', 'active')
            ->where('end_date', '>', now())
            ->first();
    }

    // Check if has active subscription
    public function hasActiveSubscription()
    {
        $subscription = $this->activeSubscription();
        return $subscription && $subscription->isActive();
    }

    // Get remaining free credits
    public function getRemainingFreeCredits()
    {
        return $this->getRemainingFreeWords();
    }

    // Check if has free credits
    public function hasFreeCredits()
    {
        return $this->hasFreeWords();
    }

    // Check if has free words available
    public function hasFreeWords()
    {
        return $this->getRemainingFreeWords() > 0;
    }

    // Get remaining free words (500 monthly)
    public function getRemainingFreeWords()
    {
        $this->resetFreeWordsIfNeeded();
        return max(0, 500 - ($this->free_words_used ?? 0));
    }

    // Reset free words at monthly cycle
    public function resetFreeWordsIfNeeded()
    {
        if (!$this->free_words_reset_date || now()->greaterThan($this->free_words_reset_date)) {
            $this->update([
                'free_words_used' => 0,
                'free_words_reset_date' => now()->addMonth()
            ]);
        }
    }

    // Check if API key is valid
    public function hasValidApiKey()
    {
        if (empty($this->gemini_api_key)) {
            return false;
        }
        
        try {
            $decryptedKey = Crypt::decrypt($this->gemini_api_key);
            return !empty($decryptedKey) && 
                   strlen($decryptedKey) > 20 && 
                   strpos($decryptedKey, 'AIza') === 0;
        } catch (\Exception $e) {
            return false;
        }
    }

    // Get decrypted API key
    public function getDecryptedApiKey()
    {
        if (empty($this->gemini_api_key)) {
            return null;
        }
        
        try {
            return Crypt::decrypt($this->gemini_api_key);
        } catch (\Exception $e) {
            return null;
        }
    }

    // Get subscription words available
    public function getSubscriptionWords()
    {
        $subscription = $this->activeSubscription();
        return $subscription ? $subscription->getRemainingWords() : 0;
    }

    // ✅ NEW: Get remaining top-up words
    public function getRemainingTopUpWords()
    {
        $topUpWordsTotal = $this->top_up_words ?? 0;
        $topUpWordsUsed = $this->paid_words_used ?? 0;
        return max(0, $topUpWordsTotal - $topUpWordsUsed);
    }

    // ✅ NEW: Check if has top-up credits available
    public function hasTopUpCredits()
    {
        return $this->getRemainingTopUpWords() > 0;
    }

    // ✅ NEW: Get total available words across all sources
    public function getTotalAvailableWords()
    {
        return $this->getRemainingFreeWords() + 
               $this->getSubscriptionWords() + 
               $this->getRemainingTopUpWords();
    }

    // ✅ NEW: Check if user has any credits available
    public function hasAnyCredits()
    {
        return $this->getTotalAvailableWords() > 0;
    }

    // ✅ NEW: Check if user has minimum words for specific page type
    public function hasMinimumWords($minWords)
    {
        return $this->getTotalAvailableWords() >= $minWords;
    }

    // ✅ FIXED: Increment word usage with proper tracking
    public function incrementWordUsage($wordCount, $usedFreeCredit, $usedTopUpWords = 0)
    {
        if ($usedFreeCredit) {
            // Use free words
            $this->increment('free_words_used', $wordCount);
            $this->increment('free_credits_used', $wordCount);
        } else {
            if ($usedTopUpWords > 0) {
                // Use top-up words
                $this->increment('paid_words_used', $wordCount);
            } else {
                // Use subscription words
                $subscription = $this->activeSubscription();
                if ($subscription && $subscription->getRemainingWords() >= $wordCount) {
                    $subscription->incrementWordsUsed($wordCount);
                }
                $this->increment('paid_words_used', $wordCount);
            }
        }
        
        // Update totals
        $this->increment('total_words_used', $wordCount);
        $this->increment('total_credits_used', $wordCount);
        
        $this->save();
    }

    // ✅ NEW: Get current top-up rate based on active plan
    public function getCurrentTopUpRate()
    {
        $subscription = $this->activeSubscription();
        
        if ($subscription && $subscription->plan) {
            return $subscription->plan->top_up_rate;
        }
        
        // Default rate for free plan (no active subscription)
        return 0.17;
    }
}