<?php

use App\Http\Controllers\ProfileController;
use App\Models\Asupan;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request;
use Inertia\Inertia;
use App\Http\Controllers\Admin\QuizController;
use App\Http\Controllers\Admin\ExportController;
use Illuminate\Support\Facades\Mail;
use App\Mail\AsupanTersimpanMail;
use Carbon\Carbon;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/

// Halaman Utama (Landing Page)
Route::get('/', function () {
    return Inertia::render('Welcome', [
        'canLogin' => Route::has('login'),
        'canRegister' => Route::has('register'),
    ]);
});

// Route Pintar
Route::get('/home', function () {
    if (Auth::check()) {
        if (Auth::user()->role === 'admin') {
            return redirect()->route('admin.dashboard');
        }
        return redirect()->route('dashboard');
    }
    return redirect()->route('login');
})->middleware(['auth', 'verified'])->name('home');


// ==========================================
// 1. ROUTES KHUSUS USER (PASIEN)
// ==========================================
Route::middleware(['auth', 'verified'])->group(function () {

    // --- DASHBOARD PASIEN (DIUBAH AGAR MENERIMA DATA ASUPAN HARI INI) ---
    Route::get('/dashboard', function () {
        if (Auth::user()->role === 'admin') return redirect()->route('admin.dashboard');

        // Pastikan pakai zona waktu Indonesia (WIB)
        $today = Carbon::now('Asia/Jakarta')->format('Y-m-d');

        // Ambil data asupan makanan HARI INI untuk pasien yang login
        $recentMeals = Asupan::where('user_id', Auth::id())
                            ->where('tanggal', $today)
                            ->get();

        // Hitung total gizi hari ini
        $dailyStats = [
            'sodium_intake' => $recentMeals->sum('natrium'),
            'calorie_intake' => $recentMeals->sum('kalori'),
            'blood_pressure' => 'Belum Ada', // Dummy
        ];

        return Inertia::render('Dashboard', [
            'dailyStats' => $dailyStats,
            'recentMeals' => $recentMeals
        ]);
    })->name('dashboard');


    // --- SIMPAN PROFIL ONBOARDING PASIEN ---
    Route::post('/profile/onboarding', function (Request $request) {
        $request->validate([
            'jenis_kelamin' => 'required',
            'berat_badan' => 'required|numeric',
            'tinggi_badan' => 'required|numeric',
        ]);

        $user = Auth::user();
        $user->jenis_kelamin = $request->jenis_kelamin;
        $user->berat_badan = $request->berat_badan;
        $user->tinggi_badan = $request->tinggi_badan;
        $user->save();

        return redirect()->back();
    })->name('profile.onboarding');


    Route::get('/input-asupan', function () {
        if (Auth::user()->role === 'admin') return redirect()->route('admin.dashboard');

        $foods = DB::table('makanan')
            ->select('id', 'nama_bahan', 'energi', 'lemak', 'natrium', 'protein', 'kh')
            ->orderBy('nama_bahan')
            ->get();

        $asupans = Asupan::where('user_id', Auth::id())
            ->orderBy('tanggal', 'desc')
            ->orderBy('id', 'desc')
            ->get();

        return Inertia::render('InputAsupan', [
            'foods' => $foods,
            'asupans' => $asupans,
        ]);
    })->name('input.asupan');

    // Halaman Kuis Kepatuhan
    Route::get('/kuis', function () {
        if (Auth::user()->role === 'admin') return redirect()->route('admin.dashboard');

        // Ambil semua soal kuis dari database dan kirim ke React
        $questionsFromDB = \App\Models\Question::all();

        return Inertia::render('Kuis', [
            'questions' => $questionsFromDB
        ]);
    })->name('kuis');

    // Route untuk MENYIMPAN Hasil Kuis Pasien
    Route::post('/kuis/simpan', function (Request $request) {
        \App\Models\QuizResult::create([
            'user_id' => Auth::id(),
            'score'   => $request->score,
            'status'  => $request->status,
            'answers' => $request->answers,
        ]);
        return redirect()->route('dashboard');
    })->name('kuis.store');

    // Simpan Asupan & Kirim Email Notifikasi
    Route::post('/input-asupan/simpan', function (Request $request) {
        if (Auth::user()->role === 'admin') return redirect()->route('admin.dashboard');

        $validated = $request->validate([
            'tanggal' => 'required|date',
            'waktu' => 'required|string|max:50',
            'nama_makanan' => 'required|string|max:255',
            'porsi' => 'nullable|string|max:255',
            'kalori' => 'nullable|numeric',
            'natrium' => 'nullable|numeric',
            'protein' => 'nullable|numeric', // Penyesuaian gizi
            'karbo' => 'nullable|numeric',   // Penyesuaian gizi
        ]);

        Asupan::create([
            'user_id' => Auth::id(),
            'tanggal' => $validated['tanggal'],
            'waktu' => $validated['waktu'],
            'nama_makanan' => $validated['nama_makanan'],
            'porsi' => $validated['porsi'] ?? null,
            'kalori' => $validated['kalori'] ?? 0,
            'natrium' => $validated['natrium'] ?? 0,
            'protein' => $validated['protein'] ?? 0,
            'karbo' => $validated['karbo'] ?? 0,
        ]);

        // Siapkan data untuk dikirim ke email
        $dataAsupan = [
            'tanggal' => $validated['tanggal'],
            'waktu' => $validated['waktu'],
            'nama_makanan' => $validated['nama_makanan'],
            'porsi' => $validated['porsi'] ?? '-',
            'natrium' => $validated['natrium'] ?? 0,
            'kalori' => $validated['kalori'] ?? 0,
        ];

        // Kirim email konfirmasi ke pasien
        Mail::to(Auth::user()->email)->send(new AsupanTersimpanMail($dataAsupan));

        return redirect()->route('input.asupan');
    })->name('input.asupan.store');

});


