<?php

namespace App\Models\PRODUCT;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;
use OwenIt\Auditing\Contracts\Auditable;
use App\Models\STOCK\Stocklog;
use App\Models\STOCK\Stocksnapshot;

class Product extends Model implements Auditable
{
    use HasFactory, SoftDeletes, \OwenIt\Auditing\Auditable;

    /*
    |--------------------------------------------------------------------------
    | Fillable
    |--------------------------------------------------------------------------
    */
    protected $fillable = [
        /* Identifiers */
        'uid',
        'ref',

        /* Basic Info */
        'name',
        'status',
        'description',
        'type',

        /* Classification */
        'category',
        'brand',
        'attribute',
        'hasAttribute',

        /* Units & Physical Properties */
        'unit',
        'volume',
        'weight',
        'itemInBox',
        'dimension',

        /* Pricing & Tax */
        'salePrice',
        'costPrice',
        'tax',

        /* Inventory */
        'minStock',
        'maxStock',
        'location',

        /* BOM & Media */
        'bom',
        'variant',
        'images',
        'documents',

        /* Immobilisation */
        'favorite',
        'sellable',
        'buyable',

        /* Flags */
        'amortisationYears',
        'amortisationRate',
        'annualAmortisation',
        'descriptionImmobilisation',

        /* Expiration */
        'hasExpiration'
    ];

    /*
    |--------------------------------------------------------------------------
    | Casts
    |--------------------------------------------------------------------------
    */
    protected $casts = [
        /* Decimal fields */
        'volume' => 'decimal:2',
        'weight' => 'decimal:2',
        'itemInBox' => 'decimal:2',
        'salePrice' => 'decimal:2',
        'costPrice' => 'decimal:2',
        'minStock' => 'decimal:2',
        'maxStock' => 'decimal:2',

        /* JSON fields */
        'unit' => 'array',
        'category' => 'array',
        'brand' => 'array',
        'attribute' => 'array',
        'type' => 'array',
        'tax' => 'array',
        'bom' => 'array',
        'variant' => 'array',
        'images' => 'array',
        'documents' => 'array',

        /* Boolean fields */
        'favorite' => 'boolean',
        'sellable' => 'boolean',
        'buyable' => 'boolean',
        'hasAttribute' => 'boolean',
        'hasExpiration' => 'boolean',
    ];

    /*
    |--------------------------------------------------------------------------
    | Boot (UID Auto-generation)
    |--------------------------------------------------------------------------
    */
    protected static function boot()
    {
        parent::boot();
        static::creating(function ($model) {
            if (empty($model->uid)) {
                $model->uid = (string) Str::ulid();
            }
            if (empty($model->ref)) {
                self::generateRef($model);
            }
            if (empty($model->tax)) {
                $model->tax = [
                    'name'  => 'TVA (0%)',
                    'value' => 0
                ];
            }
        });

        static::updating(function ($model) {
            if (empty($model->ref)) {
                self::generateRef($model);
            }
            if (empty($model->tax)) {
                $model->tax = [
                    'name'  => 'TVA (0%)',
                    'value' => 0
                ];
            }
        });
    }

  
    protected static function generateRef($model)
    {
        if (empty($model->ref) && $model->category) {

            $prefix = strtoupper(substr($model->category['name'], 0, 4));

            $lastRef = self::where('ref', 'like', $prefix . '%')
                ->orderBy('ref', 'desc')
                ->value('ref');

            $number = $lastRef
                ? ((int) substr($lastRef, strlen($prefix)) + 1)
                : 1;

            $model->ref = $prefix . str_pad($number, 5, '0', STR_PAD_LEFT);
        }
    }

    public function stocklogs()
    {
        return $this->hasMany(Stocklog::class, 'productId');
    }

    public function stocknapshot()
    {
        return $this->hasOne(Stocksnapshot::class, 'productId');
    }
}
