<?php

namespace App\Http\Controllers\Api\Student;

use App\Http\Controllers\Controller;
use App\Models\RiwayatRekomendasi;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use Illuminate\Validation\ValidationException;

class RecommendationApiController extends Controller
{
    public function hitungPrediksi(Request $request)
    {
        $user = Auth::user();

        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => 'User belum login.'
            ], 401);
        }

        $validated = $request->validate([
            'agama' => 'required|numeric|min:0|max:100',
            'pkn' => 'required|numeric|min:0|max:100',
            'bahasa_indonesia' => 'required|numeric|min:0|max:100',
            'bahasa_inggris' => 'required|numeric|min:0|max:100',
            'matematika' => 'required|numeric|min:0|max:100',
            'fisika' => 'required|numeric|min:0|max:100',
            'kimia' => 'required|numeric|min:0|max:100',
            'biologi' => 'required|numeric|min:0|max:100',
            'sejarah' => 'required|numeric|min:0|max:100',
            'geografi' => 'required|numeric|min:0|max:100',
            'ekonomi_mapel' => 'required|numeric|min:0|max:100',
            'sosiologi' => 'required|numeric|min:0|max:100',
            'seni_budaya' => 'required|numeric|min:0|max:100',
            'pjok' => 'required|numeric|min:0|max:100',
            'informatika' => 'required|numeric|min:0|max:100',

            'riasec_r' => 'required|numeric|min:0|max:100',
            'riasec_i' => 'required|numeric|min:0|max:100',
            'riasec_a' => 'required|numeric|min:0|max:100',
            'riasec_s' => 'required|numeric|min:0|max:100',
            'riasec_e' => 'required|numeric|min:0|max:100',
            'riasec_c' => 'required|numeric|min:0|max:100',

            'gaji_ortu' => 'required|numeric|min:0',
        ]);

        $gaji = (float) $validated['gaji_ortu'];

        if ($gaji < 2000000) {
            $ekonomiOrangTua = 'Kurang Mampu';
        } elseif ($gaji <= 5000000) {
            $ekonomiOrangTua = 'Menengah';
        } else {
            $ekonomiOrangTua = 'Mampu';
        }

        $payload = $validated;
        $payload['ekonomi_orang_tua'] = $ekonomiOrangTua;

        try {
            $response = Http::timeout(15)
                ->acceptJson()
                ->post('http://127.0.0.1:5000/predict', $payload);

            if (!$response->successful()) {
                return response()->json([
                    'success' => false,
                    'message' => 'ML Engine Error: ' . ($response->json()['message'] ?? $response->body())
                ], 500);
            }

            $responseData = $response->json();

            if (!isset($responseData['success']) || !$responseData['success']) {
                return response()->json([
                    'success' => false,
                    'message' => 'ML Engine Error: ' . ($responseData['message'] ?? 'Unknown Error')
                ], 500);
            }

            $teksJurusan = $responseData['prediksi_jurusan'] ?? null;

            if (!$teksJurusan) {
                return response()->json([
                    'success' => false,
                    'message' => 'Prediksi jurusan tidak ditemukan pada respons Flask.'
                ], 500);
            }

            $riwayat = RiwayatRekomendasi::create([
                'user_id' => $user->id,
                'agama' => $validated['agama'],
                'pkn' => $validated['pkn'],
                'bahasa_indonesia' => $validated['bahasa_indonesia'],
                'bahasa_inggris' => $validated['bahasa_inggris'],
                'matematika' => $validated['matematika'],
                'fisika' => $validated['fisika'],
                'kimia' => $validated['kimia'],
                'biologi' => $validated['biologi'],
                'sejarah' => $validated['sejarah'],
                'geografi' => $validated['geografi'],
                'ekonomi_mapel' => $validated['ekonomi_mapel'],
                'sosiologi' => $validated['sosiologi'],
                'seni_budaya' => $validated['seni_budaya'],
                'pjok' => $validated['pjok'],
                'informatika' => $validated['informatika'],
                'riasec_r' => $validated['riasec_r'],
                'riasec_i' => $validated['riasec_i'],
                'riasec_a' => $validated['riasec_a'],
                'riasec_s' => $validated['riasec_s'],
                'riasec_e' => $validated['riasec_e'],
                'riasec_c' => $validated['riasec_c'],
                'gaji_ortu' => $validated['gaji_ortu'],
                'hasil_rekomendasi_jurusan' => $teksJurusan,
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Prediksi berhasil dibuat.',
                'redirect_url' => route('student.result', ['id' => $riwayat->id]),
                'prediksi_jurusan' => $teksJurusan,
                'top_predictions' => $responseData['top_predictions'] ?? null
            ]);
        } catch (\Throwable $e) {
            return response()->json([
                'success' => false,
                'message' => 'Koneksi ke API Flask Python gagal: ' . $e->getMessage()
            ], 500);
        }
    }
}