<?php

namespace App\Http\Controllers\Api\Admin;

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

class DashboardAdminController extends Controller
{
    public function index(Request $request)
    {
        try {
            $riwayatModel = new RiwayatRekomendasi();
            $tableName = $riwayatModel->getTable();

            $totalSiswa = 0;

            try {
                $siswaModel = new Siswa();
                if (Schema::hasTable($siswaModel->getTable())) {
                    $totalSiswa = Siswa::count();
                }
            } catch (Throwable $e) {
                $totalSiswa = 0;
            }

            if ($totalSiswa === 0) {
                $totalSiswa = User::whereIn('role', ['siswa', 'student'])->count();
            }

            $totalRekomendasi = Schema::hasTable($tableName) ? RiwayatRekomendasi::count() : 0;
            $kolomAkurasi = $this->getKolomAkurasi($tableName);
            $rataAkurasi = null;

            if ($kolomAkurasi && Schema::hasTable($tableName)) {
                $avg = RiwayatRekomendasi::whereNotNull($kolomAkurasi)->avg($kolomAkurasi);
                $rataAkurasi = $avg !== null ? round((float) $avg, 2) : null;
            }

            $akurasiStatus = $rataAkurasi !== null
                ? 'Berdasarkan rata-rata tingkat keyakinan dari seluruh hasil rekomendasi.'
                : 'Belum ada nilai keyakinan prediksi yang tersimpan. Lakukan prediksi baru terlebih dahulu.';

            $distribusiJurusan = collect();

            if (Schema::hasTable($tableName) && Schema::hasColumn($tableName, 'hasil_rekomendasi_jurusan')) {
                $selectDistribusi = 'hasil_rekomendasi_jurusan as jurusan, COUNT(*) as total';

                if ($kolomAkurasi) {
                    $selectDistribusi .= ', ROUND(AVG(' . $kolomAkurasi . '), 2) as rata_akurasi';
                }

                $distribusiJurusan = RiwayatRekomendasi::selectRaw($selectDistribusi)
                    ->whereNotNull('hasil_rekomendasi_jurusan')
                    ->groupBy('hasil_rekomendasi_jurusan')
                    ->orderBy('total', 'desc')
                    ->limit(10)
                    ->get()
                    ->map(function ($item) use ($kolomAkurasi) {
                        return [
                            'jurusan' => $item->jurusan,
                            'total' => (int) $item->total,
                            'rata_akurasi' => $kolomAkurasi && $item->rata_akurasi !== null
                                ? round((float) $item->rata_akurasi, 2)
                                : null,
                        ];
                    });
            }

            return response()->json([
                'success' => true,
                'message' => 'Statistik dashboard berhasil dimuat.',
                'data' => [
                    'total_siswa' => $totalSiswa,
                    'rekomendasi_diproses' => $totalRekomendasi,
                    'rata_rata_akurasi' => $rataAkurasi,
                    'akurasi_status' => $akurasiStatus,
                    'distribusi_jurusan' => $distribusiJurusan,
                ],
            ], 200);
        } catch (Throwable $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal memuat statistik dashboard.',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    private function getKolomAkurasi(string $tableName): ?string
    {
        if (!Schema::hasTable($tableName)) {
            return null;
        }

        foreach (['akurasi_prediksi', 'probabilitas', 'akurasi'] as $column) {
            if (Schema::hasColumn($tableName, $column)) {
                return $column;
            }
        }

        return null;
    }
}