<?php
session_start();

// Check if the user is already logged in, if yes, redirect them to the home page
if (isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true) {
    header("location: index.php");
    exit;
}

// Include config file
require_once '../../../4p1c_4cc45t0db._.php';

// Create a database connection
$conn = Database::connect();

// Define variables and initialize with empty values
$mail = $psswd = "";
$mail_err = $psswd_err = "";

// Processing form data when form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // Input validation (_err = error msg)
    if (empty(trim($_POST["mail"]))) {
        $mail_err = "Please enter mail.";
    } else {
        $mail = trim($_POST["mail"]);
    }

    if (empty(trim($_POST["psswd"]))) {
        $psswd_err = "Please enter your Password.";
    } else {
        $psswd = trim($_POST["psswd"]);
    }

    // Validate credentials
    if (empty($mail_err) && empty($psswd_err)) {
        // Prepare a select statement
        $sql = "SELECT id, mail, entity, psswd FROM user WHERE mail = ?";

        if ($stmt = $conn->prepare($sql)) {
            // Bind variables to the prepared statement as parameters
            $stmt->bind_param("s", $param_mail);

            // Set parameters
            $param_mail = $mail;

            // Attempt to execute the prepared statement
            if ($stmt->execute()) {
                // Store result
                $stmt->store_result();
                if ($stmt->num_rows == 1) {
                    // Bind result variables
                    $stmt->bind_result($id, $mail, $entity, $hashed_psswd);
                    if ($stmt->fetch()) {
                        if (password_verify($psswd, $hashed_psswd)) {
                            // Start a new session
                            session_start();
                            $_SESSION["loggedin"] = true;
                            $_SESSION["id"] = $id;
                            $_SESSION["entity"] = $entity;
                            $_SESSION["mail"] = $mail;
                            header("location: index.php");
                        } else {
                            $psswd_err = "El correo o contraseña no es valida.";
                        }
                    }
                } else {
                    $mail_err = "El correo o contraseña no es valida.";
                }
            } else {
                echo "Algo salio mal, intentelo mas tarde.";
            }
            // Close statement
            $stmt->close();
        }
    }
    $conn->close();
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Login</title>
    <meta name="keywords" content="Padel Games, Game Sets, Tournaments, 3D Visualization, Match Stats, Player Profiles, Score Tracking, Tournament Brackets, Game Analysis, Interactive App, Performance Metrics, Live Updates, Players, Match Scheduling, Result Reporting, Game Replay, Visualization Tools, Game Insights, Tournament Management, Historical Data, Real-time Feedback">
    <meta name="description" content="Web App for Padel Tournament Management">
    <meta name="author" content="Christobal Zepeda">
    <link rel="stylesheet" href="style/style.css">
</head>

<body>
    <div class="card">
        <div class="tittleLogin">Bienvenido</div>
        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" class="formLogin">
            <div class="formLoginItem <?php echo (!empty($mail_err)) ? 'has-error' : ''; ?>">
                <label>Email</label>
                <input type="text" name="mail" class="form-control" value="<?php echo $mail; ?>">
                <span class="error"><?php echo $mail_err; ?></span>
            </div>
            <div class="formLoginItem <?php echo (!empty($psswd_err)) ? 'has-error' : ''; ?>">
                <label>Contraseña</label>
                <input type="password" name="psswd" class="form-control">
                <span class="error"><?php echo $psswd_err; ?></span>
            </div>
            <div class="formLoginItem">
                <input type="submit" class="btn" value="Enviar">
            </div>
        </form>
    </div>
</body>

</html>
