<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasOne;

class Product extends Model
{
    protected $table = 'product';
    protected $primaryKey = 'pid';
    protected string $imgPath = 'https://www.batteriestore.co.uk/img/';

    protected static function boot()
    {
        parent::boot(); // TODO: Change the autogenerated stub
    }

    protected static function booted(): void
    {
        static::addGlobalScope('stock', function (Builder $builder) {
            $builder->where('stock', 'ok')->orderBy('pid', 'desc');
        });
    }


    public function price(): Attribute
    {
        return Attribute::make(get: fn() => $this->pprice_eu);
    }
    public function priceSymbol(): Attribute
    {
        return new Attribute(get: fn() =>   symbol($this->price));
    }

    public function priceOld(): Attribute
    {
        return new Attribute(get: fn() =>  symbol($this->price /0.8));
    }

    public function jianjie1(): Attribute
    {
        return new Attribute(get: fn(string $value) => explode(' ', trim($value))[0]);
    }

    public function okpcode(): Attribute
    {
        return new Attribute(get: fn(string $value) => $this->imgPath . $value . '.jpg');
    }

    public function imgmore(): Attribute
    {
        return new Attribute(get: function ($value) {
            if ($value) {
                $images = array_map(fn($val) => $this->imgPath . $val . '.jpg', explode('|', $value));
                return array_unique(array_merge($images, [$this->okpcode]));
            } else {
                return [$this->okpcode];
            }
        });
    }

    public function comp(): Attribute
    {
        return new Attribute(get: function ($value) {
            $pattern = "/src=[\'|\"]([a-zA-Z0-9\_\-]{1,}\/)/i";
            $imgs = preg_match($pattern, $value, $arr);
            if ($imgs) {
                $replace = "src='" . '/imgorigin/';
                if (isset($arr[1])) $value = preg_replace($pattern, $replace, $value);
            }
            return $value;
        });
    }

    public function url(): Attribute
    {
        return new Attribute(get: fn() => strtolower(route('detail', [rawurlencode($this->cs), $this->category, $this->jianjie1, $this->pcode])));
    }

    public function parent(): BelongsTo
    {
        return $this->belongsTo(Category::class, 'category1', 'id');
    }

    public function cs(): Attribute
    {
        return new Attribute(get: fn($value) => ucfirst($value));
    }

    public function cart():HasOne
    {
        return  $this->HasOne(Cart::class, 'product_id', 'pid');
    }

    public function locale():Attribute
    {
        return  new Attribute(get: fn() => $this->category==='battery'?'batería':'cargador');
    }

}
