<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Product extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = ['name','code','cost', 'unit_of_measure_id',
        'type', 'image', 'minimum_stock', 'category_id'];

    protected $dates = ['deleted_at'];

    protected $appends = ['imageURL', 'warehouses_detail','percentages','nameCategory'];

    public function setCostAttribute($value)
    {
        $this->attributes['cost'] = round($value, 2);
    }

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

    public function warehouses(): BelongsToMany
    {
        return $this->belongsToMany(warehouse::class, 'warehouse_detail', 'product_id', 'warehouse_id')->withPivot(["stock"]);
    }

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


    public function brands()
    {
        return $this->belongsToMany(ProductBrand::class, 'product_brand_detail', 'product_id', 'product_brand_id');
    }

    public function prices()
    {
        return $this->hasMany(Price::class);
    }

    protected function getImageURLAttribute() {
        if($this->image) {
            return asset(\Storage::url('products/'.$this->image));
        }

        return '';
    }

    protected function getWarehousesDetailAttribute() {
        $warehousesDetail = [];

        if($this->warehouses) {
            foreach ($this->warehouses as $warehouse) {
                $warehousesDetail[] = [
                    'id' => $warehouse->pivot->id,
                    'warehouse_id' => $warehouse->id,
                    'initial_stock' => $warehouse->pivot->stock
                ];
            }
        }

        return $warehousesDetail;
    }

    protected function getPercentagesAttribute() {
        $percentages = [];

        $currencies = Currency::pluck('id')->toArray();

        foreach ($this->percentages_relation as $percentage) {
            $percentageDetails = [];

            // Collect existing currencies associated with price details
            $existingCurrencies = $percentage->details->pluck('pivot.currency_id')->toArray();

            // Get all currencies
            $allCurrencies = Currency::pluck('id')->toArray();

            // Merge existing currencies with all currencies and assign null if not existing
            $allCurrencies = array_merge($allCurrencies, $existingCurrencies);
            $allCurrencies = array_unique($allCurrencies);

            // Fetch percentages for each currency, assigning null if not found
            foreach ($allCurrencies as $currencyId) {
                $percentageDetail = $percentage->details->where('pivot.currency_id', $currencyId)->first();
                $percentageDetails[$currencyId] = $percentageDetail ? $percentageDetail->pivot->percentage : null;
            }

            $percentages[$percentage->client_category_id] = $percentageDetails;
        }

        $clientCategories = ClientCategory::pluck('id')->toArray();

        // Add null values for client categories and currencies that don't have associated percentages
        foreach ($clientCategories as $clientCategoryId) {
            if (!isset($percentages[$clientCategoryId])) {
                $percentages[$clientCategoryId] = array_fill_keys($currencies, null);
            }
        }

        return $percentages;
    }

    public function percentages_relation() {
        return $this->hasMany(ProductCategoryPercentage::class, 'product_category_id', 'category_id');
    }

   public function getnameCategoryAttribute()
    {
        return $this->category ? $this->category->name : null;
    }


    public function kardex(): HasMany
    {
        return $this->hasMany(Kardex::class, 'warehouse_detail_id', 'id');
    }
}
