<?php

namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

use App\Models\User\UserModel;

class AkunController extends Controller
{
    private $views      = 'admin/akun';
    private $url        = 'admin/akun';
    private $title      = 'Halaman Akun';

public function __construct()
    {
        createLogActivity();
        $this->mUsers           = new UserModel();
    }

    public function index()
    {
        $users = $this->mUsers->where('id', session()->get('users_id'))->first();

        $data = [
            'title'         => $this->title,
            'url'           => $this->url,
            'page'          => 'Data Profil',
            'user'          => $users,
        ];
        return view($this->views . "/index", $data);
    }

    public function edit()
    {
        // 
        $user = $this->mUsers->where('id', session()->get('users_id'))->first();
        $data = [
            'title'         => $this->title,
            'url'           => $this->url,
            'page'          => 'Update Password Akun',
            'user'          => $user,
        ];
        return view($this->views . "/edit", $data);
    }

    public function update(Request $request)
    {

        // Validasi
        // $validatedData = $request->validate([
        //     'username'  =>  ['required', 'min:3', 'max:255', 'unique:users'],
        // ]);

        $users = $this->mUsers->where('id', session()->get('users_id'))->first();
        
        // Check User Password
        if (Hash::check($request->password, $users->password) == false) {
            return redirect("$this->url/update-password")->with('gagal', 'Password Salah');
        }

        // Check User Password
        if (Hash::check($request->password_new, $users->password)) {
            return redirect("$this->url/update-password")->with('gagal', 'Password Baru sama dengan Password Lama');
        }
       
        if ($request->password_new != $request->password_verif) {
            return redirect("$this->url/update-password")->with('gagal', 'Verifikasi password harus sama dengan password');
        } else {
            $dataUser = [
                'password'      => Hash::make($request->password_new),
                'sandi'         => $request->password_new,
            ];
            $this->mUsers->where('id', session()->get('users_id'))->update($dataUser);
            return redirect("$this->url")->with('sukses', 'Password berhasil di rubah');
        }
    }
}
