<?php

namespace App\Livewire\Forms\Studio\Catalog;

use App\Models\Product;
use App\Rules\UnsignedInteger;
use App\Traits\WithMediaHandler;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Livewire\Form;

class ProductForm extends Form
{
    use WithMediaHandler;

    public ?Product $product = null;

    public string $name = '';

    public string $sku = '';

    public string $cost_price = '';

    public string $sale_price = '';

    public ?string $description = null;

    public array $image = [];

    public array $outlet_ids = [];

    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:50'],
            'sku' => [
                'required',
                'string',
                'max:20',
                Rule::unique('products', 'sku')->ignore($this->product),
            ],
            'cost_price' => ['required', new UnsignedInteger],
            'sale_price' => ['required', new UnsignedInteger],
            'description' => ['nullable', 'string'],
            'outlet_ids' => ['required', 'array', 'min:1'],
            'outlet_ids.*' => Rule::exists('outlets', 'id'),
            'image' => ['nullable', 'array', 'max:1'],
        ];
    }

    public function validationAttributes(): array
    {
        return [
            'name' => 'nama',
            'cost_price' => 'harga beli',
            'sale_price' => 'harga jual',
            'description' => 'deskripsi',
            'outlet_ids' => 'outlet',
            'image' => 'gambar',
        ];
    }

    public function setProduct(Product $product)
    {
        $product->load('outlets');

        $this->product = $product;

        $this->name = $product->name;
        $this->sku = $product->sku;
        $this->cost_price = $product->cost_price;
        $this->sale_price = $product->sale_price;
        $this->description = $product->description;
        $this->outlet_ids = $this->product->outlets->pluck('id')->toArray();
        $this->image = $this->mapMediaCollection($product->getMedia('image'));
    }

    public function store()
    {
        $this->validate();

        $data = $this->prepareSavedData();

        DB::transaction(function () use ($data) {
            $product = Product::create($data);

            $product->outlets()->attach($this->outlet_ids);

            $this->uploadMedia($this->image, $product, 'image');
        });
    }

    public function update()
    {
        $this->validate();

        $data = $this->prepareSavedData();

        DB::transaction(function () use ($data) {
            $this->product->update($data);

            $this->product->outlets()->sync($this->outlet_ids);

            $this->syncMedia($data['image'], $this->product, 'image');
            $this->uploadMedia($data['image'], $this->product, 'image');
        });
    }

    private function prepareSavedData()
    {
        return [
            'name' => $this->name,
            'sku' => $this->sku,
            'cost_price' => replaceCurrency($this->cost_price),
            'sale_price' => replaceCurrency($this->sale_price),
            'description' => $this->description,
            'outlet_ids' => $this->outlet_ids,
            'image' => $this->image,
        ];
    }
}
