<?php
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_DEPRECATED);
session_start();
if(!file_exists("../config/config.inc.php")) {
    header("Location: ../install/start.php");
}
include_once("../config/languages.inc.php");
$session_id = session_id();
$_SESSION['sml_si_l']=$session_id;
require_once("functions.php");
$settings = get_settings();
if(isset($_GET['lang'])) {
    if(check_language_enabled($_GET['lang'],$settings['languages_enabled'])) {
        $lang = $_GET['lang'];
        $_SESSION['lang']=$lang;
        header("Location: login.php");
        exit;
    }
}
if(empty($_SESSION['lang'])) {
    $browser_lang = detectUserLanguage();
    if(!empty($browser_lang)) {
        $lang = $browser_lang;
    } else {
        $lang = $settings['language'];
    }
} else {
    $lang = $_SESSION['lang'];
}
set_language($lang,$settings['language_domain']);
$style_login = $settings['style_login'];
if(empty($_SESSION['lang'])) {
    $lang = $settings['language'];
} else {
    $lang = $_SESSION['lang'];
}
$_SESSION['theme_color']=$settings['theme_color'];
$autologin = 0;
$remember_me = false;
if (isset($_COOKIE['sml_username']) && isset($_COOKIE['sml_password'])) {
    $username = encrypt_decrypt('decrypt',$_COOKIE['sml_username'],'sml');
    $password = encrypt_decrypt('decrypt',$_COOKIE['sml_password'],'sml');
    if(!empty($username) && !empty($password)) {
        $remember_me = true;
        if(isset($_COOKIE['sml_login'])) {
            $autologin = 1;
        }
    }
} else {
    $username = "";
    $password = "";
}
$verification_code = "";
$email = "";
if(isset($_GET['forgot'])) {
    if(isset($_GET['verification_code'])) {
        $verification_code = $_GET['verification_code'];
    }
    if(isset($_GET['email'])) {
        $email = $_GET['email'];
    }
    $forgot = true;
} else {
    $forgot = false;
}
session_write_close();
switch($_SESSION['lang']) {
    case 'pt_BR':
        $lang_code='pt-BR';
        break;
    case 'pt_PT':
        $lang_code='pt-PT';
        break;
    case 'zh_CN':
        $lang_code='zh-CN';
        break;
    case 'zh_TW':
        $lang_code='zh-TW';
        break;
    case 'zh_HK':
        $lang_code='zh-hk';
        break;
    default:
        $lang_code = substr($_SESSION['lang'], 0, 2);
        break;
}
switch($lang_code) {
    case 'ar':
    case 'he':
    case 'fa':
        $dir = "rtl";
        break;
    default:
        $dir = "ltr";
        break;
}
$redirect = isset($_GET['redirect']) ? $_GET['redirect'] : '';
?>
<!DOCTYPE html>
<html dir="<?php echo $dir; ?>" lang="<?php echo $lang_code; ?>">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
    <meta charset="UTF-8">
    <meta name="description" content="">
    <meta name="author" content="">
    <title><?php echo $settings['name']; ?></title>
    <?php echo print_favicons_backend($settings['logo'],$settings['theme_color']); ?>
    <link href="../viewer/vendor/fontawesome-free/css/all.min.css?v=7.2.0" rel="stylesheet" type="text/css">
    <?php switch ($settings['font_provider']) {
        case 'google': ?>
        <?php if($settings['cookie_consent']) { ?>
        <link rel="preconnect" href="https://fonts.googleapis.com">
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
        <script type="text/plain" data-category="functionality" data-service="Google Fonts">
            (function(d, l, s) {
                const fontName = '<?php echo $settings['font_backend']; ?>';
                            const e = d.createElement(l);
                            e.rel = s;
                            e.type = 'text/css';
                            e.href = `https://fonts.googleapis.com/css2?family=${fontName}`;
                            e.id = 'font_backend_link';
                            d.head.appendChild(e);
                          })(document, 'link', 'stylesheet');
        </script>
    <?php } else { ?>
        <link rel="preconnect" href="https://fonts.googleapis.com">
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
        <link rel='stylesheet' type="text/css" crossorigin="anonymous" id="font_backend_link" href="https://fonts.googleapis.com/css2?family=<?php echo $settings['font_backend']; ?>">
    <?php } ?>
    <?php break;
        case 'collabs': ?>
        <link rel="preconnect" href="https://api.fonts.coollabs.io" crossorigin>
        <link rel="stylesheet" type="text/css" href="https://api.fonts.coollabs.io/css2?family=<?php echo $settings['font_backend']; ?>&display=swap">
        <?php break;
    } ?>
    <?php if($dir=='rtl') : ?>
        <link rel="stylesheet" type="text/css" href="css/sb-admin-2.rtl.min.css?v=3">
    <?php else: ?>
        <link rel="stylesheet" type="text/css" href="css/sb-admin-2.min.css?v=6">
    <?php endif; ?>
    <?php if($settings['cookie_consent']) : ?>
        <link rel="stylesheet" type="text/css" href="vendor/cookieconsent/cookieconsent.min.css?v=3.0.0">
    <?php endif; ?>
    <link rel="stylesheet" type="text/css" href="css/theme.php?v=<?php echo time(); ?>">
    <link rel="stylesheet" type="text/css" href="css/theme_dark.php?v=<?php echo time(); ?>">
    <link rel="stylesheet" type="text/css" href="css/dark_mode.css?v=<?php echo time(); ?>">
    <link rel="stylesheet" href="css/custom.css?v=<?php echo time(); ?>">
    <?php if($dir=='rtl') : ?>
    <link rel="stylesheet" type="text/css" href="css/custom.rtl.css?v=<?php echo time(); ?>">
    <?php endif; ?>
    <?php if(file_exists(__DIR__.DIRECTORY_SEPARATOR.'css'.DIRECTORY_SEPARATOR.'custom_b.css')) : ?>
        <link rel="stylesheet" type="text/css" href="css/custom_b.css?v=<?php echo $v; ?>">
    <?php endif; ?>
