<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\SchoolProfile;
use App\Models\LessonHour;

class AuthController extends Controller
{
    // --- 1. TAMPILKAN HALAMAN LOGIN ---
    public function showLoginForm()
    {
        if (Auth::check()) {
            return redirect()->route('dashboard');
        }

        // 1. Ambil Data Sekolah (Opsional, jika ingin logo dsb)
        $school = SchoolProfile::first();
        
        // 2. Ambil Jam Pelajaran (LANGSUNG DARI MODELNYA)
        try {
            $lessonHours = LessonHour::orderBy('start_time', 'asc')->get();
        } catch (\Exception $e) {
            $lessonHours = [];
        }

        return view('auth.login', compact('lessonHours'));
    }

    // --- 2. PROSES LOGIN ---
    public function login(Request $request)
    {
        $credentials = $request->validate([
            'username' => ['required'],
            'password' => ['required'],
        ]);

        if (Auth::attempt($credentials)) {
            $request->session()->regenerate();

            // JIKA REQUEST DARI POPUP (AJAX/FETCH)
            if ($request->ajax() || $request->wantsJson()) {
                return response()->json([
                    'nama' => Auth::user()->name, // Sesuaikan jika kolom namanya berbeda
                    'redirect' => url('dashboard') // Pastikan URL sesuai dengan dashboard Anda
                ], 200);
            }

            // LOGIN BIASA
            return redirect()->intended('dashboard');
        }

        // JIKA LOGIN GAGAL & REQUEST DARI POPUP (AJAX/FETCH)
        if ($request->ajax() || $request->wantsJson()) {
            return response()->json([
                'message' => 'Username atau password salah!'
            ], 401);
        }

        // JIKA LOGIN GAGAL BIASA
        return back()->with('error', 'Username atau password salah.');
    }

    // --- 3. LOGOUT ---
    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect('/login');
    }
}