<?php
namespace App\Controllers\Backend;

use App\Controllers\BaseController;
use App\Models\AdminModel;

class ProfileController extends BaseController
{
    
    public function index()
    {
        $data['pageTitle'] = lang('Admin/Profile.pageTitle');
        return view('backend/profile/index', $data);
    }

    
    public function updatePassword()
    {
        $adminId = session()->get('user_id');
        
        $rules = [
            'current_password'      => 'required',
            'new_password'          => 'required|min_length[8]',
            'confirm_new_password'  => 'required|matches[new_password]',
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $adminModel = new AdminModel();
        $admin = $adminModel->find($adminId);

        if (!password_verify($this->request->getPost('current_password'), $admin->password)) {
            return redirect()->back()->with('error', lang('Admin/Profile.errorCurrentPass'));
        }

        $success = $adminModel->update($adminId, [
            'password' => $this->request->getPost('new_password')
        ]);

        if ($success) {
            return redirect()->to(route_to('admin.profile.show'))->with('success', lang('Admin/Profile.updateSuccess'));
        }
        
        return redirect()->back()->with('error', lang('Admin/Profile.updateFailed'));
    }
}