<?php

namespace App\Http\Controllers\user;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class ProfileController extends Controller
{
    private function checkUser()
    {
        if (!Auth::check() && !session('is_user_logged_in')) {
            return redirect('/login');
        }
        if (Auth::check()) {
            $user = Auth::user();
            if ($user->role === 'Super Admin' || $user->role === 'Admin') {
                return redirect('/');
            }
        }
        return null;
    }

    public function index()
    {
        if ($redir = $this->checkUser()) return $redir;

        $user = Auth::user();
        return view('user.profile.profile', compact('user'));
    }

    public function update(Request $request)
    {
        if ($redir = $this->checkUser()) return $redir;

        $user = Auth::user();

        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'max:255', 'unique:users,email,' . $user->id],
        ]);

        $user->update([
            'name' => $data['name'],
            'email' => $data['email'],
        ]);

        session([
            'user_name' => $data['name'],
            'user_email' => $data['email'],
        ]);

        return redirect()->route('user.profile.index')->with('success', 'Profile updated successfully.');
    }

    public function changePassword()
    {
        if ($redir = $this->checkUser()) return $redir;

        $user = Auth::user();
        return view('user.profile.change_password', compact('user'));
    }

    public function updatePassword(Request $request)
    {
        if ($redir = $this->checkUser()) return $redir;

        $user = Auth::user();

        $request->validate([
            'current_password' => ['required', 'current_password'],
            'password' => ['required', 'confirmed', 'min:6'],
        ]);

        $user->update([
            'password' => Hash::make($request->password),
        ]);

        return redirect()->route('user.profile.index')->with('success', 'Password updated successfully.');
    }
}
