<?php

namespace App\Livewire\Blesser;

use Livewire\Component;
use App\Models\PreInvoice;
use Livewire\WithFileUploads;
use App\Models\PreInvoiceItem;

class PreInvoiceForm extends Component
{
    use WithFileUploads;

    public $invoice_files = [];
    public $preInvoiceId = null;

    public $customer_name;
    public $company_name;
    public $email;
    public $phone;
    public $address;
    public $city;
    public $postal_code;
    public $notes;

    public $items = [];

    protected $messages = [
        'items.*.name.required' => 'نام هر کالا الزامی است.',
        'items.*.qty.required' => 'تعداد کالا الزامی است.',
    ];
    protected function rules()
    {
        return [
            'customer_name' => 'required|string|max:255',
            'company_name' => 'nullable|string|max:255',
            'email' => 'nullable|email',
            'phone' => 'required|string|max:50',
            'address' => 'nullable|string|max:500',
            'city' => 'nullable|string|max:255',
            'postal_code' => 'nullable|string|max:50',
            'notes' => 'nullable|string',
            'items' => 'required|array|min:1',
            'items.*.name' => 'required|string|max:255',
            'items.*.qty' => 'required|integer|min:1',
            'items.*.unit' => 'nullable|string|max:20',
            'items.*.external_url' => 'nullable|url',
            'items.*.description' => 'nullable|string',
            'invoice_files.*' => 'nullable|file|max:10240|mimes:jpg,jpeg,png,mp4,mov,avi,mp3,wav,pdf',
            'items.*.files.*' => 'nullable|file|max:10240|mimes:jpg,jpeg,png,mp4,mov,avi,mp3,wav,pdf',
        ];
    }

    public function mount($preInvoice = null)
    {
        if ($preInvoice instanceof PreInvoice) {
            $this->preInvoiceId = $preInvoice->id;
            $this->fill($preInvoice->only([
                'customer_name',
                'company_name',
                'email',
                'phone',
                'address',
                'city',
                'postal_code',
                'notes'
            ]));

            $this->items = $preInvoice->items->map(function ($item) {
                return [
                    'id' => $item->id,
                    'name' => $item->name,
                    'qty' => $item->qty,
                    'unit' => $item->unit,
                    'external_url' => $item->external_url,
                    'description' => $item->description,
                ];
            })->toArray();
        } else {
            $this->items = [
                ['name' => '', 'qty' => 1, 'unit' => '', 'external_url' => '', 'description' => '', 'files' => []]
            ];
        }
    }

    public function addItem()
    {
        $this->items[] = ['name' => '', 'qty' => 1, 'unit' => '', 'external_url' => '', 'description' => ''];
    }

    public function removeItem($index)
    {
        if (isset($this->items[$index])) {
            $item = $this->items[$index];
            if (!empty($item['id']) && $this->preInvoiceId) {
                PreInvoiceItem::find($item['id'])?->delete();
            }
            array_splice($this->items, $index, 1);
        }
    }

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

        $data = $this->only([
            'customer_name',
            'company_name',
            'email',
            'phone',
            'address',
            'city',
            'postal_code',
            'notes'
        ]);

        if ($this->preInvoiceId) {
            $pre = PreInvoice::findOrFail($this->preInvoiceId);
            $pre->update($data);
        } else {
            $pre = PreInvoice::create(array_merge($data, [
                'creator_id' => auth()->user()->id,
                'status' => 'open'
            ]));
        }

        // sync items
        foreach ($this->items as $item) {
            if (!empty($item['id'])) {
                PreInvoiceItem::find($item['id'])?->update($item);
            } else {
                $pre->items()->create($item);
            }
        }

        session()->flash('success', 'پیش‌فاکتور با موفقیت ذخیره شد.');

        $this->reset();
    }

    public function render()
    {
        return view('livewire.blesser.pre-invoice-form');
    }
}
