<?php

namespace App\Livewire\Forms\Studio\Manage;

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

class PurchaseForm extends Form
{
    use WithMediaHandler, WithPurchaseItems, WithUpdateStock;

    public ?Purchase $purchase = null;

    public ?string $invoice_number = null;

    public ?string $note = null;

    public string $purchase_date = '';

    public string $total = '';

    public string $outlet_id = '';

    public array $image = [];

    public string $perfume_id = '';

    public string $quantity_perfume = '';

    public string $product_id = '';

    public string $quantity_product = '';

    public string $bottle_id = '';

    public string $quantity_bottle = '';

    public string $item_id = '';

    public string $quantity_edit = '';

    public function rules(): array
    {
        return [
            'invoice_number' => ['nullable', 'string', 'max:50'],
            'note' => ['nullable', 'string', 'max:100'],
            'purchase_date' => ['required', 'date', 'before_or_equal:today'],
            'outlet_id' => ['required', Rule::exists('outlets', 'id')],
            'total' => ['required', new UnsignedInteger],
            'image' => ['nullable', 'array', 'max:1'],
        ];
    }

    public function validationAttributes(): array
    {
        return [
            'invoice_number' => 'nomor invoice',
            'note' => 'catatan',
            'purchase_date' => 'tanggal belanja',
            'outlet_id' => 'outlet',
            'image' => 'gambar',
        ];
    }

    public function setPurchase(Purchase $purchase)
    {
        $this->purchase = $purchase;

        $this->invoice_number = $purchase->invoice_number;
        $this->note = $purchase->note;
        $this->purchase_date = $purchase->purchase_date;
        $this->outlet_id = $purchase->outlet_id;
        $this->total = $purchase->total;

        $this->image = $this->mapMediaCollection($purchase->getMedia('image'));
    }

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

        $purchaseItems = $this->loadPurchaseItems();

        DB::transaction(function () use ($purchaseItems) {
            $purchase = Purchase::create($this->prepareSavedData());

            $purchase->load('outlet');

            $this->uploadMedia($this->image, $purchase, 'image');

            foreach ($purchaseItems as $item) {
                $item->update(['purchase_id' => $purchase->id]);

                $this->increaseOutletStock($purchase->outlet, $item);
            }
        });
    }

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

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

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

    private function prepareSavedData(): array
    {
        return [
            'invoice_number' => $this->invoice_number,
            'note' => $this->note,
            'outlet_id' => $this->outlet_id,
            'purchase_date' => $this->purchase_date,
            'total' => replaceCurrency($this->total),
        ];
    }
}
