<?php

namespace App\Http\Controllers;

use App\Models\Mill;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class MillController extends Controller
{
    /** GET /products/mills */
    public function index(Request $request)
    {
        $q = trim($request->get('q', ''));

        $mills = Mill::with(['createdBy', 'updatedBy'])
            ->when($q, fn($qr) => $qr->where('name', 'like', "%{$q}%"))
            ->orderBy('id', 'asc')
            ->paginate(12)
            ->withQueryString();

        return view('products.mills.index', compact('mills', 'q'));
    }

    /** GET /products/mills/create */
    public function create()
    {
        return view('products.mills.create');
    }

    /** POST /products/mills */
    public function store(Request $request)
    {
        $data = $request->validate([
            'name'   => ['required', 'string', 'max:191', 'unique:rm_mills,name'],
            'status' => ['required', Rule::in(['0','1'])],
        ]);

        Mill::create([
            'name'       => $data['name'],
            'status'     => (int)$data['status'],
            'created_by' => auth()->id() ?? null,
            'updated_by' => auth()->id() ?? null,
        ]);

        return redirect()->route('products.mills.index')
            ->with('success', 'Mill created successfully.');
    }

    /** GET /products/mills/{mill}/edit */
    public function edit(Mill $mill)
    {
        return view('products.mills.edit', compact('mill'));
    }

    /** PUT /products/mills/{mill} */
    public function update(Request $request, Mill $mill)
    {
        $data = $request->validate([
            'name'   => ['required', 'string', 'max:191', Rule::unique('rm_mills', 'name')->ignore($mill->id)],
            'status' => ['required', Rule::in(['0','1'])],
        ]);

        $mill->update([
            'name'       => $data['name'],
            'status'     => (int)$data['status'],
            'updated_by' => auth()->id() ?? $mill->updated_by,
        ]);

        return redirect()->route('products.mills.index')
            ->with('success', 'Mill updated successfully.');
    }

    /** DELETE /products/mills/{mill} */
    public function destroy(Mill $mill)
    {
        $mill->delete();

        return redirect()->route('products.mills.index')
            ->with('success', 'Mill deleted successfully.');
    }
}

