<?php

namespace App\Controllers\Shield;

use CodeIgniter\API\ResponseTrait;
use CodeIgniter\Shield\Controllers\LoginController as ShieldLogin;
use Jumbojett\OpenIDConnectClient;
use App\Models\Admin\UsersModel;
use CodeIgniter\Shield\Authentication\Authentication;

class LoginController extends ShieldLogin
{
    use ResponseTrait;

    public function __construct()
    {
        $this->ImgModel = model('App\Models\Admin\ImgModel');
    }

    protected $helpers = ['form', 'fungsi'];
    
    
    /**
     * Displays the form the login to the site.
     *
     * @return RedirectResponse|string
     */
    public function loginView()
    {
        if (auth()->loggedIn()) {
            return redirect()->to(config('Auth')->loginRedirect());
        }

        /** @var Session $authenticator */
        $authenticator = auth('session')->getAuthenticator();

        // If an action has been defined, start it up.
        if ($authenticator->hasAction()) {
            return redirect()->route('auth-action-show');
        }

        return $this->view(setting('Auth.views')['login'], [
            'action'   => base_url('login'),
            'email'    => '',
            'password' => '',
            'logo' => base_url('pegadaian.svg'),
        ]);
    }

    /**
     * Attempts to log the user in.
     */
    public function loginActionAjax()
    {
        header('Content-Type: application/json');

        // Validate here first, since some things,
        // like the password, can only be validated properly here.
        $rules = $this->getValidationRules();

        if (! $this->validateData($this->request->getPost(), $rules, [], config('Auth')->DBGroup)) {
            return $this->fail($this->validator->getErrors(), 400);
        }

        /** @var array $credentials */
        $credentials             = $this->request->getPost(setting('Auth.validFields')) ?? [];
        $credentials             = array_filter($credentials);
        $credentials['password'] = $this->request->getPost('password');
        $remember                = (bool) $this->request->getPost('remember');

        /** @var Session $authenticator */
        $authenticator = auth('session')->getAuthenticator();

        // Attempt to login
        $result = $authenticator->remember($remember)->attempt($credentials);
        if (! $result->isOK()) {
            return $this->fail($result->reason(), 400);
        }

        // If an action has been defined for login, start it up.
        if ($authenticator->hasAction()) {
            return $this->respond(['message' => 'auth/a/show']);
        }

        return $this->respond(['message' => config('Auth')->loginRedirect()]);
    }
}