<?php

namespace App\Livewire\Forms\Studio\Catalog;

use App\Models\Outlet;
use App\Models\Product;
use App\Rules\UnsignedInteger;
use App\Services\StockActivityLogService;
use App\Traits\Media\WithMediaHandler;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Livewire\Form;

class ProductForm extends Form
{
    use WithMediaHandler;

    public ?Product $product = null;

    public string $name = '';

    public string $sku = '';

    public string $cost_price = '';

    public string $sale_price = '';

    public ?string $description = null;

    public array $image = [];

    public array $outlet_ids = [];

    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:50'],
            'sku' => [
                'required',
                'string',
                'max:20',
                Rule::unique('products', 'sku')->ignore($this->product),
            ],
            'cost_price' => [Rule::requiredIf(auth()->user()->hasRole(['Developer', 'Owner'])), 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', 'max:1'],
        ];
    }

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

    public function setProduct(Product $product): void
    {
        $product->load('outlets');

        $this->product = $product;

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

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

        $data = $this->prepareSavedData();

        DB::transaction(function () use ($data) {
            $product = Product::create($data);

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

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

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

        $data = $this->prepareSavedData();

        DB::transaction(function () use ($data) {
            $this->product->update($data);

            // Get old outlet IDs before sync
            $oldOutlets = $this->product->outlets()
                ->withPivot('stock')
                ->get()
                ->keyBy('id');

            $oldOutletIds = $oldOutlets->keys()->toArray();

            // Sync outlets
            $this->product->outlets()->sync($this->outlet_ids);

            // Outlet yang ter-detach
            $detachedOutletIds = array_diff($oldOutletIds, $this->outlet_ids);

            foreach ($detachedOutletIds as $outletId) {
                $outlet = $oldOutlets[$outletId];
                $previousStock = $outlet->pivot->stock ?? 0;

                if ($previousStock > 0) {
                    StockActivityLogService::log(
                        logName: 'Update Outlet',
                        event: 'Menghapus',
                        description: 'Outlet '.$outlet->name.' dihapus dari product '.$this->product->name,
                        performedOn: $this->product,
                        outlet: $outlet,
                        quantityChange: $previousStock,
                        previousStock: $previousStock,
                        newStock: 0,
                        extraProperties: [
                            'action' => 'detach_outlet',
                            'item_type' => 'product',
                            'item_id' => $this->product->id,
                        ]
                    );
                }
            }

            $this->syncMedia($data['image'], $this->product, 'image');
            $this->uploadMedia($data['image'], $this->product, 'image');
        });
    }

    private function prepareSavedData(): array
    {
        return [
            'name' => $this->name,
            'sku' => $this->sku,
            'cost_price' => parseRupiahToInt($this->cost_price == '' ? '0' : $this->cost_price),
            'sale_price' => parseRupiahToInt($this->sale_price),
            'description' => $this->description,
            'outlet_ids' => $this->outlet_ids,
            'image' => $this->image,
        ];
    }
}
