<?php

namespace App\Models;

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

class Deal extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'title',
        'description',
        'url',
        'image_url',
        'price',
        'original_price',
        'store_name',
        'category',
        'is_pinned',
        'is_active',
        'expires_at',
        'upvotes',
        'downvotes'
    ];

    protected function casts(): array
    {
        return [
            'price' => 'decimal:2',
            'original_price' => 'decimal:2',
            'is_pinned' => 'boolean',
            'is_active' => 'boolean',
            'expires_at' => 'datetime',
        ];
    }

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

    public function comments()
    {
        return $this->hasMany(DealComment::class)->latest();
    }

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

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

    public function scopeCategory($query, $category)
    {
        if ($category && $category !== 'all') {
            return $query->where('category', $category);
        }
        return $query;
    }

    public function getSavingsAttribute()
    {
        if ($this->original_price && $this->price) {
            return $this->original_price - $this->price;
        }
        return null;
    }

    public function getSavingsPercentAttribute()
    {
        if ($this->original_price && $this->price && $this->original_price > 0) {
            return round((($this->original_price - $this->price) / $this->original_price) * 100);
        }
        return null;
    }

    public function getIsExpiredAttribute()
    {
        return $this->expires_at && $this->expires_at->isPast();
    }

    public function getScoreAttribute()
    {
        return $this->upvotes - $this->downvotes;
    }

    public function getIsHotAttribute()
    {
        return $this->score >= 3 && !$this->is_expired;
    }

    public function getIsNewAttribute()
    {
        return $this->created_at->gt(now()->subHours(48));
    }

    public function getIsEndingSoonAttribute()
    {
        return $this->expires_at
            && !$this->is_expired
            && $this->expires_at->lt(now()->addDays(3));
    }

    public function getDomainAttribute()
    {
        $host = parse_url($this->url, PHP_URL_HOST);
        return $host ? preg_replace('/^www\./', '', $host) : null;
    }
}
