<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Unit;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class UnitController extends Controller
{
    public function index(Request $request)
    {
        if ($request->ajax() || $request->expectsJson() || $request->has('ajax')) {
            $units = Unit::where('is_active', true)
                ->when($request->search, function ($query, $search) {
                    return $query->where('name', 'like', "%{$search}%")
                        ->orWhere('short_name', 'like', "%{$search}%");
                })
                ->orderBy('name')
                ->get(['id', 'name', 'short_name']);

            return response()->json(['units' => $units]);
        }

        $units = Unit::orderBy('name')->paginate(15);

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

    public function store(Request $request): JsonResponse|RedirectResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'short_name' => 'required|string|max:10',
            'is_active' => 'boolean',
        ]);

        $validated['is_active'] = $request->has('is_active') ? $request->boolean('is_active') : true;

        $unit = Unit::create($validated);

        if ($request->expectsJson()) {
            return response()->json([
                'success' => true,
                'message' => 'Unit created successfully',
                'unit' => $unit,
            ]);
        }

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

    public function show($id)
    {
        $unit = Unit::findOrFail($id);

        if (request()->expectsJson()) {
            return response()->json(['unit' => $unit]);
        }

        return view('admin.products.units.show', compact('unit'));
    }

    public function update(Request $request, $id): JsonResponse|RedirectResponse
    {
        $unit = Unit::findOrFail($id);

        // If only is_active is being updated (status toggle), allow partial update
        $requestData = $request->except(['_method', '_token']);
        if (count($requestData) === 1 && isset($requestData['is_active'])) {
            $unit->update(['is_active' => $request->boolean('is_active')]);

            if ($request->expectsJson()) {
                return response()->json([
                    'success' => true,
                    'message' => 'Status updated successfully',
                    'unit' => $unit->fresh(),
                ]);
            }

            return redirect()->route('admin.products.units.index')->with('success', 'Status updated successfully');
        }

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'short_name' => 'required|string|max:10',
            'is_active' => 'boolean',
        ]);

        $unit->update($validated);

        if ($request->expectsJson()) {
            return response()->json([
                'success' => true,
                'message' => 'Unit updated successfully',
                'unit' => $unit,
            ]);
        }

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

    public function destroy($id)
    {
        $unit = Unit::findOrFail($id);
        $unit->delete();

        if (request()->expectsJson()) {
            return response()->json([
                'success' => true,
                'message' => 'Unit deleted successfully',
            ]);
        }

        return redirect()->route('admin.products.units.index')->with('success', 'Unit deleted successfully');
    }
}
