<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

class TravelAgent extends Model
{
    use HasFactory;

    // Add all the new fields from the migration to the $fillable array
    protected $fillable = [
        'name',
        'contact_info',
        'rules_and_regulations',
        
        // --- ADDED FIELDS ---
        'email', // From the original table schema
        'phone', // From the original table schema
        'contact_person_name',
        'gst_number',
        'address',
        'logo_file',
        'terms_and_conditions',
        'cancellation_policy',
        'inclusions',
        'exclusions',
        'mail_mailer',
        'mail_host',
        'mail_port',
        'mail_username',
        'mail_password',
        'mail_from_address',
        'mail_from_name',
        'sms_sid',
        'sms_token',
        'sms_from_number',
        'is_active', // ADD THIS FIELD
    ];

    /**
     * Get all users for the travel agent.
     */
    public function users(): HasMany  // ADD THIS METHOD
    {
        return $this->hasMany(User::class);
    }
    
    
    /**
     * Get all services for the travel agent.
     */
    public function services(): HasMany
    {
        return $this->hasMany(Service::class);
    }

    /**
     * Get all hotels for the travel agent.
     */
    public function hotels(): HasMany
    {
        return $this->hasMany(Hotel::class);
    }

    /**
     * Get all extra services for the travel agent.
     */
    public function extraServices(): HasMany
    {
        return $this->hasMany(ExtraService::class);
    }

    /**
     * Get all customers for the travel agent.
     */
    public function customers(): HasMany
    {
        return $this->hasMany(Customer::class);
    }

    /**
     * Get all invoices for the travel agent.
     */
    public function invoices(): HasMany
    {
        return $this->hasMany(Invoice::class);
    }

    /**
     * Get all day descriptions for the travel agent.
     */
    public function dayDescriptions(): HasMany
    {
        return $this->hasMany(DayDescription::class);
    }

    /**
     * Get all invoice days for the travel agent (through invoices).
     */
    public function invoiceDays()
    {
        return $this->hasManyThrough(InvoiceDay::class, Invoice::class);
    }

    /**
     * Get all invoice day services for the travel agent (through invoices and days).
     */
    public function invoiceDayServices()
    {
        return $this->hasManyThrough(InvoiceDayService::class, Invoice::class, 'travel_agent_id', 'invoice_day_id')
                    ->join('invoice_days', 'invoice_day_services.invoice_day_id', '=', 'invoice_days.id');
    }

    /**
     * Get all invoice day hotels for the travel agent (through invoices and days).
     */
    public function invoiceDayHotels()
    {
        return $this->hasManyThrough(InvoiceDayHotel::class, Invoice::class, 'travel_agent_id', 'invoice_day_id')
                    ->join('invoice_days', 'invoice_day_hotels.invoice_day_id', '=', 'invoice_days.id');
    }

    /**
     * Get all invoice day extra services for the travel agent (through invoices and days).
     */
    public function invoiceDayExtraServices()
    {
        return $this->hasManyThrough(InvoiceDayExtraService::class, Invoice::class, 'travel_agent_id', 'invoice_day_id')
                    ->join('invoice_days', 'invoice_day_extra_services.invoice_day_id', '=', 'invoice_days.id');
    }

    // ==================== AI RELATIONSHIPS ====================

    /**
     * Get the AI key for the travel agent.
     */
    public function aiKey(): HasOne
    {
        return $this->hasOne(AiKey::class);
    }

    /**
     * Get all AI usage logs for the travel agent.
     */
    public function aiUsageLogs(): HasMany
    {
        return $this->hasMany(AiUsageLog::class);
    }

    /**
     * Get all AI subscriptions for the travel agent.
     */
    public function aiSubscriptions(): HasMany
    {
        return $this->hasMany(AiSubscription::class);
    }

    /**
     * Get active AI subscription for the travel agent.
     */
    public function activeAiSubscription()
    {
        return $this->aiSubscriptions()
            ->where('end_date', '>', now())
            ->where('payment_status', 'paid')
            ->orderBy('end_date', 'desc')
            ->first();
    }

    /**
     * Check if travel agent has AI access.
     */
    public function hasAiAccess(): bool
    {
        $aiKey = $this->aiKey;
        
        if (!$aiKey || !$aiKey->is_active) {
            return false;
        }

        return $aiKey->hasFreeCredits() || $aiKey->hasActiveSubscription();
    }

    /**
     * Get remaining free AI credits.
     */
    public function getRemainingFreeAiCredits(): int
    {
        $aiKey = $this->aiKey;
        return $aiKey ? $aiKey->getRemainingFreeCredits() : 0;
    }

    /**
     * Get total AI credits used.
     */
    public function getTotalAiCreditsUsed(): int
    {
        $aiKey = $this->aiKey;
        return $aiKey ? $aiKey->total_credits_used : 0;
    }

    /**
     * Check if travel agent has active AI subscription.
     */
    public function hasActiveAiSubscription(): bool
    {
        $aiKey = $this->aiKey;
        return $aiKey ? $aiKey->hasActiveSubscription() : false;
    }

    /**
     * Get AI subscription end date.
     */
    public function getAiSubscriptionEndDate()
    {
        $aiKey = $this->aiKey;
        return $aiKey ? $aiKey->subscription_end_date : null;
    }

    /**
     * Get monthly AI usage statistics.
     */
    public function getMonthlyAiUsage()
    {
        return $this->aiUsageLogs()
            ->selectRaw('MONTH(created_at) as month, YEAR(created_at) as year, COUNT(*) as total_uses, SUM(word_count) as total_words, SUM(cost) as total_cost')
            ->groupBy('year', 'month')
            ->orderBy('year', 'desc')
            ->orderBy('month', 'desc')
            ->get();
    }

    /**
     * Get recent AI usage (last 30 days).
     */
    public function getRecentAiUsage($days = 30)
    {
        return $this->aiUsageLogs()
            ->where('created_at', '>=', now()->subDays($days))
            ->orderBy('created_at', 'desc')
            ->get();
    }
}