<?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;

        $inspeksi = Inspeksi::query();

        if ($request->has('search')) {
            $s = $request->get('search');
            $s = strtolower($s);
            $inspeksi->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;
            $inspeksi->orderBy($order, $dir);
        }

        $data = $inspeksi->paginate($size);

        return response()->json($data);
    }
    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([
            'tanaman_id' => ['required'],
            'lahan_id' => ['required'],
            'petani_id' => ['required'],
            'health_status' => ['string'],
            'productivity_status' => ['string'],
        ]);
        $lahan = Inspeksi::create([
                "tanaman_id" => $validated["tanaman_id"],
                "lahan_id" => $validated['lahan_id'],
                "petani_id"=> $validated['petani_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([
            'petani_id' => ['required'],
            'lahan_id' => ['required'],
            'petani_id' => ['required'],
            'health_status' => ['string'],
            'productivity_status' => ['string'],
        ]);

        $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'],
            'lahan_id' => ['required'],
            'petani_id' => ['required'],
            'health_status' => ['string'],
            'productivity_status' => ['string'],
        ]);

        $inspections = [];
        foreach ($validated['inspections'] as $insoection) {
            $inspection[] = [
                "tanaman_id" => $insoection["tanaman_id"],
                "lahan_id" => $insoection['lahan_id'],
                "petani_id"=> $insoection['petani_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'], 
            [
                "tanaman_id",
                "lahan_id",
                "petani_id",
                "inspection_date",
                "health_status",
                "productivity_status",
                "issue_type",
                "issue_description",
                "recommendation",
                "notes",
                "created_date",
                "sync_status"
            ]);

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