<?php

include_once("../include/dbconnect.inc.php");
include_once("../include/global.inc.php");
//include_once("../include/caglobal.inc.php");
include_once ("../include/email.inc.php");

session_start();

getLanguage(__FILE__);

$multipleAccounts = false;
$accountsList = null;
// $currentClientIP = trim($_SERVER['HTTP_X_FORWARDED_FOR']);
$currentClientIP = mcArrTrim($_SERVER, "HTTP_X_FORWARDED_FOR");
if ($currentClientIP == "") :
   // $currentClientIP = trim($_SERVER['REMOTE_ADDR']);
   $currentClientIP = mcArrTrim($_SERVER, "REMOTE_ADDR");
endif;

// Check for "forgot password"
$parLoginForgotPasswordEnabled = getParameterValue("0", "LOGIN_FORGOT_PASSWORD_ENABLED", "0", "0");
if ($parLoginForgotPasswordEnabled == "1") :
   list($f_act, $f_chk_account) = getHttpVars(array('f_act', 'f_chk_account'));
   if ($f_act == "pwdForgotten" && $f_chk_account != "") :
      // Get email from user
      $usrId = getFieldValueFromId("user","usr_account",$f_chk_account,"usr_id");      
      if ($usrId != "") :
         $usrEmail = getFieldValueFromId("user","usr_id",$usrId,"usr_email");
         if ($usrEmail != "") :
            // Change password
            $newPwd = chr(rand(65,90)) . chr(rand(97,122)) . chr(rand(65,90)) . chr(rand(97,122)) . rand(0,9) . rand(0,9) . rand(0,9) . rand(0,9);
            $sqlStmtPwd = "UPDATE user SET usr_password = PASSWORD('" . $newPwd . "'), usr_password_modify = NOW(), usr_password_old = '' WHERE usr_id = '" . $usrId . "'";
            $res = $db->exec($sqlStmtPwd);
            if ($db->connect_errno) : die (); endif;
            if ($db->affected_rows > 0) :
               $usrName = getFieldValueFromId("user","usr_id",$usrId,"usr_name");
               $usrFirstname = getFieldValueFromId("user","usr_id",$usrId,"usr_firstname");
               $usrHqId = getFieldValueFromId("user","usr_id",$usrId,"hq_id");
               $mailFrom = getParameterValue("0", "MAIL_SENDER_ADDRESS", $usrHqId);
               $mailTo = $usrEmail;
               $mailBcc = "support@assecutor.de";
               $mailSubject = getParameterValue("0", "MAIL_SUBJECT_PREFIX", "0", "0") . "Passwort vergessen";
               $mailMode = "html";
               if ($mailMode == "html") :
                  $mailText = "Hallo <b>" . $usrFirstname . " " . $usrName . "</b></br></br>soeben wurde f�r Ihr Konto <b>\"" . $f_chk_account 
                            . "\"</b> auf https://" . $_SERVER['SERVER_NAME']
                            . " das folgende Einmalpasswort erzeugt:</br></br>"
                            . "<b>" . $newPwd . "</b>"
                            . "</br></br>Sollte diese Nachfrage nicht von Ihnen stammen, handelt es sich m�glicherweise um eine nicht autorisierte Anfrage."
                            . "</br></br>Diese Nachricht wurde automatisch erzeugt und dient nur als Hinweis, bitte antworten Sie nicht darauf.";
               else :
                  $mailText = "Hallo" . $usrFirstname . " " . $usrName . ",\n\nsoeben wurde f�r Ihr Konto \"" . $f_chk_account 
                            . "\" auf https://" . $_SERVER['SERVER_NAME']
                            . " das folgende Einmalpasswort erzeugt:\n\n"
                            . $newPwd
                            . "\n\nSollte diese Nachfrage nicht von Ihnen stammen, handelt es sich m�glicherweise um eine nicht autorisierte Anfrage."
                            . "\n\nDiese Nachricht wurde automatisch erzeugt und dient nur als Hinweis, bitte antworten Sie nicht darauf.";
               endif;

               $mailLogContent = $currentClientIP . " | " . $mailMode . " | " . $mailSubject . " | " . $usrFirstname . " " . $usrName . " | " . $f_chk_account . " | " . $newPwd;
               sendExternalMail($mailText, $mailSubject, $mailTo, $mailFrom, $mailCc, $mailBcc, $mailMode, $mailLogContent);
            else :
               $statusMessage = getLngt("Der Vorgang hat leider nicht geklappt! Bitte versuchen Sie es noch einmal oder wenden sich ggfs. an die zust�ndige Niederlassung!");
            endif;
         else :
            $statusMessage = getLngt("Es wurde leider keine E-Mail-Adresse gefunden! Bitte wenden Sie sich ggfs. an die zust�ndige Niederlassung!");
         endif;
      else :
         $statusMessage = getLngt("Der angegebene Benutzername wurde leider nicht gefunden! Bitte wenden Sie sich ggfs. an die zust�ndige Niederlassung!");
      endif;
   endif;
