<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Models\User;

class AuthController extends Controller
{
    public function showLoginForm()
    {
        return view('backend.login');
    }

public function login(Request $request)
{
    $request->validate([
        'email' => 'required',
        'password' => 'required',
        'role' => 'required|in:admin,guru,siswa,guru_bk,kepala_sekolah',
    ]);

    $identifier = $request->email;
    $role = $request->role;

    $user = null;

    if ($role === 'admin') {
        $user = User::where('email', $identifier)->where('role', 'admin')->first();
    } elseif (in_array($role, ['guru', 'guru_bk', 'kepala_sekolah'])) {
        $user = User::where('role', $role)
            ->whereHas('guru', function ($q) use ($identifier) {
                $q->where('nip', $identifier);
            })->first();
    } elseif ($role === 'siswa') {
        $user = User::where('role', 'siswa')
            ->whereHas('siswa', function ($q) use ($identifier) {
                $q->where('nisn', $identifier);
            })->first();
    }

    if (!$user) {
        return redirect()->back()->with('error', 'Pengguna tidak ditemukan atau role tidak sesuai');
    }

    if (!Hash::check($request->password, $user->password)) {
        return redirect()->back()->with('error', 'Password salah');
    }

    Auth::login($user);

    switch ($user->role) {
        case 'admin':
            return redirect()->route('backend.admin.index')->with('success', 'Selamat datang Admin!');
        case 'guru':
            return redirect()->route('backend.guru.index')->with('success', 'Selamat datang Guru!');
        case 'guru_bk':
            return redirect()->route('backend.bk.index')->with('success', 'Selamat datang Guru BK!');
        case 'kepala_sekolah':
            return redirect()->route('backend.kepsek.index')->with('success', 'Selamat datang Kepala Sekolah!');
        case 'siswa':
            return redirect()->route('backend.siswa.index')->with('success', 'Selamat datang Siswa!');
    }

    return redirect('/')->with('success', 'Login berhasil.');
}

    public function logout()
    {
        Auth::logout();
        return redirect('/');
    }
}

