<?php

namespace App\Http\Controllers\Admins;

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

class ProfileController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        // Call view Dashboard
        $profile = Auth::user();
        return view('pages.admins.profile', ['profile' => $profile]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request)
    {
        // get profile
        $user = Auth::user();
        $profile = User::findOrFail($user->id);

        //validate form
        $request->validate([
            'nik'  => 'required|min:16|max:16',
            'name'     => 'required|min:5',
            'oldPassword'   => 'required|min:8',
            'newPassword'   => 'required|min:8',
            'gender'  => 'required',
            'place_of_birth'  => 'required',
            'date_of_birth'  => 'required',
        ]);

        if (Hash::check($request->oldPassword, $user->password)) {
            $profile->update([
                'nik' => $request->nik,
                'name'     => $request->name,
                'password'   => bcrypt($request->newPassword),
                'gender' => $request->gender,
                'place_of_birth' => $request->place_of_birth,
                'date_of_birth' => $request->date_of_birth,
            ]);

            // Create Session message
            Session::flash('profile-message', [
                'type' => 'success',
                'msg' => 'Anda berhasil mengupdate data diri!'
            ]);
        } else {
            // Create Session message
            Session::flash('profile-message', [
                'type' => 'warning',
                'msg' => 'Password yang anda masukkan salah!'
            ]);
            return redirect()->route('profile.index');
        }

        //redirect to profile
        return redirect()->route('profile.index')->with(['success' => 'Data Berhasil Diubah!']);
    }
}
