<?php

namespace App\Http\Controllers;

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

class AuthController extends Controller
{
    // Fungsi untuk menampilkan form registrasi
    public function showRegisterForm()
    {
        return view('auth.register');
    }

    // Fungsi untuk menangani proses registrasi
    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'username' => 'required|unique:users',
            'email' => 'required|email|unique:users',
            'password' => 'required|min:6',
            'address' => 'required',
            'status' => 'required|in:pegawai,mahasiswa,masyarakat umum',
            'profile_image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:5000'
        ]);

        $credentials = $request->except(['password', 'profile_image']);
        $credentials['password'] = Hash::make($request->password);
        $credentials['role'] = 'visitor';

        // Handle image upload
        if ($request->hasFile('profile_image')) {
            // Menyimpan gambar ke folder storage/image_post dan memberikan nama file unik berdasarkan waktu
            $imagePath = $request->file('profile_image')->store('image_post', 'public');
            $credentials['profile_image'] = $imagePath;
        } else {
            $credentials['profile_image'] = 'image_post/profdef1.jpg'; // Gambar default
        }

        $user = User::create($credentials);

        if ($user) {
            $request->session()->regenerate();
            return redirect()->route('books.index');
        } else {
            return redirect()->route('register')->with('errorMessage', 'Registration failed!');
        }
    }

    // Fungsi untuk menampilkan form login
    public function showLoginForm()
    {
        return view('auth.login');
    }

    // Fungsi untuk menangani proses login
    public function login(Request $request)
    {
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required'],
        ]);

        if (Auth::attempt($credentials)) {
            $request->session()->regenerate();
            return redirect()->intended('books');
        }

        return back()->with('errorMessage', 'Login failed!');
    }

    // Fungsi untuk menangani logout
    public function logout(Request $request)
    {
        Auth::logout();

        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect()->route('welcome');
    }

    // Fungsi untuk menampilkan daftar pengguna (admin only)
    public function index()
    {
        $users = User::all();
        return view('admin.members.index', compact('users'));
    }
}
