<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Seller extends Model
{
    use HasFactory;


    protected static function boot()
    {
        parent::boot();

        static::creating(function ($seller) {
            if (empty($seller->slug)) {
                $base = $seller->company_name ?: ($seller->user->name ?? 'seller');
                $seller->slug = static::generateUniqueSlug($base);
            }
        });

        static::updating(function ($seller) {
            if (empty($seller->slug) && !empty($seller->company_name)) {
                $seller->slug = static::generateUniqueSlug($seller->company_name);
            }
        });
    }

    protected static function generateUniqueSlug($name)
    {
        $slug = Str::slug($name);
        $count = static::where('slug', 'LIKE', "{$slug}%")->count();
        return $count ? "{$slug}-" . ($count + 1) : $slug;
    }


    protected $fillable = [
        'user_id',
        'company_name',
        'mobile',
        'product_range',
        'price_range_min',
        'price_range_max',
        'business_description',
        'category_id',
        'gst',
        'gst_doc',
        'gst_number',
        'pan_number',
        'udyam_number',
        'iec',
        'iec_doc',
        'state',
        'country',
        'moq',
        'moq_quantity',
        'moq_unit_id',
        'moq_range_start',
        'moq_range_end',
        'is_verified',
        'is_active',
        'notification_enabled',
        'kyc_status',
        'registration_step',
        'subscription_id',
        'slug',
        'logo',
        'banner',
        'about',
        'facebook',
        'twitter',
        'linkedin',
        'instagram',
        'theme_color',
        'google_map_embed',
        'business_type',
        'business_type_json',
        'address',
        'city',
        'pincode',
        'bank_name',
        'account_name',
        'account_number',
        'ifsc_code',
        'branch_name',
        'pan_no',
        'pan_doc',
        'cancelled_cheque_doc',
        'photo',
        'delete_requested_at',
        'iec_code',
    ];

    protected $casts = [
        'delete_requested_at' => 'datetime',
        'is_verified' => 'boolean',
        'is_active' => 'boolean',
        'notification_enabled' => 'boolean',
        'business_type_json' => 'array',
        'business_type' => 'array',
        'moq_quantity' => 'integer',
        'moq_range_start' => 'integer',
        'moq_range_end' => 'integer',
    ];

    /**
     * Scope to filter only active sellers
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Check if seller is active
     */
    public function isActive(): bool
    {
        return $this->is_active ?? true;
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    public function unit()
    {
        return $this->belongsTo(Unit::class, 'moq_unit_id');
    }

    public function subscription()
    {
        return $this->belongsTo(Subscription::class);
    }

    public function products()
    {
        return $this->hasMany(Product::class);
    }

    public function inquiries()
    {
        return $this->hasMany(Inquiry::class);
    }

    public function quotes()
    {
        return $this->hasMany(Quote::class);
    }

    public function rfqs()
    {
        // Sellers might receive RFQs or respond to them. 
        // If sellers just view RFQs, no direct relation needed unless 'responses' table exists.
        // Prompt said "hasMany Rfqs". Assuming this means RFQs assigned/responded? 
        // Or maybe it meant Buyer hasMany Rfqs. 
        // Re-reading prompt: "Seller model: ... hasMany Rfqs". 
        // This is ambiguous without an intermediate table or seller_id on rfqs (which is not in schema).
        // Schema has `rfqs` with `buyer_id`. 
        // Maybe it implies `hasManyThrough` if RFQs are targeted?
        // Or maybe I should add `seller_id` to RFQs? 
        // The schema I created for RFQs only has `buyer_id`.
        // I will skip this for now or assume it's a mistake in prompt vs schema, 
        // OR it refers to a future feature. 
        // Wait, prompt 3 says "Seller model: ... hasMany Rfqs".
        // Let's assume it's a mistake and it meant Buyer, OR it means RFQs relevant to seller's category?
        // Let's stick to what's possible. 
        // Actually, if I look at prompt 3 again: "User ... hasMany Rfqs (for buyers)".
        // "Seller model: ... hasMany Rfqs". 
        // Maybe it means "Received Rfqs"? 
        // I'll leave it out for now to avoid error, as there is no column.
        return $this->hasMany(Rfq::class); // This would require seller_id on rfqs table.
    }

    public function plan()
    {
        return $this->hasOneThrough(Plan::class, Subscription::class, 'id', 'id', 'subscription_id', 'plan_id');
    }

    public function scopeVerified($query)
    {
        return $query->where('is_verified', true);
    }

    public function scopeSubscribed($query)
    {
        return $query->whereHas('subscription', function ($q) {
            $q->whereIn('status', ['active', 'grace_period'])
              ->where('end_date', '>=', now()->subDays(3));
        });
    }

    public function hasActiveSubscription()
    {
        return $this->subscription()
                    ->whereIn('status', ['active', 'grace_period'])
                    ->where('end_date', '>=', now()->subDays(3))
                    ->exists();
    }

    /**
     * Check if seller can receive inquiry notifications
     * Paid sellers always get notifications
     * Free sellers only if admin enabled
     */
    public function canReceiveNotifications()
    {
        // Paid sellers always get notifications
        if ($this->hasActiveSubscription()) {
            return true;
        }
        
        // Free sellers only if admin enabled
        return $this->notification_enabled ?? false;
    }

    public function activeSubscription()
    {
        return $this->subscription;
    }

    /**
     * Check if seller's subscription is expired
     */
    public function isSubscriptionExpired(): bool
    {
        if (!$this->subscription) {
            return true; // No subscription = expired
        }
        
        return $this->subscription->isExpired();
    }

    public function reviews()
    {
        return $this->hasMany(Review::class);
    }

    public function getAverageRatingAttribute()
    {
        return $this->reviews()->where('is_approved', true)->avg('rating') ?? 0;
    }

    // Scout Searchable Structure
    public function toSearchableArray()
    {
        return [
            'id' => $this->id,
            'company_name' => $this->company_name,
            'about' => $this->about,
            'city' => $this->city,
            'state' => $this->state,
            'country' => $this->country,
        ];
    }

    public function banners()
    {
        return $this->hasMany(Banner::class)->orderBy('is_approved', 'desc')->orderBy('created_at', 'desc');
    }

    public function certificates()
    {
        return $this->hasMany(SellerCertificate::class);
    }

    public function kycDocuments()
    {
        return $this->hasMany(KycDocument::class);
    }

    public function pages()
    {
        return $this->hasMany(SellerPage::class);
    }

    public function testimonials()
    {
        return $this->hasMany(Testimonial::class);
    }

    public function faqs()
    {
        return $this->hasMany(Faq::class);
    }

    public function micrositeSettings()
    {
        return $this->hasOne(MicrositeSetting::class);
    }

    public function getOrCreateMicrositeSettings()
    {
        if (!$this->micrositeSettings) {
            $yearsInBusiness = 0;
            if ($this->created_at) {
                $yearsInBusiness = now()->year - $this->created_at->year;
            }
            
            return $this->micrositeSettings()->create([
                'tagline' => 'Quality Products & Services',
                'years_in_business' => $yearsInBusiness,
                'happy_clients' => 100,
                'products_sold' => $this->products()->count(),
            ]);
        }
        return $this->micrositeSettings;
    }

    /**
     * Check if seller has a paid active subscription
     * Used for displaying the Crown Badge
     */
    public function isPaid(): bool
    {
        if (!$this->hasActiveSubscription()) {
            return false;
        }
        
        // Check if the current plan is actually a paid one
        // We rely on the plan relation which is retrieved via subscription
        $plan = $this->plan;
        return $plan && $plan->price_inr > 0;
    }

    // ==================== SUBSCRIPTION USAGE HELPERS ====================

    /**
     * Get subscription usage statistics
     */
    public function getUsageStats(): array
    {
        $plan = $this->plan;
        $isActive = $this->hasActiveSubscription();
        
        // Default limits for free sellers
        $defaults = [
            'product_limit' => 3,
            'product_image_limit' => 4,
            'inquiry_limit' => 0,
            'banner_limit' => 0,
            'custom_page_limit' => 0,
        ];

        return [
            'is_subscribed' => $isActive,
            'plan_name' => $plan->name ?? 'Free',
            'days_remaining' => $this->getDaysRemaining(),
            'products' => [
                'used' => $this->products()->count(),
                'limit' => $plan->product_limit ?? $defaults['product_limit'],
            ],
            'inquiries' => [
                'sent' => $this->inquiries()->whereMonth('created_at', now()->month)->count(),
                'limit' => $plan->inquiry_limit ?? $defaults['inquiry_limit'],
            ],
            'banners' => [
                'used' => $this->banners()->count(),
                'limit' => $plan->banner_limit ?? $defaults['banner_limit'],
            ],
            'pages' => [
                'used' => $this->pages()->count(),
                'limit' => $plan->custom_page_limit ?? $defaults['custom_page_limit'],
            ],
            'features' => [
                'show_contact' => $plan->show_contact_details ?? false,
                'view_buyer_contact' => $plan->view_buyer_contact ?? false,
                'has_certificates' => $plan->has_certificates ?? false,
                'has_video' => $plan->has_video ?? false,
                'has_verified_badge' => $plan->has_verified_badge ?? false,
                'allow_microsite' => $plan->allow_microsite ?? false,
            ],
        ];
    }

    /**
     * Get days remaining in subscription
     */
    public function getDaysRemaining(): int
    {
        if (!$this->subscription || !$this->subscription->end_date) {
            return 0;
        }
        
        $days = now()->diffInDays($this->subscription->end_date, false);
        return max(0, (int) $days);
    }

    /**
     * Check if a specific limit is reached
     */
    public function isLimitReached(string $type): bool
    {
        $stats = $this->getUsageStats();
        
        if (!isset($stats[$type])) {
            return false;
        }
        
        return $stats[$type]['used'] >= $stats[$type]['limit'];
    }

    /**
     * Check if seller can use a specific feature
     */
    public function canUseFeature(string $feature): bool
    {
        $stats = $this->getUsageStats();
        return $stats['features'][$feature] ?? false;
    }
}