endif;

$pageTitel = getLngt("ANMELDUNG");
$usr_id = -1;
include_once ("../admin/menu.php");
include_once ("../include/html.inc.php");
getCurrentScript(__FILE__);

$constMaxLoginTrials = getParameterValue("0", "MAXIMUM_LOGIN_TRIALS", "0", "0");
$loginTrials = checkClientLoginTrials();
if ($loginTrials == 20) :
   $conf = prepareSendMailPear("smtp.1und1.com","admin@assecutor.de","a7=!wURsT","admin@assecutor.de","ALERT: CHECK FOR BOT-ATTACK !!!","Assecutor","admin@assecutor.de","ALERT: CHECK FOR BOT-ATTACK !!!) (IP=".$currentClientIP.", account=".$f_chk_account.")");
   $mail_object =& Mail::factory("smtp", $conf[0]);
   $mail_object->send($conf[1], $conf[2], $conf[3]);
endif;
if ($loginTrials == $constMaxLoginTrials) :
   $conf = prepareSendMailPear("smtp.1und1.com","admin@assecutor.de","a7=!wURsT","admin@assecutor.de","ALERT: SYSTEM ACCESS DENIED - BOT-ATTACK !!! (IP=".$currentClientIP.", account=".$f_chk_account.")",
     "Assecutor","admin@assecutor.de","ALERT: SYSTEM ACCESS DENIED - BOT-ATTACK !!!) ");
   $mail_object =& Mail::factory("smtp", $conf[0]);
   $mail_object->send($conf[1], $conf[2], $conf[3]);
endif;
if ($loginTrials > $constMaxLoginTrials) :
    // Referer
    header("Location: ../admin/accessdenied.php");    
endif;

if (substr(phpversion(), 0, 1) >= "5") :
    if (isset($_SESSION['state']) && !isset($_SESSION['sso_error']) && isset($_SESSION['sso']) && !isset($_SESSION['usr_id']) && !isset($_SESSION['hq_id'])):
        $statusMessage = checkSSOLogin();
    // Wenn login ok, dann gelangt das Script nicht an diese Stelle (exit in checkLogin())!
    // list($f_chk_account) = getHttpVars(array('f_chk_account'));
    elseif (isset($_SESSION['state']) && isset($_SESSION['sso_error'])) :
        $statusMessage = getLngt($_SESSION['sso_error']);
        unset($_SESSION['sso_error']);
    elseif (!isset($_SESSION['usr_id']) && !isset($_SESSION['hq_id'])):
     $statusMessage = checkLogin();
     // Wenn login ok, dann gelangt das Script nicht an diese Stelle (exit in checkLogin())!
     list($f_chk_account) = getHttpVars(array('f_chk_account'));
   else:
       if(isset($_SESSION['sso'])) {
           header("Location: ../admin/start.php");
           exit();
       } else {
           // $randomCryptionNumber = $HTTP_SESSION_VARS["randomCryptionNumber"];
           $randomCryptionNumber = $_SESSION["randomCryptionNumber"];
           // header("Location: ../admin/menu_fs.php?p=" . ec("1"));

           $usrTotpSecretCurrent = getFieldValueFromId("user", "usr_id", $_SESSION['usr_id'], "usr_totp_secret");
           $usrTotpActivated = getFieldValueFromId("user", "usr_id", $_SESSION['usr_id'], "usr_totp_activated");
           if ($usrTotpSecretCurrent == "" || $usrTotpActivated != "1") :
               // 2-FA has to be activated
               header("Location: ../admin/start.php");
           else :
               // 2-FA is activated and codes have to be checked
               header("Location: ../admin/GA_verification.php");
           endif;
       }
    endif;
