<?php
$title = 'Войти на сайт';
require ($_SERVER['DOCUMENT_ROOT'].'/core/sys.php');
require($_SERVER['DOCUMENT_ROOT'].'/core/head.php');
if(isset($user['id'])){
header('Location: /');
exit;
}
if(isset($_POST['email'])){
$email = htmlspecialchars(trim($_POST['email']));
$password = htmlspecialchars(trim($_POST['password']));
$us = $db->prepare('SELECT * FROM `users` WHERE `email` = ?');
$us -> execute([$email]);
$us = $us -> fetch(PDO :: FETCH_ASSOC);

if(empty($_POST['captcha'])) $msg = 'Введите код с картинки!';
elseif(empty($email)) $msg = 'Введите e-mail';
elseif(empty($password)) $msg = 'Введите пароль';
elseif(!preg_match('/[0-9a-z_\-]+@[0-9a-z_\-^\.]+\.[a-z]{2,6}/i' , $email)) $msg = 'Неверный формат e-mail';
elseif(!isset($us['id'])) $msg = 'Неверный email';
elseif($us['password'] != md5($password)) $msg = 'Неверный пароль';
elseif($_SESSION['Captcha.Code'] != $_POST['captcha']) $msg = ('Неверный код с картинки!');

if(isset($msg)){
    /*Если есть ошибки*/
if(isset($us['id'])){
$add_men_all = $db->prepare('INSERT INTO `history_logs` SET `us` = ?,`err` = ?,`who` = ?,`ip` = ?, `soft` = ?,`time` = ?');
$add_men_all -> execute([$us['id'],1,1,htmlspecialchars($_SERVER['REMOTE_ADDR']),htmlspecialchars($_SERVER['HTTP_USER_AGENT']),time()]);
}
$_SESSION['message'] = $msg;
exit(header('Location: /auth.aspx'));
}else{
$add_men_all = $db->prepare('INSERT INTO `history_logs` SET `us` = ?,`err` = ?,`who` = ?,`ip` = ?, `soft` = ?,`time` = ?');
$add_men_all -> execute([$us['id'],0,1,htmlspecialchars($_SERVER['REMOTE_ADDR']),htmlspecialchars($_SERVER['HTTP_USER_AGENT']),time()]);
setcookie('id', $crypt->crypt($us['id']), time()+86400*365, '/');
setcookie('password', $crypt->crypt(md5($password)), time()+86400*365, '/');
setcookie('token', $crypt->crypt(htmlspecialchars($_SERVER['REMOTE_ADDR']).':'.$us['name']), time()+86400*365, '/');
$_SESSION['time'] = time();
header('Location: /');
exit;
}
}
?>
<div class="container">
  <div class="row mt-5">
  <div class="col-md-6 offset-md-3">
<div class="card">
      <div class="card-body">
<form action="" method="POST">
<h3>E-mail :</h3> <br /><input type="email" placeholder="Введите E-Mail" name="email"><br>
<h3>Пароль :</h3> <br /><input type="password" placeholder="Введите пароль" name="password"><br> 

<h3>Код с картинки : </h3><br />
<img src="/design/kcaptcha/kcaptcha.php" title="Нажмите для обновления" onclick="this.setAttribute('src','/design/kcaptcha/kcaptcha.php?hash='+Math.random());var captcha=document.getElementById('captcha');if(captcha){captcha.focus()}">
<br />
<input name="captcha" class="form-control" type="text" /><br />
<div class="row">
            <div class="col-md-6">
              <a class="btn btn-info" href="/moduls/recovery.php">Забыли пароль?</a><br>
            </div>

<div class="col-md-6 text-right">
<button type="submit" class="btn btn-success">Авторизация</button>
</div></div>
</form></div></div></div></div></div>
<?
require($_SERVER['DOCUMENT_ROOT'].'/core/foot.php');