<?php

namespace App\Models;

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

class ProductVariant extends Model
{
    protected $fillable = [
        'product_id',
        'sku',
        'price',
        'quantity',
        'security_stock',
        'options',
    ];

    protected $casts = [
        'price' => 'decimal:2',
        'quantity' => 'integer',
        'security_stock' => 'integer',
        'options' => 'array', // automatically casts json option keys
    ];

    protected static function booted()
    {
        static::saved(function ($variant) {
            $variant->syncParentQuantity();
        });

        static::deleted(function ($variant) {
            $variant->syncParentQuantity();
        });
    }

    public function syncParentQuantity()
    {
        $product = $this->product;
        if ($product) {
            if ($product->variants()->exists()) {
                $totalVariantsQty = $product->variants()->sum('quantity');
                $product->updateQuietly(['quantity' => $totalVariantsQty]);
            }
        }
    }

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

    /**
     * Mutator to format the options array from form repeater list to database key-value JSON
     */
    public function setOptionsAttribute($value)
    {
        if (is_array($value)) {
            // Check if it's the list of [{attribute_name, attribute_value}] from the form
            $firstItem = reset($value);
            if (is_array($firstItem) && array_key_exists('attribute_name', $firstItem)) {
                $formatted = [];
                foreach ($value as $item) {
                    if (!empty($item['attribute_name']) && !empty($item['attribute_value'])) {
                        $formatted[$item['attribute_name']] = $item['attribute_value'];
                    }
                }
                $this->attributes['options'] = json_encode($formatted);
                return;
            }
        }
        $this->attributes['options'] = is_array($value) ? json_encode($value) : $value;
    }

    /**
     * Mutator to ensure security stock is always an integer.
     */
    public function setSecurityStockAttribute($value)
    {
        $this->attributes['security_stock'] = (int) ($value ?? 0);
    }
}
