<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

/**
 * Unit model
 * 
 * This model represents the units in the application.
 * It is used to store the units and their associated data.
 */
class Unit extends Model
{
    use \Illuminate\Database\Eloquent\SoftDeletes;
    const UNITS = [
        ['name' => 'Bouteille', 'symbol' => 'btl', 'slug' => 'bouteille', 'description' => 'Unité de mesure pour les bouteilles'],
        ['name' => 'Comprimé', 'symbol' => 'cp', 'slug' => 'comprime', 'description' => 'Unité de mesure pour les comprimés'],
        ['name' => 'Capsule', 'symbol' => 'cap', 'slug' => 'capsule', 'description' => 'Unité de mesure pour les capsules'],
        ['name' => 'Ampoule', 'symbol' => 'amp', 'slug' => 'ampoule', 'description' => 'Unité de mesure pour les ampoules'],
        ['name' => 'Boîte', 'symbol' => 'bt', 'slug' => 'boite', 'description' => 'Unité de mesure pour les boîtes'],
        ['name' => 'Tablette', 'symbol' => 'tbt', 'slug' => 'tablette', 'description' => 'Unité de mesure pour les tablettes'],
        ['name' => 'Tube', 'symbol' => 'tb', 'slug' => 'tube', 'description' => 'Unité de mesure pour les tubes'],
    ];

    protected $guarded = [];

    public function getRouteKeyName()
    {
        return 'slug';
    }

    // Products where this unit is used as purchase unit
    public function productsAsPurchaseUnit()
    {
        return $this->hasMany(Product::class, 'purchase_unit_id');
    }

    // Products where this unit is used as sale unit
    public function productsAsSaleUnit()
    {
        return $this->hasMany(Product::class, 'sale_unit_id');
    }

    // All products that use this unit (either as purchase or sale unit)
    public function products()
    {
        return $this->hasMany(Product::class, 'purchase_unit_id')
            ->orWhere('sale_unit_id', $this->id);
    }

    // Get total count of products using this unit
    public function getTotalProductsCountAttribute()
    {
        return $this->productsAsPurchaseUnit()->count() + $this->productsAsSaleUnit()->count();
    }

    public static function generateUniqueSlug($name)
    {
        $slug = Str::slug($name);
        $query = self::where('slug', 'like', "{$slug}%");

        $count = $query->count();
        if ($count > 0) {
            $slug .= '-' . ($count + 1);
        }

        return $slug;
    }
}
