<?php $get = ''; foreach($_GET as $key => $value) { $get .= '&'.$key.'='.$value; } if(!isset($main)) { header('Location: index.php?pg='.substr(basename(__FILE__),0,-4).$get); exit; } ?>
<?php
if(isset($_GET['loginHandler'])) {
    $captcha = isset($_POST['captcha']) ? hash('sha512', $main->mysqli->real_escape_string($_POST['captcha'])) : '';
    if($main->checkToken()) {
        if($main->checkCaptcha()) {
            $email = isset($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ? $_POST['email'] : '';
            $password = isset($_POST['password']) ? sha1($_POST['password']) : '';
            if ($stmt = $main->mysqli->prepare('SELECT iduser, fname, lname, clave, admin, estado FROM user WHERE email = ? LIMIT 1')) {
                $stmt->bind_param('s', $email);
                $stmt->execute();
                $stmt->store_result();
                $stmt->bind_result($iduser, $fname, $lname, $clave, $admin, $estado);
                $stmt->fetch();
                if ($stmt->num_rows == 1) {
                    if ($main->checkBrute($iduser, 0)) {
                        $main->header(__FILE__, 'error=Ha hecho mas de 5 intentos de inicio de sesión en los últimos 30 minutos. Debe esperar una hora para ser habilitado de nuevo o intente recuperar su clave.');
                    } else {
                        if (hash_equals($clave, $password)) {
                            if($estado == 1) {
                                $user_browser = $_SERVER['HTTP_USER_AGENT'] . $main->userIp();
                                $_SESSION['iduser'] = (int)$iduser;
                                $_SESSION['email'] = $email;
                                $_SESSION['fname'] = $fname;
                                $_SESSION['lname'] = $lname;
                                $_SESSION['admin'] = (int)$admin;
                                $_SESSION['estado'] = (int)$estado;
                                $_SESSION['stringlogin'] = hash('sha512', $password . $user_browser);
                                $sql = 'INSERT INTO session(iduser, stringlogin) VALUES ("' . $iduser . '", "' . $_SESSION['stringlogin'] . '")';
                                $main->mysqli->query($sql) or exit(__LINE__ . ':' . $main->mysqli->error);
                                $sql = 'SELECT idoferente FROM useroferente WHERE iduser = "' . $iduser . '" LIMIT 1';
                                $query = $main->mysqli->query($sql) or exit(__LINE__ . ':' . $main->mysqli->error);
                                $result = $query->fetch_array();
                                $_SESSION['idoferente'] = isset($result['idoferente']) ? $result['idoferente'] : '';
                                $pg = $_SESSION['idoferente'] != '' ? 'oferente' : '';
                                $_SESSION['app'] = $pg;
                                $main->header($pg, 'success=Inicio de sesión correcto.');
                            } else {
                                $main->header(__FILE__, 'error=Su user ha sido desactivado. Contacte al administrador.');
                            }
                        } else {
                            $main->mysqli->query('INSERT INTO trysession(iduser) VALUES ("' . $iduser . '")') or exit(__LINE__ . ':' . $main->mysqli->error);
                            $main->header(__FILE__, 'error=La clave no es correcta. Intente de nuevo.');
                        }
                    }
                } else {
                    $main->header(__FILE__, 'error=El correo electrónico no esta registrado.');
                }
            } else {
                exit(__LINE__ . ':' . $main->mysqli->error);
            }
        }
    }
    $main->header(__FILE__, '');
} ?>
<?php echo $main->formOpen(__FILE__, 'loginHandler'); ?>
<div class="box-radius login-form">
    <h1>Iniciar sesión</h1>
    <p>Por favor ingrese su usuario y clave.</p>
    <div class="form-group">
        <div class="form-input">
            <?php echo $main->input(array('span' => 'Correo electrónico', 'name' => 'email', 'type' => 'email', 'required' => true)); ?>
        </div>
    </div>
    <div class="form-group">
        <div class="form-input">
            <?php echo $main->input(array('span' => 'Contraseña', 'name' => 'password', 'type' => 'password', 'required' => true)); ?>
        </div>
    </div>
    <div class="form-group">
        <div class="form-input text-center">
            <img id="captcha_image" src="captcha/captcha.php?rand=<?php rand(); ?>'">
            <br />
            <a href="javascript:refreshCaptcha();" class="label_captcha">Cambiar imagen</a>
            <br />
            <input name="captcha" class="input" type="text" placeholder="Codigo de imagen" required>
        </div>
    </div>
    <div class="form-group">
        <div class="form-input text-center">
            <input type="submit" class="btn success" value="Iniciar sesión">
        </div>
    </div>
    <div class="form-group">
        <div class="form-input text-center">
            <a href="recover-password.php">¿Olvidó su clave?</a>
            <br />
            <a href="index.php">Volver</a>
        </div>
    </div>
</div>
<?php echo $main->formClose(); ?>