<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Models\Map\Tanaman;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;

class TanamanController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): JsonResponse
    {
        Gate::authorize('petani');

        $user = Auth::user();
        $profile = $user->profile;

        $size = +$request->get('size') ?: 10;

        $tanamanQuery = Tanaman::query();

        $tanamanQuery = $tanamanQuery->where('profile_id', $profile->id);

        if ($request->has('search')) {
            $s = $request->get('search');
            $s = strtolower($s);
            $tanamanQuery->where(function($query) use ($s) {
                $query->whereRaw('lower(nama) like (?)',["%{$s}%"]);
            });
        }
        if ($request->has('sort')) {
            $order = $request->get('sort');
            $d = substr($order, 0, 1);
            $dir = $d === '-' ? 'desc' : 'asc'; 
            $order = $d === '-' ? substr($order, 1) : $order;
            $tanamanQuery->orderBy($order, $dir);
        }
        if ($request->has('lahan_id')) {
            $tanamanQuery->where('lahan_id', $request->get('lahan_id'));
        }
        if ($request->has('komoditas_id')) {
            $tanamanQuery->where('komoditas_id', $request->get('komoditas_id'));
        }

        $tanamanList = $tanamanQuery->paginate($size);

        return response()->json($tanamanList);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request): JsonResponse
    {
        Gate::authorize('petani');
        $user = Auth::user();
        $profile = $user->profile;

        $validated = $request->validate([
            'nama' => ['required', 'string', 'max:255'],
            'komoditas_id' => ['required', 'exists:master_komoditas,id'],
            'lahan_id' => ['required', 'exists:map_lahan,id'],
            'latitude' => ['nullable', 'numeric'],
            'longitude' => ['nullable', 'numeric'],
        ]);

        $tanaman = Tanaman::create([
            'nama' => $validated['nama'],
            'komoditas_id' => $validated['komoditas_id'],
            'lahan_id' => $validated['lahan_id'],
            'latitude' => $validated['latitude'] ?? null,
            'longitude' => $validated['longitude'] ?? null,
            'profile_id' => $profile->id,
        ]);

        return response()->json($tanaman);
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        return response()->json(Tanaman::findOrFail($id));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id): JsonResponse
    {
        Gate::authorize('petani');
        $tanaman = Tanaman::findOrFail($id);
        $user = Auth::user();
        $profile = $user->profile;

        if ($tanaman->profile_id !== $profile->id) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }    

        $validated = $request->validate([
            'nama' => ['required', 'string', 'max:255'],
            'komoditas_id' => ['required', 'exists:master_komoditas,id'],
            'lahan_id' => ['required', 'exists:map_lahan,id'],
            'latitude' => ['nullable', 'numeric'],
            'longitude' => ['nullable', 'numeric'],
            'kondisi_tanaman' => ['nullable', 'string', 'in:sehat,sakit,mati'],
        ]);

        $tanaman->update([
            'nama' => $validated['nama'],
            'komoditas_id' => $validated['komoditas_id'] ?? $tanaman->komoditas_id,
            'lahan_id' => $validated['lahan_id'] ?? $tanaman->lahan_id,
            'latitude' => $validated['latitude'] ?? $tanaman->latitude,
            'longitude' => $validated['longitude'] ?? $tanaman->longitude,
            'kondisi_tanaman' => $validated['kondisi_tanaman'] ?? $tanaman->kondisi_tanaman,
        ]);

        return response()->json($tanaman);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
