<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\UnitHelper;
use App\Models\CompanyUnit;
use Illuminate\Http\Request;

class UnitController extends AdminController
{
    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:100'],
            'code' => ['required', 'string', 'max:20', 'regex:/^[A-Za-z0-9]+$/'],
            'is_gst' => ['nullable', 'boolean'],
        ]);

        $code = strtoupper($data['code']);

        $unit = CompanyUnit::updateOrCreate(
            ['company_id' => $this->companyId(), 'code' => $code],
            [
                'name' => $data['name'],
                'is_gst' => $request->boolean('is_gst'),
            ]
        );

        return response()->json([
            'success' => true,
            'unit' => [
                'code' => $unit->code,
                'name' => $unit->name,
                'gst' => $unit->is_gst,
                'custom' => true,
                'label' => $unit->displayLabel(),
            ],
            'units' => UnitHelper::jsonForCompany($this->companyId()),
        ]);
    }
}
