<?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\Support\Facades\Hash;
use Illuminate\Validation\Rule;
use App\Models\User;
use Illuminate\View\View;

class ProfileController extends Controller
{
/**
     * Display the user's profile form.
     */
    public function edit(Request $request): View
    {
        return view('profile.edit', [
            'user' => $request->user(),
        ]);
    }

    /**
     * Update the user's profile information.
     */
    public function update(ProfileUpdateRequest $request): RedirectResponse
    {
        $request->user()->fill($request->validated());

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

        $request->user()->save();

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

    /**
     * Delete the user's account.
     */
    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('/');
    }

    public function profilesaya()
    {
        $user = Auth::user();
        return view('admin.profilesaya', compact('user'));
    }

    
    public function updateprofilesaya(Request $request)
    {
        $user = Auth::user();
        
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => [
                'required',
                'string',
                'email',
                'max:255',
                Rule::unique('users')->ignore($user->id),
            ],
            'password_current' => ['nullable', 'string'],
            'password' => ['nullable', 'string', 'min:8'],
        ]);
        
        // Jika ada password baru, verifikasi password lama
        if ($request->filled('password')) {
            if (!$request->filled('password_current')) {
                return back()->with('error', 'Kata sandi saat ini diperlukan untuk mengubah kata sandi');
            }
            
            if (!Hash::check($request->password_current, $user->password)) {
                return back()->with('error', 'Kata sandi saat ini tidak cocok');
            }
        }
        
        // Buat array data yang akan diupdate
        $updateData = [
            'name' => $validated['name'],
            'email' => $validated['email'],
            'usertype' => $user->usertype, // Pertahankan usertype (tanpa underscore)
        ];
        
        // Tambahkan password jika ada
        if ($request->filled('password')) {
            $updateData['password'] = Hash::make($validated['password']);
        }
        
        // Update user
        User::where('id', $user->id)->update($updateData);
        
        // Logout user setelah update profil
        Auth::logout();
        
        // Invalidate session untuk keamanan
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        
        // Redirect ke halaman login dengan pesan sukses
        return redirect()->route('login')->with('success', 'Profil berhasil diperbarui. Silakan login kembali.');
    }

   
    public function deleteprofilesaya()
    {
        $user = Auth::user();
        $userId = $user->id;
        
        Auth::logout();
        
        // Hapus user dari database
        User::where('id', $userId)->delete();
        
        return redirect()->route('login')->with('success', 'Akun Anda telah dihapus');
    }
}