<?php


class BusinessGnuteca3BusMioloLoginAttempt extends GBusiness
{
    public $attemptid;
    public $login;
    public $datahora;
    public $attempt;

    public function __construct()
    {
        parent::__construct();
        $this->setDb('admin');
    }

    public function getAttempt($login)
    {
        $sql = "SELECT attemptid,
                       login,
                       datahora, 
                       attempt,
                       extract('MINUTES' FROM now()-datahora) as minutos
                  FROM miolo_login_attempt
                 WHERE login = ?";
        $sql = $this->prepare($sql, array($login));
        $query = $this->query($sql, false);

        $attempt = new stdClass();
        $attempt->attemptid = $query[0][0];
        $attempt->login = $query[0][1];
        $attempt->datahora = $query[0][2];
        $attempt->attempt = $query[0][3];
        $attempt->minutos = $query[0][4];

        return $attempt;
    }

    public function setAttempt($login)
    {
        $attempt = $this->getAttempt($login);
        $attempt->login = $login;

        if( strlen($attempt->attemptid) > 0 )
        {
            $sql = "UPDATE miolo_login_attempt SET login = ?, datahora = NOW(), attempt = attempt+1 WHERE attemptid = ?";
            $sql = $this->prepare($sql, array($attempt->login, $attempt->attemptid));
            $execute = $this->execute($sql);
        }
        else
        {
            $sql = "INSERT INTO miolo_login_attempt (login,datahora,attempt) VALUES (?,now(),1)";
            $sql = $this->prepare($sql, array($attempt->login));
            $execute = $this->execute($sql);
        }

        return $execute[0][0] == DB_TRUE;
    }

    public function clearAttempt($login)
    {
        $attempt = $this->getAttempt($login);

        $return = true;
        if( strlen($attempt->attemptid) > 0 )
        {
            $sql = "DELETE FROM miolo_login_attempt WHERE login = ?";
            $sql = $this->prepare($sql, array($login));
            $executeQuery = $this->execute($sql);
            $return &= $executeQuery[0][0] == DB_TRUE;
        }
        return $return;
    }

}