<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\CompanySettings;
use App\Helpers\UnitHelper;
use App\Models\Item;
use App\Models\TaxRate;
use Illuminate\Http\Request;

class ItemController extends AdminController
{
    public function index()
    {
        $items = Item::with('taxRate')
            ->where('company_id', $this->companyId())
            ->latest()
            ->get();

        return view('admin.items.index', compact('items'));
    }

    public function create()
    {
        return view('admin.items.create', $this->formOptions());
    }

    public function store(Request $request)
    {
        $data = $this->validateItem($request);
        $data = $this->prepareItemData($request, $data, isNew: true);

        Item::create($data);

        return redirect()->route('admin.items.index')->with('success', 'Item created successfully.');
    }

    public function edit(Item $item)
    {
        $this->authorizeItem($item);

        return view('admin.items.edit', array_merge(
            ['item' => $item],
            $this->formOptions()
        ));
    }

    public function update(Request $request, Item $item)
    {
        $this->authorizeItem($item);

        $data = $this->validateItem($request);
        $data = $this->prepareItemData($request, $data, isNew: false, item: $item);

        $item->update($data);

        return redirect()->route('admin.items.index')->with('success', 'Item updated successfully.');
    }

    public function destroy(Item $item)
    {
        $this->authorizeItem($item);
        $item->delete();

        return redirect()->route('admin.items.index')->with('success', 'Item deleted successfully.');
    }

    private function formOptions(): array
    {
        $companyId = $this->companyId();

        return [
            'taxRates' => TaxRate::where('company_id', $companyId)->active()->selectable()->orderBy('name')->get(),
            'unitsCatalog' => UnitHelper::allForCompany($companyId),
            'unitsJson' => UnitHelper::jsonForCompany($companyId),
            'currencies' => config('item.currencies'),
            'descriptionMax' => config('item.description_max', 1000),
            'syncOpeningQty' => CompanySettings::bool('sync_opening_to_current_qty', $companyId),
            'unitOptional' => CompanySettings::bool('unit_optional', $companyId),
        ];
    }

    private function validateItem(Request $request): array
    {
        $maxDesc = config('item.description_max', 1000);

        return $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'description' => ['nullable', 'string', 'max:'.$maxDesc],
            'type' => ['required', 'in:product,service'],
            'unit' => [
                CompanySettings::bool('unit_optional', $this->companyId()) ? 'nullable' : 'required',
                'string', 'max:20',
            ],
            'tax_rate_id' => ['nullable', 'exists:tax_rates,id'],
            'hsn_sac' => ['nullable', 'string', 'max:20'],
            'sku' => ['nullable', 'string', 'max:50'],
            'opening_quantity' => ['nullable', 'numeric', 'min:0'],
            'sale_rate' => ['nullable', 'numeric', 'min:0'],
            'sale_currency' => ['nullable', 'string', 'max:10'],
            'sale_cess_percent' => ['nullable', 'numeric', 'min:0'],
            'sale_cess_amount' => ['nullable', 'numeric', 'min:0'],
            'purchase_rate' => ['nullable', 'numeric', 'min:0'],
            'purchase_currency' => ['nullable', 'string', 'max:10'],
            'purchase_cess_percent' => ['nullable', 'numeric', 'min:0'],
            'purchase_cess_amount' => ['nullable', 'numeric', 'min:0'],
            'is_active' => ['nullable', 'boolean'],
        ]);
    }

    private function prepareItemData(Request $request, array $data, bool $isNew, ?Item $item = null): array
    {
        $data['company_id'] = $this->companyId();
        $data['is_active'] = $request->boolean('is_active', true);
        $data['sale_currency'] = $data['sale_currency'] ?? 'INR';
        $data['purchase_currency'] = $data['purchase_currency'] ?? 'INR';
        $data['sale_rate'] = $data['sale_rate'] ?? 0;
        $data['purchase_rate'] = $data['purchase_rate'] ?? 0;
        $data['sale_cess_percent'] = $data['sale_cess_percent'] ?? 0;
        $data['sale_cess_amount'] = $data['sale_cess_amount'] ?? 0;
        $data['purchase_cess_percent'] = $data['purchase_cess_percent'] ?? 0;
        $data['purchase_cess_amount'] = $data['purchase_cess_amount'] ?? 0;
        $data['unit'] = filled($data['unit'] ?? null) ? $data['unit'] : null;

        if ($data['type'] === 'product') {
            $data['track_inventory'] = true;
            $opening = (float) ($data['opening_quantity'] ?? 0);

            if ($isNew) {
                $data['stock_qty'] = $opening;
                $data['opening_quantity'] = $opening;
            } else {
                unset($data['opening_quantity']);
            }
        } else {
            $data['track_inventory'] = false;
            $data['stock_qty'] = 0;
            $data['opening_quantity'] = 0;
        }

        return $data;
    }

    private function authorizeItem(Item $item): void
    {
        if ($item->company_id !== $this->companyId()) {
            abort(403);
        }
    }
}
