<?php
  // Configura los datos de tu cuenta
$pdo = new PDO("mysql:host=localhost;dbname=livedire_thomson;","livedire_thomson","kikila123");

  $username = $_POST['username'];
 // $password_sha1 = sha1($_POST['password']);
 $password_sha1 = $_POST['password'];

  $sql  = "SELECT user ";
  $sql .= "FROM users ";
  $sql .= "WHERE user=:u AND password=:p";
  $stmt = $pdo->prepare($sql);
  $stmt->execute(array(
            ":u"=>$username,
            ":p"=>$password_sha1
          ));
  $row = $stmt->fetch();

  // clear out any existing session that may exist
  session_start();
  session_destroy();
  session_start();

  if ($row) {
    $userIp = $_SERVER['REMOTE_ADDR'];
    $sql = "INSERT INTO historia(fechahora,user,direccion) VALUES (NOW(), :u, :p)";
                                          
    $stmt = $pdo->prepare($sql);
                                                  
    try{            	                  
    $stmt->execute(array(
            ":u"=>$username,
            ":p"=>$userIp
          ));
     } catch(PDOException $e)
  {
  // echo "Error " . $e->getMessage();

  }
    $_SESSION['signed_in'] = true;
    $_SESSION['username'] = $username;
    header("Location: home.php");
  } else {
    $_SESSION['flash_error'] = "Usuario o contraseña no válidos.";
    $_SESSION['signed_in'] = false;
    $_SESSION['username'] = null;
    header("Location: login.php");
  }
?>