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

class OfftakerController extends Controller
{
    public function index(): JsonResponse
    {
        if (!Gate::any(['super_admin', 'petani', 'fasilitator', 'admin'])) {
            abort(403, 'Unauthorized');
        }
        $listOfftaker = Offtaker::all();

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

    public function store(Request $request): JsonResponse
    {
        if (!Gate::any(['super_admin', 'petani', 'fasilitator', 'admin'])) {
            abort(403, 'Unauthorized');
        }

        $validated = $request->validate([
            'user_email' => ['required', 'email', 'max:255'],
            'company_name' => ['required', 'string', 'max:255'],
            'contact_name' => ['nullable', 'string', 'max:255'],
            'phone' => ['nullable', 'string', 'max:20'],
            'address' => ['nullable', 'string'],
            'is_active' => ['nullable', 'boolean'],
        ]);

        $offtaker = Offtaker::create([
            'user_email' => $validated['user_email'],
            'company_name' => $validated['company_name'],
            'contact_name' => $validated['contact_name'] ?? null,
            'phone' => $validated['phone'] ?? null,
            'address' => $validated['address'] ?? null,
            'is_active' => $validated['is_active'] ?? true,
            'sync_status' => 'synced',
            'created_date' => now(),
        ]);

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

    public function show(string $id): JsonResponse
    {
        if (!Gate::any(['super_admin', 'petani', 'fasilitator', 'admin'])) {
            abort(403, 'Unauthorized');
        }
        $offtaker = Offtaker::findOrFail($id);
        return response()->json($offtaker);
    }

    public function update(Request $request, string $id): JsonResponse
    {
        if (!Gate::any(['super_admin', 'petani', 'fasilitator', 'admin'])) {
            abort(403, 'Unauthorized');
        }
        $offtaker = Offtaker::findOrFail($id);

        $validated = $request->validate([
            'user_email' => ['email', 'max:255'],
            'company_name' => ['string', 'max:255'],
            'contact_name' => ['nullable', 'string'],
            'phone' => ['nullable', 'string'],
            'address' => ['nullable', 'string'],
            'is_active' => ['boolean'],
        ]);

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

    public function destroy(string $id): JsonResponse
    {
        if (!Gate::any(['super_admin', 'petani', 'fasilitator', 'admin'])) {
            abort(403, 'Unauthorized');
        }
        Offtaker::findOrFail($id)->delete();
        
        return response()->json(null, 204);
    }

    /**
     * Digunakan untuk sinkronisasi massal dari data lokal (offline)
     */
    public function batchUpsert(Request $request): JsonResponse
    {
        if (!Gate::any(['super_admin', 'petani', 'fasilitator', 'admin'])) {
            abort(403, 'Unauthorized');
        }

        $validated = $request->validate([
            'offtakers' => ['required', 'array'],
            'offtakers.*.id' => ['nullable', 'integer'],
            'offtakers.*.user_email' => ['required', 'email'],
            'offtakers.*.company_name' => ['required', 'string'],
            'offtakers.*.contact_name' => ['nullable', 'string'],
            'offtakers.*.phone' => ['nullable', 'string'],
            'offtakers.*.address' => ['nullable', 'string'],
        ]);

        $dataUpsert = [];
        foreach ($validated['offtakers'] as $item) {
            $dataUpsert[] = [
                'id' => $item['id'] ?? null,
                'user_email' => $item['user_email'],
                'company_name' => $item['company_name'],
                'contact_name' => $item['contact_name'] ?? null,
                'phone' => $item['phone'] ?? null,
                'address' => $item['address'] ?? null,
                'sync_status' => 'synced',
                'is_active' => true,
                'created_at' => now(),
                'updated_at' => now(),
            ];
        }

        // Melakukan upsert berdasarkan ID
        Offtaker::upsert($dataUpsert, ['id'], [
            'user_email', 'company_name', 'contact_name', 'phone', 'address', 'sync_status', 'updated_at'
        ]);

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