<?php session_start();
    require "connect.php";
    if (isset($_SESSION['user_id'])) {
        echo "<script>window.location.href = '../dashboard/index.php'</script>";
    }

    if (isset($_POST['login'])) {
      $email = $_POST['email'];
      $password = $_POST['password'];

        $sql = "SELECT * FROM users WHERE email = '$email' AND id != 1";
        $result = $connection->query($sql);
        while ($row = $result->fetch_assoc()) {
            $db_email = $row['email'];
            $db_password = $row['password'];
            $user_id = $row['user_id'];
        }

        if (empty($email) || empty($password)) {
          $error = '<div class="alert alert-danger d-flex align-items-center" role="alert">
            Please enter email and password to login
          </div>';
        }else if ($email != $db_email OR $password != $db_password) {
          $error = '<div class="alert alert-danger d-flex align-items-center" role="alert">
            Incorrect email or password. Please try again.
          </div>';
        }else if ($email == $db_email && $password == $db_password) {
          $error = "<div class='alert alert-success d-flex align-items-center' role='alert'>
            Login Successful, Redirecting...
          </div>
          <script>
          setTimeout(() => {
              window.location.href = 'session.php?id=$user_id'
          }, 1500);
          </script>";
        }else {
            $err_msg = 'error';
        }
    }
?>
