<?php
namespace App\Controllers;

use CodeIgniter\API\ResponseTrait;
use CodeIgniter\Shield\Entities\User;

class Login extends BaseController
{
    use ResponseTrait;

    public function index()
    {
        if (auth()->loggedIn()) {
            return redirect()->to('home');
        }

        return view('pages/login');
    }

    public function vlogin()
    {
        if (auth()->loggedIn())
        {
            return $this->fail(['message'=>'error'],400,null,'error');
        }

        $data = array();
        $data['status'] = 'success';
        
        helper(['form']);
        
        $request = [
            'email' => $this->request->getPost('username',FILTER_SANITIZE_ADD_SLASHES),
            'password' => $this->request->getPost('password',FILTER_SANITIZE_ADD_SLASHES)
        ];

        $loginAttempt = auth()->attempt($request);
        if (! $loginAttempt->isOK()) {
            return $this->fail($loginAttempt->reason(),400,null,'error');
        }else{
            return $this->respond(['message'=>'success'],200);
        }
    }

    public function create_user()
    {
        $users = model('UserModel');
        $tuser = model('UserModela');
        $user = new User([
            'username' => 'admin',
            'email'    => 'admin',
            'password' => '12345678',
        ]);

        $users->save($user);
        $user = $users->findById($users->getInsertID());
        $tuser->setLevel($users->getInsertID(), 'admin');
        $user->syncGroups('admin');
        $users->activate($user);
    }

    public function create_admin()
    {
        $users = model('UserModel');
        $tuser = model('UserModela');
        $user = new User([
            'username' => 'admin',
            'email'    => 'admin',
            'password' => '12345678',
        ]);

        $users->save($user);
        $user = $users->findById($users->getInsertID());
        $tuser->setLevel($users->getInsertID(), 'admin');
        $user->syncGroups('admin');
        $users->activate($user);
    }

    public function logout()
    {
        auth()->logout();
        return $this->respond(['message'=>'success'],200);
    }
}
?>