<?php

namespace App\Http\Controllers\Website;

use App\Http\Controllers\Controller;
use App\Models\CriteriaData;
use App\Models\Plant;
use App\Models\PreferenceResultSubDistrict;
use App\Models\PreferenceResultVillage;
use App\Models\SubDistrict;
use App\Models\User;
use App\Models\Village;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{
    public function index()
    {

        $countUsers = count(User::get());
        $countSubDistrict = count(SubDistrict::get());
        $countVillage = count(Village::get());
        $countPlant = count(Plant::get());
        $countCriteria = count(CriteriaData::get());

        // mengambil list tahun
        $listResultPreference = PreferenceResultSubDistrict::all();
        $years = array_unique(array_column($listResultPreference->toArray(), 'year'));
        sort($years);

        // mengambil list kecamatan
        $listSubDistrict = SubDistrict::all();

        return view('website.app.dashboard', compact('countUsers', 'countSubDistrict', 'countVillage', 'countPlant', 'years', 'countCriteria', 'listSubDistrict'));
    }

    public function getResultSubDistrictByYear($year)
    {
        $results = PreferenceResultSubDistrict::select(
            'preference_result_sub_districts.sub_district_id',
            'sub_district.sub_district',
            'preference_result_sub_districts.year',
            'sub_district.latitude',
            'sub_district.longitude',
            DB::raw("GROUP_CONCAT(preference_result_sub_districts.month ORDER BY preference_result_sub_districts.month ASC SEPARATOR ',') as months"),
            DB::raw("GROUP_CONCAT(preference_result_sub_districts.plant_name ORDER BY preference_result_sub_districts.month ASC SEPARATOR ',') as plants")
        )
            ->join('sub_district', 'sub_district.id', '=', 'preference_result_sub_districts.sub_district_id')
            ->where('preference_result_sub_districts.year', '=', $year)
            ->groupBy('preference_result_sub_districts.sub_district_id', 'sub_district.sub_district', 'preference_result_sub_districts.year')
            ->get();

        $resultSubDistrictByYear = [];
        foreach ($results as $row) {
            $subDistrictId = $row->sub_district_id;

            // Pisahkan data bulan dan tanaman menjadi array
            $months = explode(',', $row->months);
            $plants = explode(',', $row->plants);

            // Gabungkan bulan dan tanaman menjadi pasangan array
            $list = [];
            $plantCounts = [];

            foreach ($months as $index => $month) {
                $plant = $plants[$index] ?? null;

                // Menyusun list bulan & tanaman
                $list[] = [
                    'bulan' => $month,
                    'tanaman' => $plants[$index] ?? null
                ];

                // Menghitung jumlah tanaman per jenis
                if ($plant) {
                    if (!isset($plantCounts[$plant])) {
                        $plantCounts[$plant] = 0;
                    }
                    $plantCounts[$plant]++;
                }
            }

            // Ubah format plantCounts ke dalam array hasil yang diinginkan
            $result = [];
            foreach ($plantCounts as $plantName => $count) {
                $result[] = [
                    'jenis_tanaman' => $plantName,
                    'jumlah_tanaman' => $count
                ];
            }

            // Simpan dalam array terstruktur
            $resultSubDistrictByYear[$subDistrictId] = [
                'sub_district_id' => $subDistrictId,
                'subdistrict' => $row->sub_district,
                'latitude' => $row->latitude,
                'longitude' => $row->longitude,
                'tahun' => $row->year,
                'list' => $list,
                'result' => $result
            ];
        }

        $resultsVillage = PreferenceResultVillage::select(
            'preference_result_villages.village_id',
            'village.village',
            'preference_result_villages.year',
            'village.latitude',
            'village.longitude',
            'village.sub_district_id as v_sub_district_id',
            DB::raw("GROUP_CONCAT(preference_result_villages.month ORDER BY preference_result_villages.month ASC SEPARATOR ',') as months"),
            DB::raw("GROUP_CONCAT(preference_result_villages.plant_name ORDER BY preference_result_villages.month ASC SEPARATOR ',') as plants")
        )
            ->join('village', 'village.id', '=', 'preference_result_villages.village_id')
            ->where('preference_result_villages.year', '=', $year)
            ->groupBy('preference_result_villages.village_id', 'village.village', 'preference_result_villages.year')
            ->get();

        $resultVillageByYear = [];
        foreach ($resultsVillage as $row) {
            $villageId = $row->village_id;

            // Pisahkan data bulan dan tanaman menjadi array
            $months = explode(',', $row->months);
            $plants = explode(',', $row->plants);

            // Gabungkan bulan dan tanaman menjadi pasangan array
            $list = [];
            $plantCounts = [];

            foreach ($months as $index => $month) {
                $plant = $plants[$index] ?? null;

                // Menyusun list bulan & tanaman
                $list[] = [
                    'bulan' => $month,
                    'tanaman' => $plants[$index] ?? null
                ];

                // Menghitung jumlah tanaman per jenis
                if ($plant) {
                    if (!isset($plantCounts[$plant])) {
                        $plantCounts[$plant] = 0;
                    }
                    $plantCounts[$plant]++;
                }
            }

            // Ubah format plantCounts ke dalam array hasil yang diinginkan
            $result = [];
            foreach ($plantCounts as $plantName => $count) {
                $result[] = [
                    'jenis_tanaman' => $plantName,
                    'jumlah_tanaman' => $count
                ];
            }

            // Simpan dalam array terstruktur
            $resultVillageByYear[$villageId] = [
                'village' => $row->village,
                'latitude' => $row->latitude,
                'longitude' => $row->longitude,
                'sub_district_id' => $row->v_sub_district_id,
                'tahun' => $row->year,
                'list' => $list,
                'result' => $result
            ];
        }


        $listPlant = Plant::all();

        return response()->json([
            'resultSubDistrictByYear' => $resultSubDistrictByYear,
            'resultVillageByYear' => $resultVillageByYear,
            'listPlant' => $listPlant
        ]);
    }
}
