<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\RiwayatRekomendasi;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
use Exception;

class DashboardAdminController extends Controller
{
    public function index(Request $request)
    {
        try {
            // Hitung siswa (fallback ke ID unik di tabel riwayat jika data role user kosong/berbeda)
            $totalSiswa = User::whereIn('role', ['siswa', 'student'])->count();
            if ($totalSiswa === 0) {
                $totalSiswa = RiwayatRekomendasi::distinct('user_id')->count('user_id');
            }
            
            // Hitung total semua prediksi yang sudah dilakukan
            $totalRekomendasi = RiwayatRekomendasi::count();
            
            // Cek nilai rata-rata akurasi secara dinamis (default 86.4% jika kolom tidak ditemukan)
            $rataAkurasi = 86.4; 
            try {
                $tableName = (new RiwayatRekomendasi())->getTable();
                if (Schema::hasColumn($tableName, 'probabilitas')) {
                    $avg = RiwayatRekomendasi::avg('probabilitas');
                    if ($avg) $rataAkurasi = round($avg, 2);
                } elseif (Schema::hasColumn($tableName, 'akurasi')) {
                    $avg = RiwayatRekomendasi::avg('akurasi');
                    if ($avg) $rataAkurasi = round($avg, 2);
                }
            } catch (Exception $e) {}

            // Kelompokkan hasil rekomendasi untuk ditampilkan pada grafik
            $distribusiJurusan = RiwayatRekomendasi::selectRaw('hasil_rekomendasi_jurusan as jurusan, count(*) as total')
                ->whereNotNull('hasil_rekomendasi_jurusan')
                ->groupBy('hasil_rekomendasi_jurusan')
                ->orderBy('total', 'desc')
                ->get();

            return response()->json([
                'success' => true,
                'data' => [
                    'total_siswa' => $totalSiswa,
                    'rekomendasi_diproses' => $totalRekomendasi,
                    'rata_rata_akurasi' => $rataAkurasi,
                    'distribusi_jurusan' => $distribusiJurusan
                ]
            ], 200);

        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error: ' . $e->getMessage()
            ], 500);
        }
    }
}