<?php

namespace App\Livewire\Forms\Studio\Finance;

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

class ExpenseForm extends Form
{
    use WithMediaHandler;

    public ?Expense $expense = null;

    public string $description = '';

    public string $amount = '';

    public string $outlet_id = '';

    public array $image = [];

    public function rules(): array
    {
        return [
            'description' => ['required', 'string', 'max:100'],
            'amount' => ['required', new UnsignedInteger],
            'outlet_id' => [Rule::requiredIf(auth()->user()->outlets()->count() > 1), Rule::exists('outlets', 'id')],
            'image' => ['nullable', 'array'],
        ];
    }

    public function validationAttributes(): array
    {
        return [
            'description' => 'keterangan',
            'amount' => 'jumlah',
            'image' => 'gambar',
        ];
    }

    public function setExpense(Expense $expense)
    {
        $this->expense = $expense;

        $this->description = $expense->description;
        $this->amount = $expense->amount;
        $this->outlet_id = $expense->outlet_id;

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

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

        DB::transaction(function () {
            $expense = Expense::create([
                'type' => ExpenseType::OPERATIONAL,
                'description' => $this->description,
                'amount' => replaceCurrency($this->amount),
                'outlet_id' => auth()->user()->outlets()->count() > 1 ? $this->outlet_id : auth()->user()->outlets()->first()->id,
            ]);

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

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

        DB::transaction(function () {
            $this->expense->update([
                'description' => $this->description,
                'amount' => replaceCurrency($this->amount),
            ]);

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