else :
   if (!isset($HTTP_SESSION_VARS['usr_id']) && !isset($HTTP_SESSION_VARS['hq_id'])):
     $statusMessage = checkLogin();
     // Wenn login ok, dann gelangt das Script nicht an diese Stelle (exit in checkLogin())!
     list($f_chk_account) = getHttpVars(array('f_chk_account'));
   else:
       if(isset($_SESSION['sso'])) {
           header("Location: ../admin/start.php");
           exit();
       } else {
           // $randomCryptionNumber = $HTTP_SESSION_VARS["randomCryptionNumber"];
           $randomCryptionNumber = $HTTP_SESSION_VARS["randomCryptionNumber"];
           // header("Location: ../admin/menu_fs.php?p=" . ec("1"));

           $usrTotpSecretCurrent = getFieldValueFromId("user", "usr_id", $_SESSION['usr_id'], "usr_totp_secret");
           if (isset($_SESSION['sso']) || $usrTotpSecretCurrent == "") :
               // 2-FA has to be activated
               header("Location: ../admin/start.php");
           else :
               // 2-FA is activated and codes have to be checked
               header("Location: ../admin/GA_verification.php");
           endif;
       }
   endif;
endif;

//function checkSSOLogin() {
//    global $PHP_SELF, $HTTP_SESSION_VARS, $_SESSION, $hq_id, $usr_id, $emp_id, $db, $dbname, $multipleAccounts, $accountsList;
//
//    // Wurde bereits ein Account ausgewählt?
////    if (isset($_POST['sso_selected_account'])) {
////        $_SESSION['selected_account'] = $_POST['sso_selected_account'];
////    }
//
//    if (isset($_POST['sso_selected_account'])) {
//        $_SESSION['selected_account'] = $_POST['sso_selected_account'];
//        // WICHTIG: Nach dem Setzen der Session-Variable MUSS die Seite neu geladen werden,
//        // um den Login-Prozess mit dem nun bekannten Account fortzusetzen.
//        // Das Formular POST war erfolgreich, jetzt redirecten.
//        header("Location: $PHP_SELF");
//        exit();
//    }
//
//    $usr_email = $_SESSION['sso'];
//
//    if ($usr_email != ''):
//        $sqlquery = "
//            SELECT usr.usr_id, usr.hq_id, usr.usr_account
//            FROM user AS usr
//            JOIN headquarters AS hq ON usr.hq_id = hq.hq_id
//            WHERE usr.usr_email = '$usr_email'
//        ";
//
//        $result = $db->dbQ($sqlquery);
//        if (DB::isError($result)) die("$PHP_SELF: [$sqlquery] " . $result->getMessage());
//
//        $accounts = [];
//        while ($row = $result->fetch_assoc()) {
//            $accounts[] = $row;
//        }
//        $result->free();
//
//        if (count($accounts) > 1 && !isset($_SESSION['selected_account'])) {
//            $multipleAccounts = true;
//            $accountsList = $accounts;
////            showAccountSelectionModal($accounts);
////            exit();
//        }
//
//        if (isset($_SESSION['selected_account'])) {
//            foreach ($accounts as $acc) {
//                if ($acc['usr_account'] == $_SESSION['selected_account']) {
//                    $usr_id = $acc["usr_id"];
//                    $hq_id = $acc["hq_id"];
//                    $usr_account = $acc["usr_account"];
//                }
//            }
//            unset($_SESSION['selected_account']);
//        }
//
//        elseif (count($accounts) === 1) {
//            $usr_id      = $accounts[0]["usr_id"];
//            $hq_id       = $accounts[0]["hq_id"];
//            $usr_account = $accounts[0]["usr_account"];
//        }
//        else {
//            unset($_SESSION['sso']);
//            return "Benutzer $usr_email im System nicht gefunden.";
//        }
//
//        $emp_id = getOneStmt(
//                "SELECT emp.emp_id FROM employee AS emp, user AS usr
//             WHERE emp.usr_id = $usr_id
//             AND usr.usr_account = '$usr_account'
//             AND usr.hq_id = $hq_id
//             AND usr.usr_email = '$usr_email'",
//                "emp_id"
//        );
//
//        $_SESSION['usr_id'] = $usr_id;
//        $_SESSION['hq_id']  = $hq_id;
//        $_SESSION['emp_id'] = $emp_id;
//        $_SESSION['dbname'] = $dbname;
//        $_SESSION["chgpwd"] = "1";
//
//        unset($_SESSION['sso']);
//
//        header("Location: $PHP_SELF");
//        exit();
//    endif;
//}

