<?php

namespace App\Models;

use App\Classes\General\PublicConstants;
use App\Classes\Helpers\FileHelper;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable=[
        'title',
        'slug',
        'sub_title',
        'price',
        'original_price',
        'rating',
        'description',
        'about',
        'image',
        'quantity',
        'category_id'
    ];
    public static function rules($id=null)
    {
        return [
            'title' => 'required|string|max:255',
            'slug' => 'required|string|max:255|unique:products,slug,' . $id,
            'sub_title' => 'nullable|string|max:255',
            'price' => 'numeric|min:0',
            'original_price' => 'numeric|min:0',
            'rating' => 'nullable|numeric|min:0|max:5',
            'description' => 'nullable|string',
            'about' => 'nullable|string',
            'imageFile' => 'nullable|image|max:2048',
            'quantity' => 'required|integer|min:0',
            'category_id' => 'required|exists:product_categories,id'
        ];
    }
    public function Category()
    {
        return $this->belongsTo(ProductCategory::class, 'category_id');
    }
    public function ProductImages()
    {
        return $this->hasMany(ProductImage::class);
    }
    public function RatingPercentage(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->rating ? ($this->rating / 5) * 100 : 0
        );
    }
    public function AboutLines(): Attribute
    {
        return Attribute::make(
            get: fn () => explode("\n", $this->about)
        );
    }
    protected function imageUrl(): Attribute
    {
        return Attribute::make(
            get: fn () =>FileHelper::FileLink(PublicConstants::PRODUCT_IMAGE_PATH, $this->image)
        );
    } 

}
