<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\ProfileRequest;
use App\Http\Requests\UpdateUserRequest;
use Illuminate\Support\Facades\Auth;

class ProfileController extends Controller
{
    // Tampilkan profil admin
    public function adminprofile()
    {
        $user = Auth::user()->load('role');
        return view('admin.profile', compact('user'));
    }

    // Update profil (nama, email, no_telp, password jika diisi)
    public function update(UpdateUserRequest $request)
    {
        $data = $request->validated();

        // Jika password tidak diisi, hapus dari array
        if (empty($data['password'])) {
            unset($data['password']);
        }

        Auth::user()->update($data);

        return back()->with('success', 'Profil berhasil diperbarui tanpa hash password!');
    }

    // Ganti password secara langsung tanpa hash
    public function password(Request $request)
    {
        $request->validate([
            'current_password' => ['required'],
            'password'         => ['required', 'min:6', 'confirmed'],
        ]);

        // Verifikasi password lama (plain comparison, bukan hash)
        if ($request->current_password !== Auth::user()->password) {
            return back()->withErrors(['current_password' => 'Password lama salah.']);
        }

        // Simpan password baru langsung tanpa hash
        Auth::user()->update([
            'password' => $request->password,
        ]);

        return back()->with('success', 'Password berhasil diubah tanpa hash!');
    }


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

    // Update data profil (termasuk password tanpa hash)
    public function userupdate(ProfileRequest $request)
{
    $data = $request->validated();   // sudah berisi role_id = 2
    // jika password kosong, hapus
    if (empty($data['password'])) unset($data['password']);

    Auth::user()->update($data);

    return back()->with('success', 'Profile updated!');
}


    // Update password terpisah tanpa hash, dan validasi password lama juga tanpa hash
    public function userpassword(Request $request)
    {
        $user = Auth::user();

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

        // Cek password lama sesuai input tanpa hash
        if ($request->current_password !== $user->password) {
            return back()->withErrors(['current_password' => 'Current password is incorrect']);
        }

        // Simpan password baru tanpa hash
        $user->password = $request->password;
        $user->save();

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