<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator; // <--- WAJIB ADA INI
use App\Models\User;

class ProfilController extends Controller
{
    public function index()
    {
        $user = Auth::user();
        return view('admin.profil', compact('user'));
    }

    // 1. UPDATE INFO DASAR (Tas Error: 'updateProfil')
    public function update(Request $request)
    {
        $user = User::find(Auth::id());

        // Aturan Validasi
        $validator = Validator::make($request->all(), [
            'nama'     => 'required|string|max:100',
            // Pastikan ignore ID user yang benar (id_user atau id)
            'username' => 'required|string|alpha_num|max:50|unique:users,username,' . $user->id_user . ',id_user',
            'email'    => 'required|email|max:255|unique:users,email,' . $user->id_user . ',id_user',
            'no_wa'    => 'nullable|numeric',
            'alamat'   => 'nullable|string|max:255',
        ], [
            'required' => 'Kolom :attribute wajib diisi.',
            'unique'   => ':attribute sudah digunakan.',
            'numeric'  => ':attribute harus berupa angka.',
        ], [
            'nama' => 'Nama Lengkap',
            'no_wa' => 'Nomor WA'
        ]);

        // CEK ERROR KHUSUS TAS 'updateProfil'
        if ($validator->fails()) {
            // Kita lempar error ke tas 'updateProfil'
            return back()->withErrors($validator, 'updateProfil')->withInput();
        }

        // Simpan Data
        $user->nama = $request->nama;
        $user->username = $request->username;
        $user->email = $request->email;
        $user->no_wa = $request->no_wa;
        $user->alamat = $request->alamat;
        $user->save();

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

    // 2. UPDATE PASSWORD (Tas Error: 'updatePassword')
    public function updatePassword(Request $request)
    {
        // Aturan Validasi
        $validator = Validator::make($request->all(), [
            'password' => 'required|min:8|confirmed', // confirmed cek field password_confirmation
        ], [
            'required'  => 'Kata sandi baru wajib diisi.',
            'min'       => 'Kata sandi minimal :min karakter.',
            'confirmed' => 'Konfirmasi kata sandi tidak cocok.',
        ]);

        if ($validator->fails()) {
            // Tambahkan ->withInput()
            return back()->withErrors($validator, 'updatePassword')->withInput();
        }

        // Simpan Password
        $user = User::find(Auth::id());
        $user->password = Hash::make($request->password);
        $user->save();

        return back()->with('success', 'Kata sandi berhasil diubah!');
    }
}
