<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Validation\Rules\Enum;
use Illuminate\Validation\Rule;

use App\Http\Resources\Pertanian\TanamanResource;
use App\Models\Pertanian\Tanaman;
use App\Enums\KondisiTanaman;

class TanamanController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): AnonymousResourceCollection
    {
        if (!Gate::any(['petani', 'fasilitator'])) {
            abort(403);
        }

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

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

        $tanamanList = Tanaman::where('profile_id', $profile->id)
            ->when($request->search, function ($q, $search) {
                $search = strtolower($search);
                $q->whereRaw('lower(nama) like ?', ["%{$search}%"]);
            })
            ->when($request->status_kepemilikan, fn($q,$v) => $q->where('status_kepemilikan',$v))
            ->when($request->lahan_id, fn($q,$v) => $q->where('lahan_id',$v))
            ->when($request->komoditas_id, fn($q,$v) => $q->where('komoditas_id',$v))
            ->when($request->desa_kelurahan_id, fn($q,$v) => 
                $q->whereHas('lahan', fn($k) 
                    => $k->where('desa_kelurahan_id',$v)
                )
            )
            ->when($request->kecamatan_id, fn ($q, $v) =>
                $q->whereHas('lahan.desaKelurahan', fn ($k) =>
                    $k->where('kecamatan_id', $v)
                )
            )
            ->when($request->kabupaten_kota_id, fn ($q, $v) =>
                $q->whereHas('lahan.desaKelurahan.kecamatan', fn ($k) =>
                    $k->where('kabupaten_kota_id', $v)
                )
            )
            ->when($request->provinsi_id, fn ($q, $v) =>
                $q->whereHas('lahan.desaKelurahan.kecamatan.kabupatenkota', fn ($k) =>
                    $k->where('provinsi_id', $v)
                )
            );

        if ($request->filled('sort')) {
            $dir = str_starts_with($request->sort, '-') ? 'desc' : 'asc';
            $column = ltrim($request->sort, '-');

            $allowed = ['id', 'nama'];

            if (in_array($column, $allowed)) {
                $tanamanList->orderBy($column, $dir);
            }
        } else {
            $tanamanList->orderBy('nama', 'asc');
        }

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

        return TanamanResource::collection($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
    {
        if (!Gate::any(['petani', 'fasilitator'])) {
            abort(403);
        }
        $profile = Auth::user()->profile;

        $validated = $request->validate([
            'nama' => ['required', 'string', 'max:255'],
            'komoditas_id' => ['required', 'exists:master_komoditas,id'],
            'lahan_id' => [
                'required',
                Rule::exists('map_lahan', 'id')->where(function ($query) use ($profile) {
                    $query->where('profile_id', $profile->id)
                        ->whereNull('deleted_at');
                }),
            ],
            'latitude' => ['nullable', 'numeric', 'between:-90,90', 'required_with:longitude'],
            'longitude' => ['nullable', 'numeric', 'between:-180,180', 'required_with:latitude'],
            'kondisi_tanaman' => ['nullable', 'string', new Enum(KondisiTanaman::class)],
        ]);

        $tanaman = Tanaman::create([
            ...$validated,
            'profile_id' => $profile->id,
        ]);

        return (new TanamanResource($tanaman))
            ->response()
            ->setStatusCode(201);
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id): JsonResponse
    {
        if (!Gate::any(['petani', 'fasilitator'])) {
            abort(403);
        }

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

        return (new TanamanResource($tanaman))->response();
    }

    /**
     * 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
    {
        if (!Gate::any(['petani', 'fasilitator'])) {
            abort(403);
        }
        $tanaman = Tanaman::findOrFail($id);
        if ($tanaman->profile_id !== Auth::user()->profile->id) {
            return response()->json(['message' => 'Unauthorized'], 403);
        } 

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

        $validated = $request->validate([
            'nama' => ['required', 'string', 'max:255'],
            'komoditas_id' => ['required', 'exists:master_komoditas,id'],
            'lahan_id' => [
                'required',
                Rule::exists('map_lahan', 'id')->where(function ($query) use ($profile) {
                    $query->where('profile_id', $profile->id)
                        ->whereNull('deleted_at');
                }),
            ],
            'latitude' => ['nullable', 'numeric', 'between:-90,90', 'required_with:longitude'],
            'longitude' => ['nullable', 'numeric', 'between:-180,180', 'required_with:latitude'],
            'kondisi_tanaman' => ['nullable', 'string', new Enum(KondisiTanaman::class)],
        ]);

        $tanaman->update($validated);

        return (new TanamanResource($tanaman))->response();
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id): JsonResponse
    {
        if (!Gate::any(['petani', 'fasilitator'])) {
            abort(403);
        }
        $tanaman = Tanaman::findOrFail($id);
        if ($tanaman->profile_id !== Auth::user()->profile->id) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $tanaman->delete();

        return response()->json(null, 204);
    }
}