// ==========================================
// 2. ROUTES KHUSUS ADMIN
// ==========================================
Route::middleware(['auth', 'verified', 'is_admin'])->prefix('admin')->group(function () {

    Route::get('/dashboard', function () {
        // Ambil data users dengan role 'user'
        $users = User::where('role', 'user')->get();

        $patientsData = [];
        $highSodiumCount = 0;
        $totalCompliance = 0;
        $complianceCount = 0;

        // Pastikan pakai zona waktu Indonesia (WIB)
        $today = Carbon::now('Asia/Jakarta')->format('Y-m-d');

        foreach ($users as $user) {
            // Ambil Kuis Terakhir Pasien
            $latestQuiz = \App\Models\QuizResult::where('user_id', $user->id)->latest()->first();

            // Ambil Semua Asupan Makanan Pasien HARI INI
            $asupanHariIni = Asupan::where('user_id', $user->id)
                                ->where('tanggal', $today)
                                ->get();

            // Jumlahkan Nutrisi Asli dari Database
            $totalNatrium = $asupanHariIni->sum('natrium');
            $totalKalori  = $asupanHariIni->sum('kalori');
            $totalProtein = $asupanHariIni->sum('protein');
            $totalKarbo   = $asupanHariIni->sum('karbo');

            // Hitung statistik dashboard atas
            if ($totalNatrium > 2000) {
                $highSodiumCount++;
            }

            if ($latestQuiz) {
                $totalCompliance += $latestQuiz->score;
                $complianceCount++;
            }

            // Tentukan status berdasarkan asupan Natrium hari ini
            $status = 'Aman';
            if ($totalNatrium > 2000) {
                $status = 'Bahaya';
            } elseif ($totalNatrium > 1500) {
                $status = 'Waspada';
            }

            // Format data patients untuk dashboard
            $patientsData[] = [
                'id' => $user->id,
                'name' => $user->name,
                'sodium' => $totalNatrium, // Real dari Database
                'total_kalori' => $totalKalori, // Real dari Database
                'total_protein' => $totalProtein, // Real dari Database
                'total_karbo' => $totalKarbo, // Real dari Database
                'compliance' => $latestQuiz ? $latestQuiz->score : 0,
                'last_quiz_date' => $latestQuiz ? $latestQuiz->created_at->format('d/m/Y') : 'Belum pernah',
                'status' => $status,
                'food_history' => $asupanHariIni // Dikirim untuk detail Modal pop-up
            ];
        }

        // Hitung rata-rata kepatuhan semua pasien
        $avgCompliance = $complianceCount > 0 ? round($totalCompliance / $complianceCount) : 0;

        return Inertia::render('Admin/Dashboard', [
            'patients' => $patientsData,
            'stats' => [
                'total' => $users->count(),
                'avgCompliance' => $avgCompliance,
                'highSodium' => $highSodiumCount
            ]
        ]);
    })->name('admin.dashboard');

    Route::get('/pengguna', function () {
        $usersFromDB = User::where('role', 'user')->latest()->get();
        return Inertia::render('Admin/DataPengguna', [
            'users' => $usersFromDB
        ]);
    })->name('admin.users');

    // Kelola Kuis
    Route::get('/kelola-kuis', [QuizController::class, 'index'])->name('admin.kuis');
    Route::post('/kelola-kuis', [QuizController::class, 'store'])->name('admin.kuis.store');
    Route::put('/kelola-kuis/{id}', [QuizController::class, 'update'])->name('admin.kuis.update');
    Route::delete('/kelola-kuis/{id}', [QuizController::class, 'destroy'])->name('admin.kuis.destroy');

    // Export Data
    Route::get('/export-excel', [ExportController::class, 'exportData'])->name('admin.export');

});


// ==========================================
// 3. ROUTES PROFIL (Bawaan Laravel Breeze)
// ==========================================
Route::middleware('auth')->group(function () {
    Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
    Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
    Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
});

require __DIR__.'/auth.php';
