<?php
ob_start();
//ini_set('display_errors', 1);
//ini_set('display_startup_errors', 1);
//error_reporting(E_ALL);

session_start();
require_once("functions.php");

$show_popup = false;
$error_message = "";
$active_sessions = 0;

// se l'utente ha già effettuato l'accesso, reindirizzalo alla pagina home
if (isset($_SESSION["DAST-SERVER"]['info_utente_logged'])) {
    header("Location: home.php");
    exit;
}

// se l'utente ha inviato il modulo di accesso
if (isset($_POST["username"]) && !empty($_POST["username"]) && isset($_POST["password"]) && !empty($_POST["password"])) {
    $username = $_POST["username"];
    $password = $_POST["password"];
    $ip_address = $_SERVER['REMOTE_ADDR'];

    // cerca l'utente nel database
    $array_login = array('username' => $username, 'password' => $password);
    $sql_login = "SELECT * FROM clienti WHERE username = :username AND password = :password AND stato = 1 LIMIT 1";
    list($status_login, $contenuto_login, $nrows_login) = read_db_pdo($sql_login, $array_login);

    // se le credenziali di accesso dell'utente sono corrette
    if ($nrows_login == 1) {
        $id_utente = (int) $contenuto_login[0]["id_cliente"];
        if ($id_utente < 1) {
            $errori_input[] = "KO1";
            exit;
        }

        $user_logged = $contenuto_login[0]["username"];
        if ($user_logged != $username) {
            $errori_input[] = "KO2";
            exit;
        }

        $stato = $contenuto_login[0]["stato"];
        if ($stato == 0) {
            $errori_input[] = "KO2000";
            exit;
        }

        // Controlla il numero di sessioni attive per l'utente
        $sql_check_sessions = "SELECT COUNT(*) as active_sessions FROM sessioni_utente WHERE id_cliente = :id_cliente AND session_id != 'OFF'";
        $array_check_sessions = array('id_cliente' => $id_utente);
        list($status_check_sessions, $contenuto_check_sessions, $nrows_check_sessions) = read_db_pdo($sql_check_sessions, $array_check_sessions);

        $active_sessions = $contenuto_check_sessions[0]["active_sessions"] ?? 0;

        if ($active_sessions >= 2) {
            $show_popup = true;
        } else {

            // salva le informazioni dell'utente nella sessione
            $oggi = date("d-m-Y");
            $server = $_SERVER['SERVER_NAME'];
            $info_utente_logged = array("username" => $user_logged, "id_utente" => $id_utente, "data" => $oggi);
            $_SESSION["DAST-SERVER"]["hash_info_utente_logged"] = md5($user_logged . $oggi . $server);
            $_SESSION["DAST-SERVER"]['info_utente_logged'] = $info_utente_logged;

            // se l'utente ha selezionato la casella di controllo "Ricordami"
            if (isset($_POST['remember_me']) && $_POST['remember_me'] == 1) {
                $scadenza = $contenuto_login[0]["scadenza"];

                $scadenza_timestamp = strtotime($scadenza);
                // salva l'ID dell'utente e la passwordcrittografata in un cookie sicuro
                $password_crittografata = password_hash($password, PASSWORD_DEFAULT);
                setcookie('Authication', $username . '-----' . $password, time() + (86400 * 365), '/', '', true, true);
            }

            // reindirizza l'utente alla pagina home
            header("Location: home.php");
            exit;
        }

    } else {
        // Gestione dei login falliti
        $n_tentativi_login = check_admin_failed_login();
        if ($nrows_login != 1) {
            if ($n_tentativi_login < 15) {
                $show_popup = true;
                $error_message = "Credenziali non corrette o scadute. Riprova.";
            } else {
                $show_popup = true;
                $error_message = "Hai superato il numero massimo di tentativi. Contatta l'amministratore.";
            }
        }
    }

    if (!empty($errori_input)) {
        foreach ($errori_input as $errore) {
            echo $errore . "\n";
        }
        exit;
    }
}

// se l'utente effettua manualmente il logout
if (isset($_GET['logout']) && $_GET['logout'] == 1) {
    // cancella il cookie "remember_me"
    setcookie('remember_me', '', time() - 3600, '/', '', true, true);
    // distruggi la sessione
    session_destroy();
    $_SESSION = array();
    //reindirizza l'utente alla pagina di accesso
    header("Location: index_smart.php");
    exit;
}

