<?php
namespace App\Controllers;

class Profile extends BaseController
{
    public function index()
    {
        return view('profile/index', $this->viewData(['title'=>'My Profile']));
    }

    public function update()
    {
        $id = session()->get('user_id');
        $this->db->table('users')->where('id',$id)->update([
            'name'  => esc($this->request->getPost('name')),
            'phone' => esc($this->request->getPost('phone')),
        ]);
        session()->set('user_name', esc($this->request->getPost('name')));
        return redirect()->to(base_url('profile'))->with('success','Profile updated.');
    }

    public function changePassword()
    {
        $id   = session()->get('user_id');
        $user = $this->db->table('users')->where('id',$id)->get()->getRowArray();
        if (!password_verify($this->request->getPost('current_password'), $user['password'])) {
            return redirect()->back()->with('error','Current password is incorrect.');
        }
        $new = $this->request->getPost('new_password');
        $con = $this->request->getPost('confirm_password');
        if ($new !== $con) return redirect()->back()->with('error','New passwords do not match.');
        if (strlen($new) < 8) return redirect()->back()->with('error','Password must be at least 8 characters.');
        $this->db->table('users')->where('id',$id)->update(['password'=>password_hash($new, PASSWORD_BCRYPT)]);
        return redirect()->to(base_url('profile'))->with('success','Password changed successfully.');
    }
}
