<?php
namespace App\Http\Controllers\Api;

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

class InspeksiController extends Controller{
    public function index(Request $request): JsonResponse
    {
        $size = +$request->get('size') ?: 10;

        $master = Inspeksi::query();

        if ($request->has('search')) {
            $s = $request->get('search');
            $s = strtolower($s);
            $master->where(function($query) use ($s) {
                $query->whereRaw('lower(kode) like (?)',["%{$s}%"])
                    ->orWhereRaw('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;
            $master->orderBy($order, $dir);
        }
        if ($request->has('kecamatan_id')) {
            $master->where('kecamatan_id', $request->get('kecamatan_id'));
        }

        $masterList = $master->paginate($size);

        return response()->json($masterList);
    }
    public function show(string $id)
    {
        Gate::authorize('petani');

        $lahan = Inspeksi::findOrFail($id);

        return response()->json($lahan);
    }
    public function store(Request $request): JsonResponse
    {
        Gate::authorize('petani');

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

        $validated = $request->validate([
            'plant_id' => ['required', 'numeric'],
            'land_id' => ['required', 'numeric'],
            'farmer_id' => ['numeric'],
            'health_status' => ['string'],
            'productivity_status' => ['string'],
        ]);
        // dd($validated);
        $lahan = Inspeksi::create([
                "tanaman_id" => $validated["plant_id"],
                "lahan_id" => $validated['land_id'],
                "petani_id"=> $validated['farmer_id'],
                "inspection_date"=> $request['inspection_date'],
                "health_status"=> $request['health_status'],
                "productivity_status"=> $validated['productivity_status'],
                "issue_type"=> $request['issue_type'],
                "issue_description"=> $request['issue_description'],
                "recommendation"=> $request['recommendation'],
                "notes"=> $request['notes'],
                "created_date"=> $validated['created_date'] ?? null,
                "sync_status"=> $validated['sync_status'] ?? 'synced'
            ]);

        return response()->json($lahan, 201);
    }
    public function update(Request $request, string $id)
    {
        Gate::authorize('petani');

        $lahan = Inspeksi::findOrFail($id);

        $validated = $request->validate([
            'tanaman_id' => ['required', 'string', 'max:255'],
            'lahan_id' => ['required', 'string'],
            'petani_id' => ['numeric'],
            'health_status' => ['string'],
            'productivity_status' => ['numeric'],
        ]);

        $lahan->update($validated);

        return response()->json($lahan);
    }
    public function destroy(string $id)
    {
        Gate::authorize('petani');

        $lahan = Inspeksi::findOrFail($id);        
        $lahan->delete();

        return response()->json(null, 204);
    }
    public function batchUpsert(Request $request): JsonResponse
    {
        Gate::authorize('petani');
        $user = Auth::user();
        $profile = $user->profile;

        $validated = $request->validate([
            'tanaman_id' => ['required', 'string', 'max:255'],
            'lahan_id' => ['required', 'string'],
            'petani_id' => ['numeric'],
            'health_status' => ['string'],
            'productivity_status' => ['numeric'],
        ]);

        $inspections = [];
        foreach ($validated['inspections'] as $insoection) {
            $inspection[] = [
                "plant_id" => $insoection["plant_id"],
                "land_id" => $insoection['land_id'],
                "farmer_id"=> $insoection['farmer_id'],
                "inspection_date"=> $insoection['inspection_date'],
                "health_status"=> $insoection['health_status'],
                "productivity_status"=> $insoection['productivity_status'],
                "issue_type"=> $insoection['issue_type'],
                "issue_description"=> $insoection['issue_description'],
                "recommendation"=> $insoection['recommendation'],
                "notes"=> $insoection['notes'],
                "created_date"=> $insoection['created_date'],
                "sync_status"=> $insoection['sync_status']
            ];
        }

        Inspeksi::upsert($inspections, 
            ['id'], 
            [
                "plant_id",
                "land_id",
                "farmer_id",
                "inspection_date",
                "health_status",
                "productivity_status",
                "issue_type",
                "issue_description",
                "recommendation",
                "notes",
                "created_date",
                "sync_status"
            ]);

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