$temp_auth = explode("-----", $_COOKIE["Authication"]);
$username = $temp_auth[0];
$password = $temp_auth[1];
ob_end_flush();
?>


<!doctype html>
<html lang="it">
<head>
    <title>NOW - Login</title>
    <link rel="stylesheet" href="./front-end-files/css/bootstrap-italia.min.css" />
    <link rel="stylesheet" href="./front-end-files/css/stile.css" />
    <script src="./front-end-files/js/bootstrap-italia.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <link rel="icon" type="image/png" href="./images/now_icon.png" />
    <script>window.__PUBLIC_PATH__ = 'fonts'</script>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <link rel="icon" type="image/png" href="./images/now_icon.png" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.3/font/bootstrap-icons.css">
    <style>
        .login {
            position: absolute;
            top: 50%;
            left: 50%;
            margin-right: -50%;
            transform: translate(-50%, -50%);
            background: #00000;
            padding: 50px;
            border-radius: 40px;
            min-width: 40%;
            max-width: 80%;
            color: #FFF;
        }
        footer {
            position: absolute;
            bottom: 0;
            width: 100%;
        }

        footer p {
            position: relative;
            margin-top: 10px;
            text-align: center;
            color: white;
        }

        body {
            height: 100vh;
            overflow: hidden;
            filter: drop-shadow(0 0 10px white);
            background-color: #000000;
        }
