<?php

namespace App\Livewire\Forms\Studio\Manage;

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

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

    public ?Purchase $purchase = null;

    public ?string $invoice_number = null;

    public ?string $note = null;

    public string $purchase_date = '';

    public string $total = '';

    public string $warehouse_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'],
            'warehouse_id' => ['required', Rule::exists('warehouses', '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',
            'warehouse_id' => 'gudang',
            'image' => 'gambar',
        ];
    }

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

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

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

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

        $purchaseItems = $this->loadPurchaseItems();

        // Recalculate total to ensure data integrity
        $calculatedTotal = $purchaseItems->sum(function ($item) {
            return $item->unit_price * $item->quantity;
        });

        // Override the total input with the calculated one to prevent mismatches
        $this->total = formatCurrencyNumber($calculatedTotal);

        DB::transaction(function () use ($purchaseItems, $calculatedTotal) {
            $data = $this->prepareSavedData();
            $data['total'] = $calculatedTotal; // Use strict calculated total

            $purchase = Purchase::create($data);

            $purchase->load('warehouse');

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

            foreach ($purchaseItems as $item) {
                // Ensure item integrity before linking
                if ($item->quantity <= 0 || $item->unit_price <= 0) {
                    continue; // Or throw exception
                }

                $item->update(['purchase_id' => $purchase->id]);

                $this->increaseWarehouseStock($purchase->warehouse, $item);
            }
        });
    }

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