<?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 App\Models\Map\Panen;

class PanenController extends Controller
{
    public function index(): JsonResponse
    {
        Gate::authorize('petani');

        $user = Auth::user();
        $listPanen = Panen::where('farmer_id', $user->profile->id)->get();
        
        return response()->json($listPanen);
    }

    public function store(Request $request): JsonResponse
    {
        Gate::authorize('petani');

        $validated = $request->validate([
            'land_id' => ['required', 'integer'],
            'plant_id' => ['required', 'integer'],
            'commodity_name' => ['required', 'string', 'max:255'],
            'weight_kg' => ['required', 'numeric'],
            'harvest_date' => ['required', 'date'],
            'notes' => ['nullable', 'string'],
        ]);

        $panen = Panen::create([
            'land_id' => $validated['land_id'],
            'plant_id' => $validated['plant_id'],
            'farmer_id' => Auth::user()->profile->id,
            'commodity_name' => $validated['commodity_name'],
            'weight_kg' => $validated['weight_kg'],
            'harvest_date' => $validated['harvest_date'],
            'notes' => $validated['notes'] ?? null,
            'sync_status' => 'synced'
        ]);

        return response()->json($panen, 201);
    }

    public function show(string $id): JsonResponse
    {
        Gate::authorize('petani');
        $panen = Panen::findOrFail($id);
        return response()->json($panen);
    }

    public function update(Request $request, string $id): JsonResponse
    {
        Gate::authorize('petani');
        $panen = Panen::findOrFail($id);

        $validated = $request->validate([
            'commodity_name' => ['string', 'max:255'],
            'weight_kg' => ['numeric'],
            'harvest_date' => ['date'],
            'notes' => ['nullable', 'string'],
        ]);

        $panen->update($validated);
        return response()->json($panen);
    }

    public function destroy(string $id): JsonResponse
    {
        Gate::authorize('petani');
        Panen::findOrFail($id)->delete();
        return response()->json(null, 204);
    }

    /**
     * Digunakan untuk sinkronisasi massal dari data lokal (offline)
     */
    public function batchUpsert(Request $request): JsonResponse
    {
        Gate::authorize('petani');
        $profileId = Auth::user()->profile->id;

        $validated = $request->validate([
            'panens' => ['required', 'array'],
            'panens.*.id' => ['nullable', 'integer'],
            'panens.*.land_id' => ['required', 'integer'],
            'panens.*.plant_id' => ['required', 'integer'],
            'panens.*.commodity_name' => ['required', 'string'],
            'panens.*.weight_kg' => ['required', 'numeric'],
            'panens.*.harvest_date' => ['required', 'date'],
        ]);

        $dataUpsert = [];
        foreach ($validated['panens'] as $item) {
            $dataUpsert[] = [
                'id' => $item['id'] ?? null,
                'land_id' => $item['land_id'],
                'plant_id' => $item['plant_id'],
                'farmer_id' => $profileId,
                'commodity_name' => $item['commodity_name'],
                'weight_kg' => $item['weight_kg'],
                'harvest_date' => $item['harvest_date'],
                'sync_status' => 'synced',
                'created_at' => now(),
                'updated_at' => now(),
            ];
        }

        // Melakukan upsert berdasarkan ID
        Panen::upsert($dataUpsert, ['id'], [
            'weight_kg', 'commodity_name', 'harvest_date', 'sync_status', 'updated_at'
        ]);

        return response()->json(['status' => 'success'], 200);
    }
}