<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Kriteria;
use App\Models\Alternatif;
use App\Models\SubKriteria;
use Illuminate\Support\Facades\DB;
use App\Models\HistorisPerhitungan;
use App\Models\MemberKelompokTani;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;

class DashboardController extends Controller
{
    public function index(Request $request)
    {
        $user = Auth::user();
        $periode = $request->input('periode');

        $isSuperAdmin = $user->role === 'super_admin';
        $isAdmin = $user->role === 'admin';

        // Ambil daftar user_id yang boleh diakses
        if ($isSuperAdmin) {
            $accessibleUserIds = User::pluck('id');
        } elseif ($isAdmin) {
            $adminMember = MemberKelompokTani::where('user_id', $user->id)->first();
            $accessibleUserIds = MemberKelompokTani::where('kelompok_tani_id', $adminMember->kelompok_tani_id)
                ->pluck('user_id');
        } else {
            $accessibleUserIds = collect([$user->id]);
        }

        // Data historis (filter berdasarkan user_id yang boleh diakses)
        $query = HistorisPerhitungan::whereIn('user_id', $accessibleUserIds);

        if ($periode) {
            $query->where('periode', $periode);
        }

        $historis = $query->orderBy('periode', 'desc')->paginate(10);

        // Chart Data
        $chartSubquery = DB::table('historis_perhitungan')
            ->select('periode', DB::raw('MAX(nilai_akhir) as max_nilai'), 'user_id')
            ->whereIn('user_id', $accessibleUserIds)
            ->groupBy('periode', 'user_id');

        $chartQuery = DB::table('historis_perhitungan as h1')
            ->joinSub($chartSubquery, 'h2', function ($join) {
                $join->on('h1.periode', '=', 'h2.periode')
                     ->on('h1.nilai_akhir', '=', 'h2.max_nilai')
                     ->on('h1.user_id', '=', 'h2.user_id');
            })
            ->select('h1.periode', 'h1.nilai_akhir', 'h1.nama_lahan')
            ->orderBy('h1.periode', 'asc');

        $chartData = $chartQuery->get();

        return view('admin.dashboard', [
            'title' => 'Dashboard',
            'jumlahKriteria' => Kriteria::count(),
            'jumlahSubkriteria' => SubKriteria::count(),
            'jumlahAlternatif' => Alternatif::whereIn('user_id', $accessibleUserIds)->count(),
            'jumlahUser' => $isSuperAdmin ? User::count() : $accessibleUserIds->count(),
            'user' => $user,
            'historis' => $historis,
            'periode' => $periode,
            'chartData' => $chartData
        ]);
    }
}
