<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Auth;
use App\Models\RiwayatPrediksi;

class PrediksiController extends Controller
{
    // menampilkan halaman utama
    public function index()
    {
        return view('tampilanutama.utama');
    }

    // proses prediksi ke Flask
    public function proses(Request $request)
    {
        $data   = $request->all();
        $gejala = $request->gejala ?? [];

        if (count($gejala) < 2) {
            return redirect()->back()->with('error', 'Gejala yang dimasukkan belum cukup untuk melakukan prediksi penyakit.');
        }

        $response = Http::post('https://alyaghania.pythonanywhere.com/predict', [
            "Smoking_Status" => $request->merokok == "ya" ? 1 : 0,
            "Alcohol_Use"    => $request->alkohol == "ya" ? 1 : 0,
            "Stress_Level"   => $request->stres   == "ya" ? 1 : 0,

            "Abdominal_Pain" => in_array("g1", $gejala) ? 1 : 0,
            "Bloating"       => in_array("g2", $gejala) ? 1 : 0,
            "Heartburn"      => in_array("g3", $gejala) ? 1 : 0,
            "Rectal_Bleeding"=> in_array("g4", $gejala) ? 1 : 0,
            "Appetite_Loss"  => in_array("g5", $gejala) ? 1 : 0,
            "Weight_Loss"    => in_array("g6", $gejala) ? 1 : 0,

            "NSAID_Use"      => $request->obat == "ya" ? 1 : 0,
        ]);

        $hasil = $response->json()['hasil_prediksi'] ?? "Tidak ada hasil";
        $indikasi = $response->json()['indikasi_lain'] ?? [];

        $mapping = [
            'GASTRITIS' => 'Gastritis',
            'GERD'      => 'Gerd',
            'DISPEPSIA' => 'Dispepsia',
        ];
        $hasil = $mapping[$hasil] ?? $hasil;
        $indikasi = array_map(fn($i) => $mapping[$i] ?? $i, $indikasi);

        // Simpan ke database
        if ($hasil != "Tidak ada hasil" && Auth::check()) {
            RiwayatPrediksi::create([
                'user_id'       => Auth::id(),
                'nama'          => Auth::user()->name, // ambil dari akun
                'jenis_kelamin' => null,
                'umur'          => null,
                'gejala'        => $gejala,
                'stres'         => $request->stres,
                'merokok'       => $request->merokok,
                'alkohol'       => $request->alkohol,
                'obat'          => $request->obat,
                'hasil'         => $hasil,
                'indikasi'      => $indikasi
            ]);
        }

        return view('tampilanutama.prediksi', compact('hasil', 'data', 'indikasi'));
    }

    // riwayat prediksi
    public function riwayat()
    {
        $riwayat = RiwayatPrediksi::where('user_id', Auth::id())
                    ->orderBy('created_at', 'desc')
                    ->get();

        return view('tampilanutama.riwayat', compact('riwayat'));
    }
}
