<?php

namespace App\Http\Controllers;

use App\Models\Unit;
use App\Services\AuditLogService;
use Illuminate\Http\Request;

class UnitController extends Controller
{
    protected AuditLogService $audit;

    public function __construct(AuditLogService $audit)
    {
        $this->audit = $audit;
    }

    public function index()
    {
        $units = Unit::orderBy('code')->paginate(50);
        return view('units.index', compact('units'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'code'          => 'required|string|max:20|unique:units,code',
            'name_en'       => 'required|string|max:100',
            'name_ar'       => 'required|string|max:100',
            'short_name_en' => 'nullable|string|max:20',
            'short_name_ar' => 'nullable|string|max:20',
            'allow_decimal' => 'required|boolean',
        ]);

        $unit = Unit::create($validated);
        $this->audit->log('UNIT_CREATED', 'units', $unit->id, null, $validated);

        return redirect()->route('units.index')->with('success', 'Unit created.');
    }

    public function update(Request $request, Unit $unit)
    {
        $validated = $request->validate([
            'code'          => 'required|string|max:20|unique:units,code,' . $unit->id,
            'name_en'       => 'required|string|max:100',
            'name_ar'       => 'required|string|max:100',
            'short_name_en' => 'nullable|string|max:20',
            'short_name_ar' => 'nullable|string|max:20',
            'allow_decimal' => 'required|boolean',
        ]);

        $old = $unit->toArray();
        $unit->update($validated);
        $this->audit->log('UNIT_UPDATED', 'units', $unit->id, $old, $validated);

        return redirect()->route('units.index')->with('success', 'Unit updated.');
    }

    /**
     * AJAX: All units for select.
     */
    public function apiList()
    {
        $units = Unit::orderBy('code')->get(['id', 'code', 'name_en', 'name_ar', 'short_name_en', 'allow_decimal']);
        return response()->json($units);
    }
}
