<?php

namespace App\Http\Controllers\Web\Konfigurasi;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
    public function login()
    {
        $title = 'Login';
        return view('auth.login', compact('title'));
    }

    public function register()
    {
        $title = 'Register';
        return view('auth.register', compact('title'));
    }

    public function createAccount(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8|confirmed',
        ]);

        User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'email_verified_at' => null,
            'created_by' => null,
            'updated_by' => null,
            'deleted_by' => null,
        ]);

        return redirect()->route('auth.login')->with('success', 'Account created successfully. Please login.');
    }

    public function verify(User $user)
    {
        try {
            $newStatus = $user->email_verified_at ? null : now();
            
            $user->update([
                'email_verified_at' => $newStatus
            ]);

            return response()->json([
                'status' => 'success',
                'message' => 'User status updated successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Server Error'], 500);
        }
    }

    public function authenticate(Request $request)
    {
        $request->validate([
            'email_username' => 'required|string',
            'password' => 'required|string',
        ]);

        $login = $request->input('email_username');

        $field = filter_var($login, FILTER_VALIDATE_EMAIL)
            ? 'email'
            : 'name';

        if (Auth::attempt([$field => $login, 'password' => $request->password], $request->boolean('remember'))) {
            if (Auth::user()->email_verified_at === null) {
                Auth::logout();

                return back()->withErrors([
                    'email_username' => 'Akun belum diverifikasi.',
                ]);
            }
            $request->session()->regenerate();
            return redirect()->intended('');
        }

        throw ValidationException::withMessages([
            'email_username' => ['Email atau username salah.'],
        ]);
    }

    public function logout(Request $request)
    {
        Auth::logout();

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

        return redirect()->intended('');
    }
}
