<?php

namespace App\Http\Controllers;

use App\Models\Machine;
use App\Models\Material;
use App\Models\MaterialCategory;
use Illuminate\Http\Request;

class MachineController extends Controller
{
    public function __construct()
    {
        $this->middleware(\App\Http\Middleware\PermissionMiddleware::class . ':manage machines')
            ->only(['create', 'store', 'edit', 'update', 'destroy']);
    }

    public function index(Request $request)
    {
        $query = Machine::with(['categories', 'materials']);

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

        $machines = $query->orderBy('name')->paginate(20);

        return view('pages.stock.machines.index', [
            'title' => 'Data Mesin',
            'machines' => $machines,
        ]);
    }

    public function create()
    {
        $categories = MaterialCategory::active()->orderBy('name')->get();
        $materials = Material::where('is_active', true)->orderBy('name')->get();

        return view('pages.stock.machines.create', [
            'title' => 'Tambah Mesin',
            'categories' => $categories,
            'materials' => $materials,
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'description' => ['nullable', 'string', 'max:500'],
            'cost_per_click' => ['required', 'numeric', 'min:0'],
            'categories' => ['nullable', 'array'],
            'categories.*' => ['exists:material_categories,id'],
            'materials' => ['nullable', 'array'],
            'materials.*' => ['exists:materials,id'],
        ]);

        $machine = Machine::create([
            'name' => $validated['name'],
            'description' => $validated['description'] ?? null,
            'cost_per_click' => $validated['cost_per_click'],
        ]);

        if (!empty($validated['categories'])) {
            $machine->categories()->sync($validated['categories']);
        }
        if (!empty($validated['materials'])) {
            $machine->materials()->sync($validated['materials']);
        }

        return redirect()->route('stock.machines.index')
            ->with('success', 'Mesin berhasil ditambahkan.');
    }

    public function edit(Machine $machine)
    {
        $machine->load(['categories', 'materials']);
        $categories = MaterialCategory::active()->orderBy('name')->get();
        $materials = Material::where('is_active', true)->orderBy('name')->get();

        return view('pages.stock.machines.edit', [
            'title' => 'Edit Mesin',
            'machine' => $machine,
            'categories' => $categories,
            'materials' => $materials,
        ]);
    }

    public function update(Request $request, Machine $machine)
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'description' => ['nullable', 'string', 'max:500'],
            'is_active' => ['boolean'],
            'cost_per_click' => ['required', 'numeric', 'min:0'],
            'categories' => ['nullable', 'array'],
            'categories.*' => ['exists:material_categories,id'],
            'materials' => ['nullable', 'array'],
            'materials.*' => ['exists:materials,id'],
        ]);

        $machine->update([
            'name' => $validated['name'],
            'description' => $validated['description'] ?? null,
            'is_active' => $request->boolean('is_active'),
            'cost_per_click' => $validated['cost_per_click'],
        ]);

        $machine->categories()->sync($validated['categories'] ?? []);
        $machine->materials()->sync($validated['materials'] ?? []);

        return redirect()->route('stock.machines.index')
            ->with('success', 'Mesin berhasil diperbarui.');
    }

    public function destroy(Machine $machine)
    {
        $machine->delete();

        return redirect()->route('stock.machines.index')
            ->with('success', 'Mesin berhasil dihapus.');
    }
}
