<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Auth;
use App\Models\Distribusi\Distribution;

class DistributionController extends Controller
{
    public function index(): JsonResponse
    {
        if (!Gate::any(['super_admin', 'petani'])) {
            abort(403);
        }

        $user = Auth::user();
        $query = Distribution::query();

        // Jika petani, filter hanya data miliknya
        if ($user->role === 'petani') {
            $query->where('farmer_id', $user->profile->id);
        }

        return response()->json($query->get());
    }

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

        $validated = $request->validate([
            'offtaker_id' => 'required|numeric',
            'commodity_name' => 'required|string',
            'quantity_kg' => 'required|numeric',
            'farmer_grade' => 'nullable|string',
            'distribution_date' => 'required|date',
        ]);

        $distribution = Distribution::create(array_merge($validated, [
            'farmer_id' => Auth::user()->profile->id,
            'farmer_name' => Auth::user()->name,
            'status' => 'pending',
            'sync_status' => 'synced',
            'created_date' => now()
        ]));

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

    public function update(Request $request, string $id): JsonResponse
    {
        // Biasanya Admin atau Offtaker yang melakukan update grade/price
        Gate::authorize('super_admin'); 

        $distribution = Distribution::findOrFail($id);
        
        $validated = $request->validate([
            'offtaker_grade' => 'required|string',
            'grade_difference_reason' => 'nullable|string',
            'price_per_kg' => 'required|numeric',
            'status' => 'required|string', // e.g., 'graded'
            'received_date' => 'required|date',
        ]);

        $totalValue = $validated['price_per_kg'] * $distribution->quantity_kg;

        $distribution->update(array_merge($validated, [
            'total_value' => $totalValue,
            'updated_date' => now()
        ]));

        return response()->json($distribution);
    }

    public function batchUpsert(Request $request): JsonResponse
{
    Gate::authorize('any', ['super_admin', 'petani']);
    
    $validated = $request->validate([
        'distributions' => ['required', 'array'],
        'distributions.*.farmer_id' => ['required', 'numeric'],
        'distributions.*.offtaker_id' => ['required', 'numeric'],
        'distributions.*.commodity_name' => ['required', 'string'],
        'distributions.*.quantity_kg' => ['required', 'numeric'],
    ]);

    $dataUpsert = [];
    foreach ($validated['distributions'] as $item) {
        $dataUpsert[] = [
            'id' => $item['id'] ?? null, // Jika NULL, Postgres akan membuat ID baru
            'farmer_id' => $item['farmer_id'],
            'farmer_name' => $item['farmer_name'] ?? null,
            'offtaker_id' => $item['offtaker_id'],
            'offtaker_name' => $item['offtaker_name'] ?? null,
            'commodity_name' => $item['commodity_name'],
            'quantity_kg' => $item['quantity_kg'],
            'farmer_grade' => $item['farmer_grade'] ?? null,
            'offtaker_grade' => $item['offtaker_grade'] ?? null,
            'status' => $item['status'] ?? 'graded',
            'sync_status' => 'synced',
            'created_at' => now(),
            'updated_at' => now(),
        ];
    }

    // Upsert berdasarkan ID bigint
    Distribution::upsert($dataUpsert, ['id'], [
        'quantity_kg', 'offtaker_grade', 'status', 'sync_status', 'updated_at'
    ]);

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