<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class LoginController extends Controller
{
    /**
     * Show the login page
     */
    public function index()
    {
        // If user is already logged in, redirect based on role
        if (session()->has('logged_in') && session('logged_in')) {
            return $this->redirectBasedOnRole();
        }

        return view('loginpage');
    }

    /**
     * Handle login request
     */
    public function login(Request $request)
    {
        $request->validate([
            'username' => 'required',
            'password' => 'required',
        ]);

        $user = DB::table('users')
            ->select('id', 'username', 'email', 'name', 'password', 'id_roleuser', 'image') // tambahkan 'image'
            ->where('username', $request->username)
            ->first();

        if (!$user) {
            return back()->with('error', 'Username atau password salah!');
        }

        try {
            $decryptedPassword = Crypt::decryptString($user->password);
        } catch (\Exception $e) {
            return back()->with('error', 'Password tidak valid!');
        }

        if ($request->password !== $decryptedPassword) {
            return back()->with('error', 'Username atau password salah!');
        }

        // Get role information
        $roleInfo = DB::table('roleuser')
            ->where('id_role', $user->id_roleuser)
            ->first();

        if (!$roleInfo) {
            return back()->with('error', 'Role pengguna tidak ditemukan!');
        }

        // Create session data
        $userData = [
            'id' => $user->id,
            'username' => $user->username,
            'email' => $user->email,
            'name' => $user->name,
            'photo' => $user->image ?? null,
            'role_id' => $user->id_roleuser,
            'role_name' => $roleInfo->nama_role,
            'logged_in' => true
        ];

        // Store user data in session
        session($userData);

        // Redirect based on role
        return $this->redirectBasedOnRole();
    }

    /**
     * Redirect user based on role
     */
    private function redirectBasedOnRole()
    {
        if (session('role_name') == 'admin') {
            return redirect()->route('dashboard');
        } else {
            // For students/alumni
            return redirect()->route('formalumni');
        }
    }

    /**
     * Logout user
     */
    public function logout()
    {
        session()->flush();

        return redirect()->route('login')->with('success', 'Berhasil logout!');
    }
}