</head>

<body class="bg_login <?php echo ($settings['background']!='' && $style_login==2) ? 'bg_image' : 'bg-gradient-primary' ; ?>" style="<?php echo ($settings['background']!='' && $style_login==2) ? 'background-image: url(assets/'.$settings['background'].') !important;'  : '' ; ?>">
<script>
    var dark_mode_setting = <?php echo $settings['dark_mode']; ?>;
    var dark_mode = '0';
    if(dark_mode_setting==1) {
        if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
            dark_mode = '1';
        }
        if (localStorage.getItem("dark_mode") === null) {
            localStorage.setItem("dark_mode",dark_mode);
        } else {
            dark_mode = localStorage.getItem('dark_mode');
        }
        if(dark_mode=='1') document.body.classList.add("dark_mode");
        window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
            dark_mode = e.matches ? '1' : '0';
            if(dark_mode=='1') {
                document.body.classList.add("dark_mode");
                localStorage.setItem("dark_mode",'1');
            } else {
                document.body.classList.remove("dark_mode");
                localStorage.setItem("dark_mode",'0');
            }
        });
    }
</script>
<style>
    *{ font-family: '<?php echo $settings['font_backend']; ?>', sans-serif; }
</style>
<div class="container">
    <div class="row">
        <?php if(!empty($settings['logo'])) { ?>
            <div class="col-md-12 text-white mt-4 text-center">
                <img style="max-height:100px;max-width:200px;width:auto;height:auto" src="assets/<?php echo $settings['logo']; ?>" />
            </div>
        <?php } else { ?>
            <div class="col-md-12 text-white mt-4 text-center title_name_login">
                <h3 class="mb-0"><?php echo strtoupper($settings['name']); ?></h3>
            </div>
        <?php } ?>
    </div>
    <div class="row justify-content-center mt-3">
        <div class="<?php echo ($style_login==1 && $settings['background']!='') ? 'col-xl-10 col-lg-12 col-md-9' : 'col-xl-6 col-lg-8 col-md-9'; ?>" style="<?php echo ($style_login==2) ? 'max-width:540px' : ''; ?>">
            <div class="card o-hidden border-0 shadow-lg my-2 <?php echo ($style_login==2) ? 'glass_effect' : ''; ?>">
                <div class="card-body p-0">
                    <div class="row" style="min-height: 530px;">
                        <div style="<?php echo ($settings['background']!='' && $style_login==1) ? 'background-image: url(assets/'.$settings['background'].');'  : '' ; ?>" class="d-none bg-login-image <?php echo ($style_login==1 && $settings['background']!='') ? 'col-lg-6 d-lg-block' : ''; ?>"></div>
                        <div class="<?php echo ($style_login==1 && $settings['background']!='') ? 'col-lg-6' : 'col-md-12'; ?> pl-0">
                            <div class="p-5">
                                <li class="nav-item dropdown no-arrow lang_switcher_login <?php echo ($style_login==2 || $settings['background']=='') ? 'fix_left_pos_lang_switcher' : ''; ?>">
                                    <a class="nav-link dropdown-toggle" href="#" id="langDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" <?php echo ($settings['languages_count']==1) ? 'style="cursor:default;pointer-events:none;"' : ''; ?> >
                                        <img style="height: 14px;" src="img/flags_lang/<?php echo $lang; ?>.png" />
                                    </a>
                                    <div class="dropdown-menu dropdown-menu-left shadow" aria-labelledby="langDropdown">
                                        <?php if((!check_language_enabled('en_US',$settings['languages_enabled']) && check_language_enabled('en_GB',$settings['languages_enabled'])) || (check_language_enabled('en_US',$settings['languages_enabled']) && !check_language_enabled('en_GB',$settings['languages_enabled']))) {
                                            $languages_list['en_GB']['name'] = "English";
                                            $languages_list['en_US']['name'] = "English";
                                        }
                                        foreach ($languages_list as $lang_code => $lang_data): ?>
                                            <?php if (check_language_enabled($lang_code, $settings['languages_enabled'])): ?>
                                                <span style="cursor: pointer;" onclick="switch_language('<?php echo $lang_code; ?>');" class="<?php echo ($lang == $lang_code) ? 'lang_active' : ''; ?> noselect dropdown-item align-middle">
                                                    <img class="mb-1" src="img/flags_lang/<?php echo $lang_code; ?>.png?v=3" />
                                                    <span class="ml-2"><?php echo $lang_data['name']; ?></span>
                                                </span>
                                            <?php endif; ?>
                                        <?php endforeach; ?>
                                    </div>
                                </li>
                                <div class="text-center">
                                    <h4 id="title_login" class="h4 text-gray-900 mb-0"><?php echo ($forgot) ? _("Forgot Password") : _("Welcome!"); ?></h4>
                                    <p id="description_login" class="mb-3"><?php echo ($forgot) ? _("Change your password here") : _("Login to your account here"); ?></p>
                                </div>
                                <?php if($forgot) { ?>
                                    <form class="user">
                                        <div class="<?php echo (!empty($verification_code)) ? 'disabled' : ''; ?>">
                                            <div class="form-group">
                                                <input tabindex="1" autofocus type="email" class="form-control form-control-user" id="email_f" value="<?php echo $email; ?>" placeholder="<?php echo _("E-mail"); ?>">
                                            </div>
                                            <a tabindex="2" href="#" id="btn_forgot_code" onclick="send_verification_code();return false;" class="btn btn-primary btn-user btn-block">
                                                <?php echo _("Send Verification Code"); ?>
                                            </a>
                                        </div>
                                        <hr>
                                        <div class="form-group">
                                            <input tabindex="3" type="text" class="form-control form-control-user" id="forgot_code" value="<?php echo $verification_code; ?>" placeholder="<?php echo _("Verification code"); ?>">
                                        </div>
                                        <div class="form-group position-relative">
                                            <input tabindex="4" autocomplete="new-password" type="password" class="form-control form-control-user" id="password_f" placeholder="<?php echo _("New password"); ?>">
                                            <i onclick="show_hide_password('password_f');" class="btn_show_hide_passw fa fa-eye-slash" aria-hidden="true"></i>
                                        </div>
                                        <div class="form-group position-relative">
                                            <input tabindex="5" autocomplete="new-password" type="password" class="form-control form-control-user" id="repeat_password_f" placeholder="<?php echo _("Repeat password"); ?>">
                                            <i onclick="show_hide_password('repeat_password_f');" class="btn_show_hide_passw fa fa-eye-slash" aria-hidden="true"></i>
                                        </div>
                                        <a tabindex="6" href="#" id="btn_change_password" onclick="change_password_forgot();return false;" class="btn btn-success btn-user btn-block">
                                            <?php echo _("Change password"); ?>
                                        </a>
                                        <hr>
                                        <div class="text-center">
                                            <a class="small" href="login.php"><?php echo _("Back to Login"); ?></a>
                                        </div>
                                    </form>
                                <?php } else { ?>
                                    <form class="user">
                                        <div class="form-group">
                                            <input tabindex="1" autofocus type="text" class="form-control form-control-user" id="username_l" aria-describedby="emailHelp" value="<?php echo $username; ?>" placeholder="<?php echo _("Username or E-mail"); ?>">
                                        </div>
                                        <div class="form-group position-relative">
                                            <input tabindex="2" type="password" class="form-control form-control-user" id="password_l" value="<?php echo $password; ?>" placeholder="<?php echo _("Password"); ?>">
                                            <i id="btn_show_hide_passw" onclick="show_hide_password('password_l');" class="fa fa-eye-slash" aria-hidden="true"></i>
                                        </div>
                                        <div class="form-group text-center">
                                            <div class="form-check">
                                                <input tabindex="3" type="checkbox" id="remember_l" <?php echo ($remember_me) ? 'checked' : ''; ?>>
                                                <label class="form-check-label" for="remember_l">
                                                    <?php echo _("Remember me"); ?>
                                                </label>
                                            </div>
                                        </div>
                                        <a tabindex="3" href="#" id="btn_login" onclick="login();return false;" class="btn btn-primary btn-user btn-block">
                                            <?php echo _("Login"); ?>
                                        </a>
                                        <?php if($settings['smtp_valid']) : ?>
                                            <div class="text-center mt-3">
                                                <a class="small" href="login.php?forgot=1"><?php echo _("Forgot Password?"); ?></a>
                                            </div>
                                        <?php endif; ?>
                                        <hr>
                                    </form>
                                <?php } ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div id="modal_login_email" class="modal" tabindex="-1" role="dialog" data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><?php echo _("E-mail required"); ?></h5>
            </div>
            <div class="modal-body">
                <p><?php echo _("Please enter your e-mail address to continue."); ?></p>
                <div class="form-group mb-0">
                    <input type="email" class="form-control" id="login_email_required" placeholder="<?php echo _("E-mail"); ?>">
                </div>
            </div>
            <div class="modal-footer">
                <button id="btn_login_email_required" onclick="save_login_email();return false;" type="button" class="btn btn-primary"><?php echo _("Continue"); ?></button>
            </div>
        </div>
    </div>
