<?php

namespace App\Http\Controllers;

use App\Http\Requests\ProfileUpdateRequest; 
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\View\View;
use Illuminate\Support\Facades\Hash;
use App\Services\DummyDataService;

class ProfileController extends Controller
{
    /**
     * Tampilkan halaman profil user.
     */
    public function index(Request $request): View
    {
        $user = $request->user();
        
        $viewData = ['user' => $user];

        if ($user->role === 'penjaga perpus') {
            $viewData['statistik'] = DummyDataService::getAdminDashboardStats();
            $viewData['aktivitasTerakhir'] = DummyDataService::getAktivitasTerakhir();

        } elseif ($user->role === 'guru') {
            $viewData['bukuOffline'] = DummyDataService::getBukuPinjamOffline($user);
            $viewData['bukuOnline'] = DummyDataService::getBacaBukuOnline($user);
            $viewData['laporan'] = DummyDataService::getLaporanMinatBaca();
            
        } else {
            $viewData['bukuOffline'] = DummyDataService::getBukuPinjamOffline($user);
            $viewData['bukuOnline'] = DummyDataService::getBacaBukuOnline($user);
            $viewData['statistik'] = DummyDataService::getDashboardStats();
        }

        return view('profile.index', $viewData);
    }

    /**
     * Tampilkan form edit profil.
     */
    public function edit(Request $request): View
    {
        return view('profile.edit', [
            'user' => $request->user(),
        ]);
    }

    /**
     * Update data profil ke Database MySQL.
     */
    public function update(Request $request): RedirectResponse
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'], 
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email,'.Auth::id()],
            'no_hp' => ['nullable', 'string', 'max:15'], 
        ]);

        $user = $request->user();
        $user->name = $request->name;
        $user->email = $request->email;
        $user->no_hp = $request->no_hp; 

        if ($user->isDirty('email')) {
            $user->email_verified_at = null;
        }

        $user->save();

        return Redirect::route('profile.edit')->with('status', 'profile-updated');
    }

    /**
     * Hapus akun user.
     */
    public function destroy(Request $request): RedirectResponse
    {
        $request->validateWithBag('userDeletion', [
            'password' => ['required', 'current_password'],
        ]);

        $user = $request->user();

        Auth::logout();

        $user->delete(); 

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

        return Redirect::to('/');
    }
}