@keyframes shadowGlow {
    0% {
        filter: drop-shadow(0 0 10px #ff00ff);
    }
    25% {
        filter: drop-shadow(0 0 10px #00ffff);
    }
    50% {
        filter: drop-shadow(0 0 10px #ff1493);
    }
    75% {
        filter: drop-shadow(0 0 10px #8a2be2);
    }
    100% {
        filter: drop-shadow(0 0 10px #ff00ff);
    }
}

body {
    height: 100vh;
    overflow: hidden;
    animation: shadowGlow 8s ease infinite;
    background-color: #000000;
}
        .form-group {
            position: relative;
            margin-bottom: 1rem;
            margin-top: 10px;
        }

        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.7);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }

        .modal-content {
            background: #000000;
            border-radius: 10px;
            padding: 20px;
            color: #FFF;
            text-align: center;
            max-width: 500px;
            width: 80%;
        }

        .my-confirm-button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .my-confirm-button:hover {
            background-color: #0056b3;
        }

        .error-modal-content {
            background: #b22222;
            border-radius: 10px;
            padding: 20px;
            color: #FFF;
            text-align: center;
            max-width: 500px;
            width: 80%;
        }
        @keyframes gradientFlow {
            0% {
                background-position: 0% 50%;
                box-shadow: 0 0 20px rgba(255, 0, 255, 0.6);
            }
            25% {
                box-shadow: 0 0 20px rgba(0, 255, 255, 0.6);
            }
            50% {
                background-position: 100% 50%;
                box-shadow: 0 0 20px rgba(255, 0, 128, 0.6);
            }
            75% {
                box-shadow: 0 0 20px rgba(128, 0, 255, 0.6);
            }
            100% {
                background-position: 0% 50%;
                box-shadow: 0 0 20px rgba(255, 0, 255, 0.6);
            }
        }

        .modern-button {
            background: linear-gradient(
                90deg,
                #ff00ff,
                #00ffff,
                #ff1493,
                #8a2be2,
                #ff00ff
            );
            background-size: 300% 100%;
            color: white !important;
            width: 100%;
            cursor: pointer;
            font-family: "Arial Black", sans-serif;
            border: none;
            padding: 12px;
            border-radius: 8px;
            animation: gradientFlow 8s ease infinite;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
            font-size: 16px;
            letter-spacing: 1px;
            text-transform: uppercase;
            font-weight: bold;
            margin-top: 25px;
        }

        .modern-button::before {
            content: '';
            position: absolute;
            top: -2px;
            left: -2px;
            right: -2px;
            bottom: -2px;
            z-index: -1;
            background: linear-gradient(
                90deg,
                #ff00ff,
                #00ffff,
                #ff1493,
                #8a2be2,
                #ff00ff
            );
            background-size: 300% 100%;
            animation: gradientFlow 8s ease infinite;
            filter: blur(10px);
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .modern-button:hover::before {
            opacity: 1;
        }

        .modern-button:hover {
            transform: translateY(-2px);
            letter-spacing: 2px;
        }

        .modern-button:active {
            transform: translateY(1px);
        }

        /* Stili input con effetto moderno */
        .form-control {
            background: rgba(255, 255, 255, 0.1) !important;
            border: 1px solid rgba(255, 255, 255, 0.2) !important;
            color: white !important;
            transition: all 0.3s ease;
        }

        .form-control:focus {
            background: rgba(255, 255, 255, 0.15) !important;
            border-color: rgba(255, 255, 255, 0.3) !important;
            box-shadow: 0 0 15px rgba(255, 255, 255, 0.1) !important;
        }

        .form-control::placeholder {
            color: rgba(255, 255, 255, 0.6) !important;
        }

        body {
            height: 100vh;
            overflow: hidden;
            background-color: #000000;
        }

        .form-group {
            position: relative;
            margin-bottom: 1.5rem;
        }

        .form-check-input {
            background-color: rgba(255, 255, 255, 0.1);
            border-color: rgba(255, 255, 255, 0.2);
        }

        .form-check-input:checked {
            background-color: #ff00ff;
            border-color: #ff00ff;
        }

        .login {
            background: rgba(0, 0, 0);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.1);
        }
    </style>
</head>

<body style="background-color: #000000;">
    <div class="login">
        <div style="text-align: center;margin-bottom: 30px;">
            <img src="./images/impulse.svg" alt="logo" width="300" height="200" style="margin-top: 5px; margin-left: -45px;">
        </div>
        <div class="login__form">
            <form method="post" action="index_smart.php">
                <div class="form-group">
                    <input type="text" class="form-control" id="user" name="username" value="<?php echo $username; ?>" placeholder="USERNAME" required>
                </div>
                <div class="form-group">
                    <input type="password" class="form-control" id="password" name="password"  value="<?php echo $password; ?>" placeholder="PASSWORD" required>
                    <?php if (isset($errori_input) && in_array("KO100", $errori_input)): ?>
                            <small class="form-text text-danger">Credenziali non corrette</small>
                        <?php endif; ?>
                        <div class="alert alert-fill-danger" role="alert" id="error_login" style="display:none">
                            <i class="mdi mdi-alert-circle"></i>ERRORE! Dati non validi
                </div>
                <input type="submit" class="btn modern-button" value="ACCEDI" name="submit" id="submit">
                <div class="form-check mt-3">
                    <input type="checkbox" class="form-check-input" id="remember" name="remember_me" value="1">
                    <label class="form-check-label" for="remember" style="color:#FFF;">RICORDAMI</label>
                </div>
            </form>
        </div>
    </div>
     <script>
        document.addEventListener('DOMContentLoaded', function () {
            <?php if ($show_popup && $active_sessions >= 2) { ?>
                // Mostra il modal per il limite di sessioni
                const overlay = document.createElement('div');
                overlay.className = 'modal-overlay';

                const modalContent = document.createElement('div');
                modalContent.className = 'modal-content';
                modalContent.innerHTML = `
                    <h3>Attenzione!</h3>
                    <p>Hai raggiunto il limite massimo di sessioni attive. Chiudi una sessione e non fare il furbo.</p>
                    <button class="btn my-confirm-button">Torna al Login</button>
                `;

                overlay.appendChild(modalContent);
                document.body.appendChild(overlay);

                overlay.style.display = 'flex';

                modalContent.querySelector('.my-confirm-button').onclick = function () {
                    window.location.href = "index.php";
                };

                overlay.onclick = function (e) {
                    if (e.target === overlay) {
                        overlay.style.display = 'none';
                        document.body.removeChild(overlay);
                    }
                };
            <?php } elseif ($show_popup) { ?>
                // Mostra il modal per l'errore di login
                const overlayError = document.createElement('div');
                overlayError.className = 'modal-overlay';

                const modalContentError = document.createElement('div');
                modalContentError.className = 'modal-content error-modal-content';
                modalContentError.innerHTML = `
                    <h3>Errore di Accesso</h3>
                    <p><?php echo htmlspecialchars($error_message); ?></p>
                    <button class="btn my-confirm-button">Chiudi</button>
                `;

                overlayError.appendChild(modalContentError);
                document.body.appendChild(overlayError);

                overlayError.style.display = 'flex';

                modalContentError.querySelector('.my-confirm-button').onclick = function () {
                    overlayError.style.display = 'none';
                    document.body.removeChild(overlayError);
                };

                overlayError.onclick = function (e) {
                    if (e.target === overlayError) {
                        overlayError.style.display = 'none';
                        document.body.removeChild(overlayError);
                    }
                };
            <?php } ?>
        });
        </script>
</body>
</html>