function checkSSOLogin() {
    global $PHP_SELF, $HTTP_SESSION_VARS, $_SESSION, $hq_id, $usr_id, $emp_id, $db, $dbname, $multipleAccounts, $accountsList;

    // 1. POST VERARBEITUNG
    // Wenn ein Account ausgewählt wurde, speichern wir ihn und machen einen Reload (Redirect),
    // damit die Seite sauber mit der Auswahl neu lädt.
    if (isset($_POST['sso_selected_account'])) {
        $_SESSION['selected_account'] = $_POST['sso_selected_account'];
        // WICHTIG: Hier neu laden, damit wir aus dem POST-Modus rauskommen
        header("Location: $PHP_SELF");
        exit();
    }

    $usr_email = $_SESSION['sso'];

    if ($usr_email != ''):
        $sqlquery = "
            SELECT usr.usr_id, usr.hq_id, usr.usr_account 
            FROM user AS usr
            JOIN headquarters AS hq ON usr.hq_id = hq.hq_id
            WHERE usr.usr_email = '$usr_email'
        ";

        $result = $db->dbQ($sqlquery);
        if (DB::isError($result)) die("$PHP_SELF: [$sqlquery] " . $result->getMessage());

        $accounts = [];
        while ($row = $result->fetch_assoc()) {
            $accounts[] = $row;
        }
        $result->free();

        // 2. PRÜFUNG: MUSS MODAL ANGEZEIGT WERDEN?
        if (count($accounts) > 1 && !isset($_SESSION['selected_account'])) {
            $multipleAccounts = true;
            $accountsList = $accounts;

            // WICHTIG: Hier abbrechen!
            // Wir dürfen nicht weiterlaufen, da wir noch keine User-ID haben.
            // Das Skript läuft nun weiter im HTML und zeigt das Modal an.
            return;
        }

        // 3. ACCOUNT ZUWEISUNG (wenn Auswahl getroffen oder nur 1 Account)
        if (isset($_SESSION['selected_account'])) {
            foreach ($accounts as $acc) {
                if ($acc['usr_account'] == $_SESSION['selected_account']) {
                    $usr_id = $acc["usr_id"];
                    $hq_id = $acc["hq_id"];
                    $usr_account = $acc["usr_account"];
                }
            }
            // Auswahl wieder löschen, damit man beim nächsten Mal nicht festhängt
            unset($_SESSION['selected_account']);

        } elseif (count($accounts) === 1) {
            $usr_id      = $accounts[0]["usr_id"];
            $hq_id       = $accounts[0]["hq_id"];
            $usr_account = $accounts[0]["usr_account"];
        } else {
            // Fallback: Session löschen wenn kein Account passt
            unset($_SESSION['sso']);
            return "Benutzer $usr_email im System nicht gefunden.";
        }

        // Ab hier haben wir sicher eine $usr_id

        $emp_id = getOneStmt(
                "SELECT emp.emp_id FROM employee AS emp, user AS usr
             WHERE emp.usr_id = $usr_id 
             AND usr.usr_account = '$usr_account'
             AND usr.hq_id = $hq_id
             AND usr.usr_email = '$usr_email'",
                "emp_id"
        );

        $_SESSION['usr_id'] = $usr_id;
        $_SESSION['hq_id']  = $hq_id;
        $_SESSION['emp_id'] = $emp_id;
        $_SESSION['dbname'] = $dbname;
        $_SESSION["chgpwd"] = "1";

//        unset($_SESSION['sso']);

        header("Location: $PHP_SELF");
        exit();
    endif;
}