</div>

<?php require_once("footer_login.php"); ?>

<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="vendor/jquery-easing/jquery.easing.min.js"></script>
<script src="js/sb-admin-2.min.js"></script>
<?php if($settings['cookie_consent']) : ?>
    <script type="text/javascript" src="vendor/cookieconsent/cookieconsent.min.js?v=3.0.0"></script>
<?php endif; ?>
<script src="js/function.js?v=<?php echo time(); ?>"></script>
<script>
    (function($) {
        "use strict"; // Start of use strict
        window.autologin = <?php echo $autologin; ?>;
        window.redirect = '<?php echo $redirect; ?>';
        window.language = '<?php echo $lang; ?>';
        window.login_labels = window.login_labels || {};
        window.login_labels.check_msg = `<?php echo _("Check your inbox for the verification code."); ?>`;
        window.login_labels.password_success = `<?php echo _("Password successfully changed!"); ?>`;
        window.login_labels.error_msg = `<?php echo _("Error, retry later"); ?>`;
        if(autologin==1) {
            login();
        }
        $(document).keyup(function(event) {
            if (event.key == "Enter") {
                event.preventDefault();
                if($('#modal_login_email').is(':visible')) {
                    $("#btn_login_email_required").trigger('click');
                } else if($('#btn_change_password').length) {
                    $("#btn_change_password").trigger('click');
                } else {
                    $("#btn_login").trigger('click');
                }
            }
        });
    })(jQuery); // End of use strict

    function show_hide_password(id) {
        if($('#'+id).attr("type") == "text"){
            $('#'+id).attr('type', 'password');
            $('#'+id).parent().find('i').addClass( "fa-eye-slash" );
            $('#'+id).parent().find('i').removeClass( "fa-eye" );
        }else if($('#'+id).attr("type") == "password"){
            $('#'+id).attr('type', 'text');
            $('#'+id).parent().find('i').removeClass( "fa-eye-slash" );
            $('#'+id).parent().find('i').addClass( "fa-eye" );
        }
    }
</script>
<?php if(!empty($settings['ga_tracking_id'])) : ?>
    <?php if($settings['cookie_consent']) { ?>
        <script type="text/plain" data-category="analytics" data-service="Google Analytics" async src="https://www.googletagmanager.com/gtag/js?id=<?php echo $settings['ga_tracking_id']; ?>"></script>
        <script type="text/plain" data-category="analytics" data-service="Google Analytics">
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '<?php echo $settings['ga_tracking_id']; ?>', {
            'page_title': 'login'
        });
        </script>
    <?php } else { ?>
        <script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo $settings['ga_tracking_id']; ?>"></script>
        <script>
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '<?php echo $settings['ga_tracking_id']; ?>', {
                'page_title': 'login'
            });
        </script>
    <?php } ?>
<?php endif; ?>
<?php if($settings['cookie_consent']) : ?>
    <?php require_once('cookie_consent.php'); ?>
<?php endif; ?>
<script>
    window.addEventListener('load', () => {
        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register('service-worker.js?v=<?php echo time(); ?>', {
                scope: '.'
            });
        }
    });
</script>
</body>
</html>
