<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Tool;
use Illuminate\Http\Request;
use Inertia\Inertia;

class ToolController extends Controller
{
    public function index()
    {
        $tools = Tool::latest()->get();

        return Inertia::render('Admin/Pages/Tools/Index', [
            'tools' => $tools,
        ]);
    }

    public function create()
    {
        return Inertia::render('Admin/Pages/Tools/Create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'type' => 'required|in:buy,rent',
            'price' => 'required|numeric|min:0',
            'quantity' => 'required|integer|min:1',
        ]);

        Tool::create([
            'name' => $request->name,
            'type' => $request->type,
            'price' => $request->price,
            'quantity' => $request->quantity,
            'date' => today(),
        ]);

        return redirect()->route('admin.tools.index');
    }

    public function edit(Tool $tool)
    {
        return Inertia::render('Admin/Pages/Tools/Edit', [
            'tool' => $tool,
        ]);
    }

    public function update(Request $request, Tool $tool)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'type' => 'required|in:buy,rent',
            'price' => 'required|numeric|min:0',
            'quantity' => 'required|integer|min:1',
        ]);

        $tool->update($request->all());

        return redirect()->route('admin.tools.index');
    }

    public function destroy(Tool $tool)
    {
        $tool->delete();

        return redirect()->route('admin.tools.index');
    }
}