<?php

namespace App\Models;

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

class Product extends Model
{
    use HasFactory;

    protected $guarded = ['id', 'created_at', 'updated_at'];

    protected function casts(): array
    {
        return [
            'category_id' => 'integer',
            'price' => 'decimal:2',
            'discount_price' => 'decimal:2',
            'discount' => 'decimal:2',
            'clicks' => 'integer',
            'direct_commission_rate' => 'decimal:2',
            'estimated_direct_commission' => 'decimal:2',
            'indirect_commission_rate' => 'decimal:2',
            'estimated_indirect_commission' => 'decimal:2',
            'sales_180day' => 'integer',
            'positive_feedback' => 'decimal:2',
            'code_start_time' => 'datetime',
            'code_end_time' => 'datetime',
            'code_quantity' => 'integer',
            'code_minimum_spend' => 'decimal:2',
        ];
    }

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

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

    public function scopeFilterByPriceRange($query, $minPrice = null, $maxPrice = null)
    {
        if ($minPrice !== null) {
            $query->where('price', '>=', $minPrice);
        }
        if ($maxPrice !== null) {
            $query->where('price', '<=', $maxPrice);
        }

        return $query;
    }

    public function scopeSearch($query, $searchTerm)
    {
        return $query->where(function ($q) use ($searchTerm) {
            $q->where('name_ar', 'like', "%{$searchTerm}%")
                ->orWhere('name_en', 'like', "%{$searchTerm}%");
        });
    }

    public function scopeSortBy($query, $field, $direction = 'asc')
    {
        $allowedFields = ['price', 'discount_price', 'clicks', 'sales_180day', 'positive_feedback'];

        if (in_array($field, $allowedFields)) {
            return $query->orderBy($field, $direction);
        }

        return $query;
    }
}
