<?php
$r = "";
require_once($r."inc/funciones.php");
$error=$_GET['error'];
validSession($r);
if (isset($_POST["entrar"])) {
    $mysqli = connectDB($r);
    $correo = trim($_POST["correo"]);
    $contrasena = $_POST["contrasena"];

    // Preparar y ejecutar la consulta para obtener el usuario
    $stmt = $mysqli->prepare("SELECT * FROM z_usuarios WHERE correo = ? ORDER BY id DESC LIMIT 1");
    $stmt->bind_param('s', $correo);
    $stmt->execute();
    $result = $stmt->get_result();
    $num1 = $result->num_rows;

    if ($num1 > 0) {
        $row1 = $result->fetch_assoc();

        // Verificar la contraseña usando SHA-1
        if ($row1["contraseña"] === sha1($contrasena)) {
            if ($row1["eliminado"] == 0) {
                if ($row1["estado"] != 1) {
                    if (empty($_SESSION["userid"])) {
                        $_SESSION['userid'] = $row1["id"];
                        $_SESSION['nombre'] = $row1["nombre"];
                        $_SESSION['perfil'] = $row1["tipo"];
                        $ahora = time();

                        // Actualizar última conexión
                        $stmt = $mysqli->prepare("UPDATE z_usuarios SET ultima = ? WHERE id = ?");
                        $stmt->bind_param('ii', $ahora, $_SESSION['userid']);
                        $stmt->execute();

                        // Registrar acceso
                        $stmt = $mysqli->prepare("INSERT INTO z_accesos (correo, fecha) VALUES (?, ?)");
                        $stmt->bind_param('si', $correo, $ahora);
                        $stmt->execute();

                        if ($row1["cpass"] == '1') {
                            exit(header("Location:" . $r . "cpass.php?id=user"));
                        } else {
                            if (isset($_SESSION["redirect_after_login"])) {
                                $redirectPath = $_SESSION["redirect_after_login"];
                                unset($_SESSION["redirect_after_login"]);
                                header("Location: " . $redirectPath);
                            } else {
                                header("Location: " . $r . "dashboard.php");
                            }
                            exit();
                        }
                    } else {
                        exit(header("Location:" . $r . "logout.php"));
                    }
                } else {
                    $error = "Usuario inactivo!!";
                }
            } else {
                $error = "Este usuario ha sido Eliminado!!";
            }
        } else {
            $error = "Contraseña incorrecta!!";
        }
    } else {
        $error = "Usuario no existe!!";
    }
}

?><!DOCTYPE html>
<html lang="es">

<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  
  <meta name="theme-color" content="#a49f9b"/>
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">
  <title>INICIO DE SESSION - QUIMIFOREN</title>
  <!-- Bootstrap core CSS-->
  <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <!-- Custom fonts for this template-->
  <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
  <link href="vendor/sweet/sweetalert.css" rel="stylesheet">
  <!-- Custom styles for this template-->
  <link href="css/sb-admin.css" rel="stylesheet">
  <style>
      @media (min-width: 992px){
    .container {
        max-width: 540px;
    }
}
      @media (min-width: 768px){
    .container {
        max-width: 540px;
    }
}
@media (min-width: 540px){
    .container {
        max-width: 450px;
    }
}
  </style>
</head>

<body  style="background-image:url(http://www.bird-wittenbergdental.com/wp-content/uploads/2017/01/top-line-management-login-background-1.jpg);background-position-x: center;background-size: cover;">
  <div class="container" >
    <div class="card card-login mx-auto mt-5">
      <div class="card-header text-center" style="background:#53585d;"><img src="/img/logo-quimiforen-header.png" width="120px"><h3>INGRESAR</h3><p>Le damos la bienvenida a Quimiforen por favor ingrese sus datos</p></div>
      <div class="card-body text-center">
        <form id="login" name="login" action="index.php" method="post"  style="padding: 18px 10%;">
          <div class="form-group">
            <label for="correo">Correo Electronico</label>
            <input class="form-control" name="correo" type="email" aria-describedby="correo" placeholder="Correo Electronico">
          </div>
          <div class="form-group">
            <label for="contrasena">Contraseña</label>
            <input class="form-control" name="contrasena" type="password" placeholder="Contraseña" required>
          </div>
          <div class="form-group">
            <div class="form-check">
              <label class="form-check-label">
                <input class="form-check-input" type="checkbox">Recordarme</label>
            </div>
          </div>
          <button type="submit" class="btn btn-dark btn-block" name="entrar" value="entrar">INGRESAR</button>
        </form>
        <? if($error!=''){ echo '<hr/><div class="alert alert-danger alert-dismissible"><a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>'.$error.'</div>';} ?>
        <hr/>
        <div class="text-center">
            <p>Tenga en cuenta: Esta Web utiliza cookies para su correcto funcionamiento.</p>
          <a class="btn btn-link btn-sm"  onclick="pass('Contáctese con el administrador para que le asigne una nueva clave')">Olvide mi Contraseña</a>
        </div>
      </div>
    </div>
  </div>
  <!-- Bootstrap core JavaScript-->
  <script src="vendor/jquery/jquery.min.js"></script>
  <script src="js/form.js"></script>
  <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <!-- Core plugin JavaScript-->
  <script src="vendor/jquery-easing/jquery.easing.min.js"></script>
  <script src="vendor/sweet/sweetalert.js"></script>
  <script>
      function pass(text,tipo){
          swal(text);
      }
  </script>
</body>

</html>
