<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;

class AdPackagePurchase extends Model
{
    protected $fillable = [
        'user_id',
        'package_id',
        'pricing_tier_id',
        'purchase_source',
        'ad_id',
        'location_country',
        'location_state',
        'location_city',
        'location_scope',
        'category_id',
        'subcategory_id',
        'total_paid',
        'currency',
        'features_granted',
        'usage_count',
        'usage_limit',
        'purchased_at',
        'expires_at',
        'last_used_at',
        'status',
    ];

    protected $casts = [
        'features_granted' => 'array',
        'total_paid' => 'decimal:2',
        'purchased_at' => 'datetime',
        'expires_at' => 'datetime',
        'last_used_at' => 'datetime',
    ];

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

    public function package()
    {
        return $this->belongsTo(AdPackage::class, 'package_id');
    }

    public function pricingTier()
    {
        return $this->belongsTo(PackagePricingTier::class, 'pricing_tier_id');
    }

    public function ad()
    {
        return $this->belongsTo(Ad::class);
    }

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

    public function subcategory()
    {
        return $this->belongsTo(Subcategory::class);
    }

    // Scopes
    public function scopeActive($query)
    {
        return $query->where('status', 'active')
                    ->where('expires_at', '>', now());
    }

    public function scopeExpired($query)
    {
        return $query->where('expires_at', '<=', now())
                    ->orWhere('status', 'expired');
    }

    public function scopeForCategory($query, $categoryId)
    {
        return $query->where('category_id', $categoryId);
    }

    public function scopeForLocation($query, $country, $state = null, $city = null)
    {
        $query->where('location_country', $country);
        
        if ($state) {
            $query->where('location_state', $state);
        }
        
        if ($city) {
            $query->where('location_city', $city);
        }
        
        return $query;
    }

    // Helper methods
    public function isActive()
    {
        return $this->status === 'active' && !$this->isExpired();
    }

    public function isExpired()
    {
        return $this->expires_at < now();
    }

    public function isExhausted()
    {
        return $this->usage_count >= $this->usage_limit;
    }

    public function canBeAppliedTo(Ad $ad)
    {
        // Check if package is still active
        if (!$this->isActive()) {
            return false;
        }

        // Check if usage limit reached
        if ($this->isExhausted()) {
            return false;
        }

        // Check category match
        if ($ad->category_id !== $this->category_id) {
            return false;
        }

        // Check subcategory if specified
        if ($this->subcategory_id && $ad->subcategory_id !== $this->subcategory_id) {
            return false;
        }

        // Check location match based on scope
        return $this->matchesLocation($ad);
    }

    protected function matchesLocation(Ad $ad)
    {
        switch ($this->location_scope) {
            case 'city':
                return $ad->location_city === $this->location_city &&
                       $ad->location_state === $this->location_state &&
                       $ad->location_country === $this->location_country;
            
            case 'state':
                return $ad->location_state === $this->location_state &&
                       $ad->location_country === $this->location_country;
            
            case 'country':
                return $ad->location_country === $this->location_country;
            
            case 'all_india':
                return $ad->location_country === 'India';
            
            default:
                return false;
        }
    }

    public function incrementUsage()
    {
        $this->increment('usage_count');
        $this->last_used_at = now();
        $this->save();

        // Check if exhausted
        if ($this->isExhausted()) {
            $this->status = 'exhausted';
            $this->save();
        }
    }

    public function markAsExpired()
    {
        $this->status = 'expired';
        $this->save();
    }

    public function getRemainingUsage()
    {
        return max(0, $this->usage_limit - $this->usage_count);
    }

    public function getDaysRemaining()
    {
        if ($this->isExpired()) {
            return 0;
        }
        
        return now()->diffInDays($this->expires_at, false);
    }

    public function getFeature($key, $default = null)
    {
        return $this->features_granted[$key] ?? $default;
    }
}
