<?php

namespace App\Http\Controllers\Web\Ekosistem;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Pertanian\Lahan;
use App\Models\Profile;
use App\Models\Wilayah\Provinsi;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class LahanController extends Controller
{
    public function index(Request $request)
    {
        $query = Lahan::with(['profile', 'desakelurahan'])->orderBy('created_at', 'desc');

        if ($request->search) {
            $query->where('nama', 'like', '%' . $request->search . '%')
                  ->orWhereHas('profile', function($q) use ($request) {
                      $q->where('nama', 'like', '%' . $request->search . '%');
                  });
        }

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

    public function create()
    {
        $provinsi = Provinsi::orderBy('nama', 'asc')->get();
        $profiles = Profile::orderBy('nama', 'asc')->get();
        return view('master.lahan.add', compact('provinsi', 'profiles'));
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'nama'                  => ['required', 'string', 'max:255'],
            'status_kepemilikan'    => ['required', 'string', 'max:255'],
            'profile_id'            => ['required'],
            'keluarga_pengelola_id' => ['nullable'],
            'adat_pemilik_id'       => ['nullable'],
            'desa_kelurahan_id'     => ['nullable'],
            'luas_lahan'            => ['nullable', 'numeric'],
            'path'                  => ['nullable', 'string'], 
        ]);

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

        if ($request->filled('path')) {
            json_decode($request->path);
            if (json_last_error() !== JSON_ERROR_NONE) {
                return response()->json(['status' => 'error', 'message' => 'Format koordinat (path) bukan JSON array yang valid.'], 422);
            }
        }

        Lahan::create([
            'nama'               => $request->nama,
            'status_kepemilikan' => $request->status_kepemilikan,
            'profile_id'         => $request->profile_id,
            'desa_kelurahan_id'  => $request->desa_kelurahan_id,
            'luas_lahan'         => $request->luas_lahan,
            'path'               => $request->path,
            'created_by'         => auth()->id(),
            'updated_by'         => auth()->id(),
        ]);

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

    public function show($id)
    {
        $lahan = Lahan::with(['profile', 'desakelurahan.kecamatan.kabupatenkota.provinsi', 'tanaman.komoditas'])->findOrFail($id);
        
        return view('master.lahan.view', compact('lahan')); 
    }
}