function showAccountSelectionModal($accounts) {
    echo '
    <html>
    <head>
        <title>Account auswählen</title>
        <style>
            body { font-family: Arial; background:#f3f3f3; }
            .modal {
                width: 400px; margin: 100px auto; padding: 20px;
                background: white; border-radius: 10px;
                box-shadow: 0 0 15px rgba(0,0,0,0.2);
                text-align:center;
            }
            select, button {
                width: 90%; padding: 10px; margin-top: 15px;
                font-size: 16px;
            }
            button {
                background:#007bff; color:white; border:none;
                border-radius:8px; cursor:pointer;
            }
            button:hover {
                background:#0056b3;
            }
        </style>
    </head>
    <body>
    <div class="modal">
        <h2>Bitte Account ausw&auml;hlen</h2>
        <form method="POST">
            <select name="sso_selected_account">
    ';

    foreach ($accounts as $acc) {
        echo '<option value="'.$acc['usr_account'].'">'.$acc['usr_account'].'</option>';
    }

    echo '
            </select>
            <button type="submit">Weiter</button>
        </form>
    </div>
    </body>
    </html>
    ';
}

// Login-Formular
function checkLogin()
{
  global $PHP_SELF, $HTTP_SESSION_VARS, $_SESSION, $hq_id, $usr_id, $emp_id, $db, $dbname, $currentClientIP;

  list($f_submit, $f_chk_account, $f_chk_password, $statusMessage, $deviceIsKnown) =
    getHttpVars(array('f_submit', 'f_chk_account', 'f_chk_password', 'statusMessage', 'deviceIsKnown'));
  if ($f_submit == getLngt("Anmelden")):

    $f_chk_account = str_replace("'", "\'", $f_chk_account);
    $f_chk_password = str_replace("'", "\'", $f_chk_password);
    $sessionVars = authenticate($f_chk_account, $f_chk_password, $statusMessage);
    $usr_id = $sessionVars[0];
    $hq_id = $sessionVars[1];
    $emp_id = $sessionVars[2];
    if ($usr_id != "" && is_numeric($usr_id) && $usr_id > "0") :
       $randomCryptionNumber = ($usr_id + 1234);
    else :
       $randomCryptionNumber = rand(1,10000);
    endif;
    if ($usr_id != ''):
      // Return-Wert ist ungleich '', name/pass ist g�ltig
      if (phpversion() < '4.1.0'):
        // bis auschl. PHP 4.1.0.
        session_register("usr_id","hq_id","emp_id");
        $HTTP_SESSION_VARS["usr_id"] = $usr_id;
        $HTTP_SESSION_VARS["hq_id"] = $hq_id;
        $HTTP_SESSION_VARS["emp_id"] = $emp_id;
        $HTTP_SESSION_VARS["dbname"] = $dbname;
        $HTTP_SESSION_VARS["randomCryptionNumber"] = $randomCryptionNumber;
        $HTTP_SESSION_VARS["chgpwd"] = "1";
      else:
        // ab einschl. PHP 4.1.0.
        $_SESSION['usr_id'] = $usr_id;
        $_SESSION['hq_id'] = $hq_id;
        $_SESSION['emp_id'] = $emp_id;
        $_SESSION['dbname'] = $dbname;
        $_SESSION['randomCryptionNumber'] = $randomCryptionNumber;
        $_SESSION["chgpwd"] = "1";
      endif;
      if ($deviceIsKnown != "1" && getParameterValue("0", "LOGIN_CHECK_DEVICE", "0", "0") == "1"):
        $usrFreeDevice = getOneStmt("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'usr' AND gdc_obj_id = " . $usr_id . " AND gdc_gen_fieldname = 'usr_free_device'", "gdc_content");
        $usr_account = getOneStmt("SELECT usr_account FROM user AS usr WHERE usr_id = " . $usr_id, "usr_account");
        if ($usrFreeDevice != "1"):
          insertStmt("genericdatacontainer", array("gdc_obj_type", "usr", "gdc_obj_id", $usr_id, "gdc_gen_fieldname", "usr_free_device", "gdc_content", "1", "gdc_context", date("Y-m-d H:i:s")));
          myWriteLog(
            "usr_free_device = '1' was set:\n" .
            "\$usr_id = " . $usr_id . ", \$usr_account = [" . $usr_account . "], \$_SERVER['HTTP_USER_AGENT'] = [" . $_SERVER['HTTP_USER_AGENT'] . "], \$_SERVER['REMOTE_ADDR'] = [" . $currentClientIP . "]"
          );
        else:
          $usr_email = getOneStmt("SELECT usr_email FROM user AS usr WHERE usr_id = " . $usr_id, "usr_email");
//          $browser = get_browser(null, true);
          if ($usr_email != ""):
            include_once("../include/email/htmlMimeMail.php");
            $usr_firstname = getOneStmt("SELECT usr_firstname FROM user AS usr WHERE usr_id = " . $usr_id, "usr_firstname");
            $usr_name = getOneStmt("SELECT usr_name FROM user AS usr WHERE usr_id = " . $usr_id, "usr_name");        
            $mailObj = new htmlMimeMail();
            $mailObj->setFrom(getParameterValue("0", "MAIL_SENDER_ADDRESS", $hq_id));
            $mailObj->setBcc("ca@assecutor.de");
            $parMailSubjectPrefix = trim(getParameterValue("0", "MAIL_SUBJECT_PREFIX", "0", "0"));
            $mailObj->setSubject($parMailSubjectPrefix . " Anmeldung von einem unbekannten Ger�t");
            $mailObj->setText("Hallo " . $usr_firstname . ' ' . $usr_name . ",\n\n". 'soeben hat sich jemand mit Ihrem Konto "' . $usr_account .
              '" auf https://' . $_SERVER['SERVER_NAME'] .
              " von einem bisher unbekannten Ger�t angemeldet:\n\n" .
              $_SERVER['HTTP_USER_AGENT'] .
//              $browser["browser"] . " " . $browser["platform"] .
              "\n\nSollte diese Anmeldung nicht von Ihnen stammen, handelt es sich m�glicherweise um einen nicht autorisierten Login." .
              "\n\nDiese Mail wurde automatisch erzeugt und dient nur als Hinweis, bitte antworten Sie nicht darauf."
            );
            $mailResult = $mailObj->send(array($usr_email), 'smtp');
//            $mailResult = $mailObj->send(array("ca@assecutor.de"), 'smtp');
            myWriteLog(
              "Warningmail was sent from <" . getParameterValue("0", "MAIL_SENDER_ADDRESS", $hq_id) . "> to <" . $usr_email . ">:\n" .
              "\$usr_id = " . $usr_id . ", \$usr_account = [" . $usr_account . "], \$_SERVER['HTTP_USER_AGENT'] = [" . $_SERVER['HTTP_USER_AGENT'] . "], \$_SERVER['REMOTE_ADDR'] = [" . $currentClientIP . "]"
            );
          else:
            myWriteLog(
              "Warningmail could not be sent because no mail-address available:\n" .
              "\$usr_id = " . $usr_id . ", \$usr_account = [" . $usr_account . "], \$_SERVER['HTTP_USER_AGENT'] = [" . $_SERVER['HTTP_USER_AGENT'] . "], \$_SERVER['REMOTE_ADDR'] = [" . $currentClientIP . "]"
            );
          endif;
        endif;
      endif;
      header("Location: $PHP_SELF");
      exit();
    endif;
  elseif ($f_submit == 'Registrieren'):
    header("Location: register.php");
  endif;
  return $statusMessage;
}

function myWriteLog($log_text) {
  $log_file_name = "../log/login_" . date("Ym") . ".log";

  $fileHandle = @fopen($log_file_name, 'a');
  @fwrite($fileHandle, "[" . date("Y-m-d H:i:s") . "] " . $log_text .  "\n");
  @fclose($fileHandle);
}

// authenticate username/password against a database
// returns: 0 if username and password is incorrect
//          emp_id if username and password are correct
function authenticate($f_chk_account, $f_chk_password, &$statusMessage)
{
  global $db, $PHP_SELF, $currentClientIP;
  $retArray = array("","","");
  
  if ($f_chk_account == "" || $f_chk_password == "") : 
     $statusMessage = getLngt("Benutzername und/oder Passwort fehlt oder ist falsch.");
     return ""; 
  endif;

  $sqlquery = "SELECT usr.usr_id, usr.hq_id, usr.usr_password FROM user AS usr, headquarters AS hq"
              . " WHERE usr.usr_account = '$f_chk_account'"
              . " AND (usr.usr_password_old = OLD_PASSWORD('" . $f_chk_password . "') OR usr.usr_password = PASSWORD('" . $f_chk_password . "'))"
              . " AND usr.hq_id = hq.hq_id";
  $result = $db->dbQ($sqlquery);
  $usr_id = "";
  $hq_id = "";
  while ($row = $result->fetch_assoc()):
     $usr_id = intval($row["usr_id"]);
     $hq_id = intval($row["hq_id"]);
     $usr_password = $row["usr_password"];
  endwhile;
  $result->free();
            
  if ($db->connect_errno):  
    $statusMessage = '$PHP_SELF: authenticate: Fehler bei Abfrage von Datenbank.';    
  else:
  
    // Get the IP of the current client calling the page
    // $currentClientIP = trim($_SERVER['REMOTE_ADDR']);  // Defined above, global import
  
    if ($usr_id == '') :
      $statusMessage = getLngt("Benutzername und/oder Passwort fehlt oder ist falsch.");
      
      // Login-trial failed! Update table "ipsecurity"
      updateClientLoginTrials();

      // Write logdata into log database
      writeToLogDB("52",$hq_id,"",$usr_id,"","","","ACCOUNT=" . $f_chk_account . "|MESS=Login failed|IP=" . $currentClientIP);
    else :          
      if (substr($usr_password, 0, 1) != "*") {
        $db->query("UPDATE user SET usr_password = PASSWORD('" . $f_chk_password . "') WHERE usr_id = " . $usr_id);
      }
      $retArray[0] = $usr_id;
      $retArray[1] = $hq_id;
      $retArray[2] = "";
    
      $emp_id = getOneStmt(
      "SELECT emp.emp_id FROM employee AS emp, user AS usr" .
         " WHERE emp.usr_id = $usr_id AND usr.usr_account = '$f_chk_account' AND usr.hq_id = $hq_id"
         . " AND usr.usr_password = PASSWORD('$f_chk_password')", "emp_id");
      if ($db->connect_errno) :
         $statusMessage = getLngt("$PHP_SELF: authenticate: Fehler bei Abfrage von Datenbank.");
      else:         
         $retArray[2] = $emp_id;
      endif;
      
      // Write logdata into log database
      writeToLogDB("52",$hq_id,"",$usr_id,"","",$emp_id,"ACCOUNT=" . $f_chk_account . "|MESS=Login ok|IP=" . $currentClientIP);
    endif;    
  endif;

  // Check status of authentication, if user is a customer
  mcIsSet($emp_id);
  if ($emp_id != "" && getFieldValueFromId("user","usr_id",$usr_id,"usr_type") == "2") :
     $cmp_authenticated = getOneStmt(
                 "SELECT cmp.cmp_authenticated"
                 . " FROM company AS cmp, customer AS cs, costcenter AS csc, employee AS emp"
                 . " WHERE emp.emp_id = $emp_id AND"
                 . "       emp.csc_id = csc.csc_id AND"
                 . "       csc.cs_id = cs.cs_id AND"
                 . "       cs.cmp_id = cmp.cmp_id", "cmp_authenticated");
     if ($db->connect_errno) :
        $statusMessage = getLngt("$PHP_SELF: authenticate: Fehler bei Abfrage von Datenbank.");
     else:         
        if ($cmp_authenticated != "1") :
           // Customer has no access
           $retArray = array("","","");
           $statusMessage = getLngt("Leider haben Sie keine Zugangsberechtigung.");
        endif;
     endif;                       
  endif;
        
  return $retArray;
}

$title = getLngt("Herzlich willkommen!");
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="description" content="votian"> <meta name="keywords" content="votian">
<title><?php echo $pageTitel; ?></title>
<link rel="stylesheet" type="text/css" href="../css/phoenix.css">
<style type="text/css">
  <?php include_once ("../css/navigation.css.php"); ?>
</style>

<?php include_once ("../include/js_framework.inc.php"); ?>

<script type="text/javascript">
<!--
<?php echo $jsMenuOut; ?>

function initForm()
{
  myhide('abmelden');
  myhide('sprache');
  document.forms[0].f_chk_account.focus();
  document.forms[0].deviceIsKnown.value = getCookie("deviceIsKnown");
//alert(document.forms[0].deviceIsKnown.value);
}
function getCookie(cname) {
  var name = cname + "=";
  var ca = document.cookie.split(";");
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == " ") {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

// Forgot password
function forgot_password() {
	var usrAccount = document.forms[0].f_chk_account.value;
	if (usrAccount == '') {
		 alert('<?php echo getLngt("Bitte tragen Sie Ihren Benutzernamen ein und bet�tigen Sie den Link erneut!") ?>');
	} else {
		 if (confirm('<?php echo getLngt("Eine E-Mail wird an Ihre erfasste Adresse geschickt!") ?>')) {
		 	  document.forms[0].f_act.value='pwdForgotten';
        document.forms[0].submit();
		 }
	}
}

-->
</script>
<script src="../include/lib_global.js" type="text/javascript">
</script>
<noscript>
  <center>
  <b><br>JavaScript ist nicht verf&uuml;gbar. Bitte aktivieren Sie JavaScript<br><br>
        in Ihrem Browser, damit diese Seite ordnungsgem&auml;&szlig; funktioniert!</b><br><br>
  </center>
</noscript>
</head>

<body leftmargin="1" topmargin="1" marginwidth="0" marginheight="0" link="#990000" vlink="#990000" alink="#990000" onLoad="<?php echo $phpCurrentNavigationOnLoad ?>initForm();">
<?php echo $phpMenuOut ?>
<?php echo $phpReducedMenuOut ?>
<?php echo $phpPageTitelOut ?>

<div class="maincontent" name="maincontent" id="maincontent">

  <?php echo htmlDivLineSpacer("30px"); ?>
  
  <div class="f12bp1_blue">
    <?php echo $title ?>
  </div>

  <?php echo htmlDivLineSpacer("25px"); ?>

    <?php
        if($multipleAccounts) :
            echo '
    <div class="modal">
        <h2>Bitte Account ausw&auml;hlen</h2>
        <form action="login.php" method="POST">
            <select name="sso_selected_account">
    ';

    foreach ($accountsList as $acc) {
        echo '<option value="'.$acc['usr_account'].'">'.$acc['usr_account'].'</option>';
    }

    echo '
            </select>
               <br>
               <br>
            <button type="submit" style="width: 120px; height: 25px; padding-top: 0px; background: rgb(84, 184, 251); color: rgb(0, 0, 0); font-size: 12pt; font-weight: bold; font-style: normal; font-family: Helvetica, Arial; border: 1px solid rgb(204, 204, 204); appearance: none; cursor: pointer;">Weiter</button>
        </form>
    </div>';
        else :
    ?>
  <div>
    <?php echo getLngt("Bitte melden Sie sich an:") ?>
  </div>
  
  <?php echo htmlDivLineSpacer("25px"); ?>
<!--    $_SERVER['SERVER_NAME']-->

    <?php
    $parSSOEnabled = "1";
    if ($parSSOEnabled == "1"){
        $tenantId = 'a70b907f-9db5-417e-a1a4-77a71bd0c8b5';
        $clientId = '94ee35c5-81fb-4ad6-8364-2a854a60851d';
        $redirectUri = 'https://test.sb.assecutor.de/admin/o-auth.php';

        // URL f�r die Anmeldung bei Microsoft erstellen
        $authorizeUrl = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/authorize";
        $scope = 'openid profile email';

        $_SESSION['state'] = bin2hex(openssl_random_pseudo_bytes(16)); // Schutz vor CSRF

        $loginUrl = $authorizeUrl . '?' . http_build_query([
                        'client_id'     => $clientId,
                        'response_type' => 'code',
                        'redirect_uri'  => $redirectUri,
                        'response_mode' => 'query',
                        'scope'         => $scope,
                        'state'         => $_SESSION['state']
                ]);

        echo '<div class="bsk-container" style="margin-top: 15px;">';
        echo '    <a href="' . $loginUrl . '" style="font-family: \'Segoe UI\', sans-serif; font-size: 15px; font-weight: 600; color: #5E5E5E; background-color: #FFFFFF; padding: 12px 12px; text-decoration: none; border: 1px solid #8C8C8C; align-items: center; justify-content: center;">';
        echo '<img src="../images/ms-symbollockup.png" alt="Microsoft Logo" style="height: 1em; width: 1em; top: .125em; position: relative; margin-right: 12px;">';
        echo '        Mit Microsoft anmelden';
        echo '    </a>';
        echo '</div>';

        // echo "<a href='$loginUrl'>". getLngt("Mit Microsoft anmelden") . "</a>";
        echo htmlDivLineSpacer("50px");
    }
    ?>
    <details>
        <summary>Klassisches Login</summary>
        <br>
        <form action="login.php" method="POST">
            <input type="hidden" name="f_act" value="">
            <div>
                <div <?php echo setStyleHtmlDiv("150px","left"); ?>><?php echo getLngt("Name:") ?></div>
                <div>
                    <input type="text" name="f_chk_account" value="<?php echo mcIsSet($f_chk_account) ?>" size="20" maxlength="20">
                </div>
            </div>
            <?php echo htmlDivLineSpacer("10px"); ?>
            <div>
                <div <?php echo setStyleHtmlDiv("150px","left"); ?>><?php echo getLngt("Passwort:") ?></div>
                <div>
                    <input type="password" name="f_chk_password" value="" size="20" maxlength="20">
                </div>
            </div>

            <?php echo htmlDivLineSpacer("20px"); ?>

            <?php echo defineButton(getLngt("Anmelden"), "f_submit", "", "", "", "", "", "", "", "", "", "", "", "", "", getLngt("Anmelden") . " ALT+a", "a", true); ?>

            <?php echo htmlDivLineSpacer("20px"); ?>

            <?php
            // $parLoginForgotPasswordEnabled = getParameterValue("0", "LOGIN_FORGOT_PASSWORD_ENABLED", "0", "0");
            if ($parLoginForgotPasswordEnabled == "1") :
                echo "<a href=\"javascript:forgot_password();\">" . getLngt("Passwort vergessen") . "</a>";
                echo htmlDivLineSpacer("20px");
            endif;
            ?>

            <div class="f10bp1_red">
                <?php echo $statusMessage; ?>
            </div>
            <input type="hidden" name="deviceIsKnown" value="">
        </form>
    </details>

</div>
<?php endif; ?>
</body>
</html>

<script type="text/javascript">
<!--
  checkBrowser();
-->
</script>
