<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Beneficiary;

class MapController extends Controller
{
    public function index()
    {
        $beneficiaries = Beneficiary::accessibleBy(auth()->user())
            ->with(['horticultures', 'livestocks', 'poultries', 'fish'])
            ->whereNotNull('latitude')
            ->whereNotNull('longitude')
            ->get();

        // Daftar warna yang cerah dan kontras untuk tiap desa
        $colors = [
            '#e6194B', '#3cb44b', '#ffe119', '#4363d8', '#f58231', '#911eb4', '#42d4f4', '#f032e6', '#bfef45', '#fabed4', 
            '#469990', '#dcbeff', '#9A6324', '#fffac8', '#800000', '#aaffc3', '#808000', '#ffd8b1', '#000075', '#a9a9a9',
            '#000000', '#577590', '#4d908e', '#43aa8b', '#90be6d', '#f9c74f', '#f9844a', '#f8961e', '#f3722c', '#f94144',
            '#277da1', '#577590', '#4d908e', '#43aa8b', '#90be6d', '#f9c74f', '#f9844a', '#f8961e', '#f3722c', '#f94144',
            '#6a4c93', '#1982c4', '#8ac926', '#ffca3a', '#ff595e', '#5f0f40', '#9a031e', '#fb8b24', '#e36414', '#0f4c5c',
            '#582f0e', '#7f4f24', '#936639', '#a68a64', '#b6ad90', '#c2c5aa', '#a3b18a', '#588157', '#3a5a40', '#344e41',
            '#001219', '#005f73', '#0a9396', '#94d2bd', '#e9d8a6', '#ee9b00', '#ca6702', '#bb3e03', '#ae2012', '#9b2226'
        ];

        // Ambil semua desa unik
        $villages = $beneficiaries->pluck('village')->unique()->values()->toArray();
        $villageColors = [];
        foreach ($villages as $index => $village) {
            // Assign warna berdasarkan index (cycle colors if more than available)
            $villageColors[$village] = $colors[$index % count($colors)];
        }

        $mappedBeneficiaries = $beneficiaries->map(function ($b) use ($villageColors) {
            $type = 'Lainnya';
            if ($b->horticultures->count() > 0) $type = 'Hortikultura';
            elseif ($b->livestocks->count() > 0) $type = 'Ternak';
            elseif ($b->poultries->count() > 0) $type = 'Unggas';
            elseif ($b->fish->count() > 0) $type = 'Perikanan';

            return [
                'id' => $b->id,
                'name' => $b->name,
                'lat' => (float)$b->latitude,
                'lng' => (float)$b->longitude,
                'type' => $type,
                'color' => $villageColors[$b->village] ?? '#gray',
                'village' => $b->village,
                'district' => $b->district,
            ];
        });

        // Ambil pemetaan kecamatan ke desa
        $districtVillages = $beneficiaries->groupBy('district')->map(function ($items) {
            return $items->pluck('village')->unique()->values()->toArray();
        })->toArray();

        return view('map', [
            'beneficiaries' => $mappedBeneficiaries,
            'villageColors' => $villageColors,
            'villages' => $villages,
            'districtVillages' => $districtVillages
        ]);
    }
}
