<?php

namespace App\Http\Controllers;

use App\Models\Uom;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;
use Illuminate\Support\Facades\DB;
use Spatie\Activitylog\Models\Activity;

class UomController extends Controller
{
    public function index(): View
    {
        $uoms = Uom::query()
            ->orderBy('code')
            ->paginate(15);

        return view('uoms.index', compact('uoms'));
    }

    public function create(): View
    {
        return view('uoms.create');
    }

    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'code' => 'required|string|max:10|unique:uoms,code',
            'name' => 'required|string|max:255',
            'factor_to_base' => 'required|numeric|min:0',
            'is_active' => 'boolean',
        ]);

        try {
            DB::transaction(function () use ($request) {
                Uom::create([
                    'code' => strtoupper($request->code),
                    'name' => $request->name,
                    'factor_to_base' => $request->factor_to_base,
                    'is_active' => $request->boolean('is_active', true),
                ]);
            });

            return redirect()->route('uoms.index')->with('success', 'UOM created successfully.');
        } catch (\Throwable $e) {
            report($e);
            return back()->withInput()->withErrors(['error' => 'Failed to create UOM.']);
        }
    }

    public function show(Uom $uom): View
    {
        return view('uoms.show', compact('uom'));
    }

    public function edit(Uom $uom): View
    {
        return view('uoms.edit', compact('uom'));
    }

    public function update(Request $request, Uom $uom): RedirectResponse
    {
        $request->validate([
            'code' => 'required|string|max:10|unique:uoms,code,' . $uom->id,
            'name' => 'required|string|max:255',
            'factor_to_base' => 'required|numeric|min:0',
            'is_active' => 'boolean',
        ]);

        try {
            $oldData = $uom->toArray();

            DB::transaction(function () use ($request, $uom) {
                $uom->update([
                    'code' => strtoupper($request->code),
                    'name' => $request->name,
                    'factor_to_base' => $request->factor_to_base,
                    'is_active' => $request->boolean('is_active', true),
                ]);
            });

            return redirect()->route('uoms.index')->with('success', 'UOM updated successfully.');
        } catch (\Throwable $e) {
            report($e);
            return back()->withInput()->withErrors(['error' => 'Failed to update UOM.']);
        }
    }

    public function destroy(Uom $uom): RedirectResponse
    {
        try {
            // Check if UOM is being used by any items
            if ($uom->items()->count() > 0) {
                return back()->withErrors(['error' => 'Cannot delete UOM. It is being used by items.']);
            }

            $uomData = $uom->toArray();
            $uom->delete();

            return redirect()->route('uoms.index')->with('success', 'UOM deleted successfully.');
        } catch (\Throwable $e) {
            report($e);
            return back()->withErrors(['error' => 'Failed to delete UOM.']);
        }
    }

    public function search(Request $request)
    {
        $q = (string) $request->get('q', '');
        $uoms = Uom::query()
            ->where('is_active', true)
            ->when($q !== '', function ($query) use ($q) {
                $query->where(function ($sub) use ($q) {
                    $sub->where('code', 'like', "%{$q}%")
                        ->orWhere('name', 'like', "%{$q}%");
                });
            })
            ->orderBy('code')
            ->limit(20)
            ->get(['id', 'code', 'name']);

        return response()->json([
            'results' => $uoms->map(function ($uom) {
                return [
                    'id' => $uom->id,
                    'text' => $uom->code . ' - ' . $uom->name,
                ];
            }),
        ]);
    }
}
