<?php

namespace App\Http\Controllers\Website;

use App\Http\Controllers\Controller;
use App\Models\PreferenceResultSubDistrict;
use App\Models\PreferenceResultVillage;
use App\Models\Village;
use Illuminate\Http\Request;

class SubDistrictResultPreferenceController extends Controller
{
    public function index()
    {
        // mengambil list tahun
        $listResultPreference = PreferenceResultSubDistrict::all();
        $years = array_unique(array_column($listResultPreference->toArray(), 'year'));
        sort($years);

        return view('website.app.sub-district-result-preference', compact('years'));
    }

    public function getSubDistrictResultPreference($month, $year)
    {
        $preferenceResultSubDistrict = PreferenceResultSubDistrict::select(
            'preference_result_sub_districts.id',
            'preference_result_sub_districts.sub_district_id as prsd_sub_district_id',
            'preference_result_sub_districts.value_preference',
            'preference_result_sub_districts.plant_name',
            'preference_result_sub_districts.month',
            'preference_result_sub_districts.year',
            'sub_district.id as sd_id',
            'sub_district.sub_district',
            'sub_district.latitude',
            'sub_district.longitude'
        )
            ->join('sub_district', 'sub_district.id', '=', 'preference_result_sub_districts.sub_district_id')
            ->where('preference_result_sub_districts.month', '=', $month)
            ->where('preference_result_sub_districts.year', '=', $year)
            ->get();

        $preferenceResultVillage = PreferenceResultVillage::select(
            'preference_result_villages.id',
            'preference_result_villages.village_id as prsv_village_id',
            'preference_result_villages.value_preference',
            'preference_result_villages.plant_name',
            'preference_result_villages.month',
            'preference_result_villages.year',
            'village.id as v_id',
            'village.sub_district_id as v_sub_district_id',
            'village.village',
            'village.latitude',
            'village.longitude',
        )
            ->join('village', 'village.id', '=', 'preference_result_villages.village_id')
            ->where('preference_result_villages.month', '=', $month)
            ->where('preference_result_villages.year', '=', $year)
            ->get();


        return response()->json([
            'preferenceResultSubDistrict' => $preferenceResultSubDistrict,
            'preferenceResultVillage' => $preferenceResultVillage,
        ]);
    }
}
