<?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 App\Models\Pertanian\Lahan;
use App\Http\Resources\Pertanian\LahanResource;
use App\Enums\StatusLahan;

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

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

        $profileId = $user->role === 'petani' ? $profile->id : $request->profile_id;

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

        $listLahan = Lahan::when($request->search, function ($q, $search) {
                $search = strtolower($search);
                $q->whereRaw('lower(nama) like ?', ["%{$search}%"]);
            })
            ->when($profileId, fn($q,$v) => $q->where('profile_id',$v))
            ->when($request->status_kepemilikan, fn($q,$v) => $q->where('status_kepemilikan',$v))
            ->when($request->desa_kelurahan_id, fn($q,$v) => $q->where('desa_kelurahan_id',$v))
            ->when($request->kecamatan_id, fn ($q, $v) =>
                $q->whereHas('desaKelurahan', fn ($k) =>
                    $k->where('kecamatan_id', $v)
                )
            )
            ->when($request->kabupaten_kota_id, fn ($q, $v) =>
                $q->whereHas('desaKelurahan.kecamatan', fn ($k) =>
                    $k->where('kabupaten_kota_id', $v)
                )
            )
            ->when($request->provinsi_id, fn ($q, $v) =>
                $q->whereHas('desaKelurahan.kecamatan.kabupatenota', 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)) {
                $listLahan->orderBy($column, $dir);
            }
        } else {
            $listLahan->orderBy('nama', 'asc');
        }

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

        return LahanResource::collection($listLahan);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request): JsonResponse
    {
        if (!Gate::any(['petani', 'fasilitator'])) {
            abort(403);
        }

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

        if (!$profile) {
            abort(404, 'Profile tidak ditemukan');
        }

        $profileRule = $user->role === 'fasilitator' ? ['required', 'numeric', 'exists:profiles,id'] : ['nullable'];

        $validated = $request->validate([
            'nama' => ['required', 'string', 'max:255'],
            'status_kepemilikan' => ['required', new Enum(StatusLahan::class)],
            'desa_kelurahan_id' => ['nullable', 'numeric', 'exists:master_desa_kelurahan,id'],
            'path' => ['nullable', 'array'],
            'path.*' => ['array'],
            'luas_lahan' => ['nullable', 'numeric'],
            'profile_id' => $profileRule,
        ]);

        $targetProfileId = $user->role === 'fasilitator'
            ? $validated['profile_id']
            : $profile->id;

        if ($user->role === 'fasilitator') {
            $targetProfile = Profile::findOrFail($targetProfileId);

            if ($targetProfile->desa_kelurahan_id !== $profile->desa_kelurahan_id) {
                abort(403, 'Tidak boleh lintas desa');
            }
        }

        $desaKelurahanId = $user->role === 'fasilitator'
            ? $profile->desa_kelurahan_id
            : ($validated['desa_kelurahan_id'] ?? $profile->desa_kelurahan_id);

        $lahan = Lahan::create([
            ...$validated,
            'profile_id' => $profile->id,
            'desa_kelurahan_id' => $desaKelurahanId,
        ]);

        return (new LahanResource($lahan))
            ->response()
            ->setStatusCode(201);
    }

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

        $lahan = Lahan::with('desaKelurahan')->findOrFail($id);
        if ($lahan->profile_id !== Auth::user()->profile->id && Auth::user()->role === 'petani') {
            return response()->json(['message' => 'Unauthorized'], 403);
        } else if (Auth::user()->role === 'fasilitator' && $lahan->desa_kelurahan_id !== Auth::user()->profile->desa_kelurahan_id) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        return (new LahanResource($lahan))->response();
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id): JsonResponse
    {
        if (!Gate::any(['petani', 'fasilitator'])) {
            abort(403);
        }

        $lahan = Lahan::findOrFail($id);
        if ($lahan->profile_id !== Auth::user()->profile->id && Auth::user()->role === 'petani') {
            return response()->json(['message' => 'Unauthorized'], 403);
        } else if (Auth::user()->role === 'fasilitator' && $lahan->desa_kelurahan_id !== Auth::user()->profile->desa_kelurahan_id) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $validated = $request->validate([
            'nama' => ['required', 'string', 'max:255'],
            'status_kepemilikan' => ['required', new Enum(StatusLahan::class)],
            'desa_kelurahan_id' => ['nullable', 'numeric', 'exists:master_desa_kelurahan,id'],
            'path' => ['nullable', 'array'],
            'path.*' => ['array'],
            'luas_lahan' => ['nullable', 'numeric'],
        ]);

        $lahan->update($validated);

        return (new LahanResource($lahan))->response();
    }

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

        $lahan = Lahan::findOrFail($id);
        if ($lahan->profile_id !== Auth::user()->profile->id && Auth::user()->role === 'petani') {
            return response()->json(['message' => 'Unauthorized'], 403);
        } else if (Auth::user()->role === 'fasilitator' && $lahan->desa_kelurahan_id !== Auth::user()->profile->desa_kelurahan_id) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $lahan->delete();

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

    public function batchUpsert(Request $request): JsonResponse
    {
        if (!Gate::any(['petani', 'fasilitator'])) {
            abort(403);
        }
        
        $user = Auth::user();
        $profile = $user->profile;

        $validated = $request->validate([
            'lahans' => ['required', 'array'],
            'lahans.*.id' => ['numeric'],
            'lahans.*.nama' => ['required', 'string', 'max:255'],
            'lahans.*.status_kepemilikan' => ['required', 'numeric'],
            'lahans.*.desa_kelurahan_id' => ['numeric'],
            'lahans.*.path' => ['string'],
            'lahans.*.luas_lahan' => ['numeric'],
        ]);

        $lahans = [];
        foreach ($validated['lahans'] as $lahan) {
            $lahans[] = [
                'id' => $lahan['id'] ?? null,
                'nama' => $lahan['nama'],
                'status_kepemilikan' => $lahan['status_kepemilikan'],
                'profile_id' => $profile->id,
                'desa_kelurahan_id' => $lahan['desa_kelurahan_id'] ?? null,
                'path' => $lahan['path'] ?? null,
                'luas_lahan' => $lahan['luas_lahan'] ?? null,
            ];
        }

        Lahan::upsert($lahans, ['id'], ['nama', 'status_kepemilikan', 'profile_id', 'desa_kelurahan_id', 'path', 'luas_lahan']);

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