<?php

namespace App\Models;

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

class CountryStoreStats extends Model
{
    use HasFactory;

    protected $fillable = [
        'country_store_id',
        'followers_count',
        'uses_count',
        'views_count',
        'impressions_count',
        'popularity',
        'max_discount',
        'avg_discount',
        'last_offer_added_at',
        'last_usage',
    ];

    protected $casts = [
        'followers_count' => 'integer',
        'uses_count' => 'integer',
        'views_count' => 'integer',
        'impressions_count' => 'integer',
        'popularity' => 'integer',
        'max_discount' => 'decimal:2',
        'avg_discount' => 'decimal:2',
        'last_offer_added_at' => 'datetime',
        'last_usage' => 'datetime',
    ];

    // ✅ FIX: Relations with explicit foreign key
    public function countryStore()
    {
        return $this->belongsTo(CountryStore::class, 'country_store_id', 'id');
    }

    // Scopes
    public function scopePopular($query, $threshold = 100)
    {
        return $query->where('popularity', '>=', $threshold);
    }

    public function scopeHighDiscount($query, $minDiscount = 50)
    {
        return $query->where('max_discount', '>=', $minDiscount);
    }

    public function scopeRecentlyActive($query, $days = 30)
    {
        return $query->where('last_usage', '>=', now()->subDays($days));
    }

    // Helper Methods
    public function incrementFollowers($amount = 1)
    {
        $this->increment('followers_count', $amount);
        $this->updatePopularity();
    }

    public function incrementUses($amount = 1)
    {
        $this->increment('uses_count', $amount);
        $this->update(['last_usage' => now()]);
        $this->updatePopularity();
    }

    public function incrementViews($amount = 1)
    {
        $this->increment('views_count', $amount);
        $this->updatePopularity();
    }

    public function incrementImpressions($amount = 1)
    {
        $this->increment('impressions_count', $amount);
    }

    public function updateDiscountStats()
    {
        $offers = $this->countryStore->offers()
                       ->where('status', 'active')
                       ->whereNotNull('discount_value');

        $this->update([
            'max_discount' => $offers->max('discount_value'),
            'avg_discount' => $offers->avg('discount_value'),
        ]);
    }

    public function updatePopularity()
    {
        // Simple popularity calculation based on activity
        $popularity = ($this->followers_count * 2) + 
                     ($this->uses_count * 3) + 
                     ($this->views_count * 1);

        $this->update(['popularity' => $popularity]);
    }

    public function markOfferAdded()
    {
        $this->update(['last_offer_added_at' => now()]);
        $this->updateDiscountStats();
    }
}