<?php

namespace App\Models;

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

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'category_id',
        'sku',
        'name',
        'slug',
        'description',
        'price',
        'discount_percent',
        'stock',
        'weight',
        'status',
        'type',
        'min_purchase',
        'label',
        'label_color',
        'cost_price',
        'service_form',
        'subscription_period',
        'download_link',
        'allow_dp',
        'digital_note',
    ];

    protected $casts = [
        'service_form' => 'array',
        'allow_dp' => 'boolean',
    ];

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

    public function images()
    {
        return $this->hasMany(ProductImage::class);
    }

    public function variants()
    {
        return $this->hasMany(ProductVariant::class);
    }

    public function stockHistories()
    {
        return $this->hasMany(StockHistory::class);
    }

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

    public function flashSaleProducts()
    {
        return $this->hasMany(FlashSaleProduct::class);
    }

    // Get active flash sale product if any
    public function getActiveFlashSaleAttribute()
    {
        $now = now();
        return $this->flashSaleProducts()
            ->whereHas('flashSale', function ($query) use ($now) {
                $query->where('is_active', true)
                    ->where('start_time', '<=', $now)
                    ->where('end_time', '>=', $now);
            })
            ->first();
    }

    // Get final price after discount
    public function getFinalPriceAttribute()
    {
        if ($this->discount_percent > 0) {
            return (float) ($this->price - ($this->price * $this->discount_percent / 100));
        }

        return (float) $this->price;
    }

    // Get calculated average rating
    public function getAverageRatingAttribute()
    {
        return round($this->reviews()->avg('rating') ?? 0, 1);
    }

    // Get calculated total sold count
    public function getSoldCountAttribute()
    {
        return (int) \Illuminate\Support\Facades\DB::table('order_items')
            ->join('orders', 'order_items.order_id', '=', 'orders.id')
            ->whereIn('orders.status', ['paid', 'processing', 'shipped', 'delivered', 'completed'])
            ->where('order_items.product_id', $this->id)
            ->sum('order_items.qty');
    }
    
    // Append average rating and sold count to array/json representation
    protected $appends = ['average_rating', 'sold_count', 'active_flash_sale', 'final_price'];
}
