<?php

namespace App\Controllers;


use App\Models\UserModel;
use App\Models\UserRoleModel;

class User extends BaseController
{
    public function index()
    {
        $model = new UserModel();
        $userRolesModel = new UserRoleModel();

        $data['users'] = $model
            ->select('user.*, user_role.id AS user_role_id, user_role.name AS user_role_name, user_role.code AS user_role_code')
            ->join('user_role', 'user_role.id = user.user_role_id')
            ->whereIn('user.status', [1, 2])
            ->orderBy('user.created_datetime', 'DESC')
            ->findAll();
        $data['userroles'] = $userRolesModel->whereIn('status', [1])->orderBy('created_datetime', 'DESC')->findAll();

        return view('user', $data);
    }

    public function save()
    { 
        $model = new UserModel();

        $result = $model->save([
            'first_name'     => $this->request->getPost('first_name'),
            'last_name'      => $this->request->getPost('last_name'),
            'username'        => $this->request->getPost('username'),
            'contact_no_1'   => $this->request->getPost('contact_no_1'),
            'contact_no_2'   => $this->request->getPost('contact_no_2'),
            'password'        => password_hash($this->request->getPost('password'),PASSWORD_DEFAULT),
            'user_role_id'  => $this->request->getPost('user_role_id'),
            'email'          => strtolower($this->request->getPost('email')),
            'status'         => $this->request->getPost('status')
        ]);

        if ($result) {
            session()->setFlashdata(
                'success',
                'User saved successfully.'
            );
        } else {
            session()->setFlashdata(
                'error',
                'Lesson to save User.'
            );
        }

        return redirect()->to('/user');
    }

    public function get($id)
    {
        $model = new UserModel();

        $data = $model->find($id);

        return $this->response->setJSON($data);
    }

    public function update()
    {
        $model = new UserModel();

        $id = $this->request->getPost('updid');

        $result = $model->update($id, [
            'first_name'    => $this->request->getPost('updfirst_name'),
            'last_name'     => $this->request->getPost('updlast_name'),
            'username'       => $this->request->getPost('updusername'),
            'contact_no_1'  => $this->request->getPost('updcontact_no_1'),
            'contact_no_2'  => $this->request->getPost('updcontact_no_2'),
            'password' => $this->request->getPost('updpassword'),
            'email'         => strtolower($this->request->getPost('updemail')),
            'user_role_id'  => $this->request->getPost('upduser_role_id'),
            'status'        => $this->request->getPost('updstatus'),
        ]);

        if ($result) {
            session()->setFlashdata(
                'success',
                'User updated successfully.'
            );
        } else {
            session()->setFlashdata(
                'error',
                'Unable to update User.'
            );
        }

        return redirect()->to('/user');
    }

    public function delete()
    {
        $model = new UserModel();

        $id = $this->request->getPost('delid');

        $result = $model->update($id, [
            'status' => 3
        ]);

        if ($result) {
            session()->setFlashdata(
                'success',
                'User deleted successfully.'
            );
        } else {
            session()->setFlashdata(
                'error',
                'Student to delete User.'
            );
        }

        return redirect()->to('/user');
    }

    public function authenticate()
    {
        $userModel = new UserModel();

        $username = $this->request->getPost('username');
        $password = $this->request->getPost('password');

        $user = $userModel
            ->where('username', $username)
            ->where('status', 1)
            ->first();

        if (!$user) {
            //return redirect()->back()->with('error', 'Invalid username');
            return redirect()->to('/login')->with('error', 'Invalid username or password');
        }
        if (!password_verify($password, $user['password'])) {
            //return redirect()->back()->with('error', 'Invalid password');
            return redirect()->to('/login')->with('error', 'Invalid username or password');
        }
        session()->set([
            'user_id'      => $user['id'],
            'username'     => $user['username'],
            'full_name'    => $user['first_name'] . ' ' . $user['last_name'],
            'user_role_id' => $user['user_role_id'],
            'logged_in'    => true
        ]);
        return redirect()->to('/dashboard');
    }

    public function login()
    {

        return view('login');
    }
}