<?php

namespace Modules\Product\Entities;

use App\Models\BaseModel;
use Illuminate\Database\Eloquent\Builder;
use Modules\Category\Entities\Model as Category;
use Modules\Client\Entities\Model as Client;
use Modules\Slider\Entities\Model as Slider;
use Modules\Order\Entities\ModelProduct as OrderProduct;

class Model extends BaseModel
{
    protected $table = 'products';
    protected $guarded = [];

    /* ==============================
     | Relationships
     ============================== */

    public function Categories()
    {
        return $this->belongsToMany(Category::class, 'product_categories','product_id','category_id');
    }

    public function Image()
    {
        return $this->hasOne(ModelImage::class, 'product_id');
    }

    public function Images()
    {
        return $this->hasMany(ModelImage::class, 'product_id');
    }

    public function Sections()
    {
        return $this->hasMany(ModelSection::class, 'product_id');
    }

    public function Items()
    {
        return $this->hasManyThrough(
            SectionItem::class,
            ModelSection::class,
            'product_id',
            'section_id'
        );
    }

    public function Rates()
    {
        return $this->hasMany(ModelReview::class, 'product_id');
    }

    public function Sliders()
    {
        return $this->morphMany(Slider::class, 'linkable');
    }

    /* ==============================
     | Boot
     ============================== */

    protected static function booted()
    {
        static::created(function ($model) {
            $model->updateQuietly([
                'arrangement' => $model->id,
            ]);
        });
    }

    /* ==============================
     | Discount Logic (Centralized)
     ============================== */

    public function activeDiscount(): ?array
    {
        $now = now();

        if (
            !is_null($this->discount) &&
            $this->from &&
            $this->to &&
            $now->between($this->from, $this->to)
        ) {
            return [
                'value' => $this->discount,
                'type'  => $this->discount_type,
            ];
        }

        if (
            setting('discount_value') &&
            setting('discount_from') &&
            setting('discount_to') &&
            $now->between(setting('discount_from'), setting('discount_to'))
        ) {
            return [
                'value' => setting('discount_value'),
                'type'  => setting('discount_type'),
            ];
        }

        return null;
    }

    public function hasDiscount(): bool
    {
        return !is_null($this->activeDiscount());
    }

    public function discountValue(): float
    {
        $discount = $this->activeDiscount();

        if (!$discount) {
            return 0;
        }

        return (float) $discount['value'];
    }

    public function discountType(): ?string
    {
        return $this->activeDiscount()['type'] ?? null;
    }

    /* ==============================
     | Price Calculation
     ============================== */

    public function calcPrice(): string
    {
        $price = $this->price;
        
        if($price > 0){
            if ($this->hasDiscount()) {
                if ($this->discountType() === 'percentage') {
                    $price -= ($price * $this->discountValue() / 100);
                } else {
                    $price -= $this->discountValue();
                }
            }
        }

        return number_format(
            $price * Country()->currancy_value,
            Country()->decimals,
            '.',
            ''
        );
    }

    public function price(): string
    {
        return number_format(
            $this->price * Country()->currancy_value,
            Country()->decimals,
            '.',
            ''
        );
    }

    /* ==============================
     | Accessors
     ============================== */

    public function getRateAttribute(): float
    {
        return $this->rates()
            ->whereNotNull('rate')
            ->where('rate', '>=', 0)
            ->avg('rate') ?? 0;
    }

    public function getIsFavAttribute(): bool
    {
        $clientId = auth('sanctum')->id() ?? auth('client')->id();

        if (!$clientId) {
            return false;
        }

        return $this->belongsToMany(Client::class, 'product_favourites','product_id','client_id')
            ->wherePivot('client_id', $clientId)
            ->exists();
    }

    /* ==============================
     | Helpers
     ============================== */

    public function randomImage(): ?string
    {
        return $this->images()
            ->inRandomOrder()
            ->value('image');
    }
    
    
    
    public function orderProducts()
    {
        return $this->hasMany(OrderProduct::class, 'product_id');
    }
}
