<?php

namespace App\Http\Controllers;

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

class UnitController extends Controller
{
    public function __construct()
    {
        $this->middleware(\App\Http\Middleware\PermissionMiddleware::class . ':manage units')
            ->only(['create', 'store', 'edit', 'update', 'destroy']);
    }
    public function index(Request $request)
    {
        $query = Unit::withCount('products');

        if ($request->filled('search')) {
            $query->where(function ($q) use ($request) {
                $q->where('name', 'like', '%' . $request->search . '%')
                  ->orWhere('symbol', 'like', '%' . $request->search . '%');
            });
        }

        if ($request->filled('status')) {
            $query->where('is_active', $request->status === 'active');
        }

        $units = $query->latest()->paginate(15)->withQueryString();

        return view('pages.units.index', [
            'title' => 'Kelola Satuan',
            'units' => $units,
        ]);
    }

    public function create()
    {
        return view('pages.units.form', [
            'title' => 'Tambah Satuan',
            'unit' => new Unit(),
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:100',
            'symbol' => 'required|string|max:20',
            'is_active' => 'boolean',
        ]);

        $validated['is_active'] = $request->has('is_active');

        Unit::create($validated);

        return redirect()->route('products.units.index')
            ->with('success', 'Satuan berhasil ditambahkan.');
    }

    public function edit(Unit $unit)
    {
        return view('pages.units.form', [
            'title' => 'Edit Satuan',
            'unit' => $unit,
        ]);
    }

    public function update(Request $request, Unit $unit)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:100',
            'symbol' => 'required|string|max:20',
            'is_active' => 'boolean',
        ]);

        $validated['is_active'] = $request->has('is_active');

        $unit->update($validated);

        return redirect()->route('products.units.index')
            ->with('success', 'Satuan berhasil diperbarui.');
    }

    public function destroy(Unit $unit)
    {
        if ($unit->products()->exists()) {
            return redirect()->back()
                ->with('error', 'Satuan tidak dapat dihapus karena digunakan oleh produk.');
        }

        $unit->delete();

        return redirect()->route('products.units.index')
            ->with('success', 'Satuan berhasil dihapus.');
    }
}
