<?php

namespace App\Http\Controllers\Web\Ekosistem;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Pertanian\Komoditas;
use Illuminate\Support\Facades\Validator;

class KomoditasController extends Controller
{
    public function index(Request $request)
    {
        $query = Komoditas::orderBy('created_at', 'desc');

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

        $komoditas = $query->paginate($request->per_page ?? 10);
        return view('master.komoditas.index', compact('komoditas'));
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'nama' => ['required', 'string', 'max:255', 'unique:master_komoditas,nama'], // Tambah unique biar nggak ada data kembar
        ], [
            'nama.unique' => 'Nama komoditas ini sudah ada di database.'
        ]);

        if ($validator->fails()) {
            return response()->json(['status' => 'error', 'errors' => $validator->errors()], 422);
        }

        Komoditas::create([
            'nama'       => $request->nama,
            'created_by' => auth()->id(),
            'updated_by' => auth()->id(),
        ]);

        return response()->json(['status' => 'success', 'message' => 'Komoditas berhasil ditambahkan.']);
    }

    public function show($id)
    {
        $komoditas = Komoditas::findOrFail($id);
        return response()->json(['status' => 'success', 'data' => $komoditas]);
    }

    public function update(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'nama' => ['required', 'string', 'max:255', 'unique:master_komoditas,nama,' . $id],
        ], [
            'nama.unique' => 'Nama komoditas ini sudah digunakan.'
        ]);

        if ($validator->fails()) {
            return response()->json(['status' => 'error', 'errors' => $validator->errors()], 422);
        }

        $komoditas = Komoditas::findOrFail($id);
        $komoditas->update([
            'nama'       => $request->nama,
            'updated_by' => auth()->id(),
        ]);

        return response()->json(['status' => 'success', 'message' => 'Komoditas berhasil diupdate.']);
    }

    public function destroy($id)
    {
        $komoditas = Komoditas::findOrFail($id);
        
        $komoditas->update(['deleted_by' => auth()->id()]);
        $komoditas->delete();

        return response()->json(['status' => 'success', 'message' => 'Komoditas berhasil dihapus.']);
    }
}
