<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\SalaryComponent;
use Illuminate\Http\Request;

class SalaryComponentController extends Controller
{
    /**
     * @return array<int, string>
     */
    private function allowedValueTypes(): array
    {
        return ['fixed', 'variable', 'basic_percent', 'ctc_percent'];
    }

    public function index()
    {
        $salaryComponents = SalaryComponent::orderBy('name')->paginate(15);
        return view('salary-components.index', compact('salaryComponents'));
    }

    public function create()
    {
        return view('salary-components.create');
    }

    public function store(Request $request)
    {
        $companyId = auth()->user()?->company_id;
        $validated = $request->validate([
            'name' => 'required|string|max:191',
            'type' => 'required|in:earning,deduction',
            'value_type' => 'required|in:' . implode(',', $this->allowedValueTypes()),
            'default_amount' => 'required|numeric|min:0',
            'is_taxable' => 'boolean',
        ]);
        $normalizedName = strtolower(trim((string) $validated['name']));
        $existing = SalaryComponent::query()
            ->where('company_id', $companyId)
            ->whereRaw('LOWER(name) = ?', [$normalizedName])
            ->exists();
        if ($existing) {
            return redirect()->route('salary-components.create')
                ->withErrors(['name' => 'A salary component with this name already exists.'])
                ->withInput();
        }
        $validated['is_taxable'] = $request->boolean('is_taxable');
        $validated['name'] = trim((string) $validated['name']);
        $validated['company_id'] = $companyId;
        SalaryComponent::create($validated);
        return redirect()->route('salary-components.index')->with('success', 'Salary component created successfully.');
    }
}
