<?php

namespace App\Livewire\Forms\Studio\Catalog;

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

class BottleForm extends Form
{
    use WithMediaHandler;

    public ?Bottle $bottle = null;

    public string $name = '';

    public string $size = '';

    public string $cost_price = '';

    public string $sale_price = '';

    public ?string $description = null;

    public array $outlet_ids = [];

    public array $image = [];

    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:50'],
            'size' => ['required', new UnsignedInteger],
            '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'],
        ];
    }

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

    public function setBottle(Bottle $bottle)
    {
        $this->bottle = $bottle;

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

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

        DB::transaction(function () {
            $bottle = Bottle::create($this->prepareSavedData());

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

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

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

        DB::transaction(function () {
            $this->bottle->update($this->prepareSavedData());

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

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

    private function prepareSavedData(): array
    {
        return [
            'name' => $this->name,
            'size' => $this->size,
            'cost_price' => replaceCurrency($this->cost_price),
            'sale_price' => replaceCurrency($this->sale_price),
            'description' => $this->description,
        ];
    }
}
