<?php
   //20150611 - changed to home from index.php - pj
   //20160513 - Multi level security groups [SecurityGroupID IN()] - pj
   //20170802 - changed login process to user API loginUser function - maanie
   //20171011: Set default language to be english on the Admin side. Gael
   //20171020 - if UCG doesnt exist  create one. jacques

   //20171106 - added Under Construction - pj
   //20171127 - added un-Under Construction - pj
   //20171204 - Clean URL string using urlencode - maanie
   //20180220 - get vendorkey from DB settings - maanie
   //20180412 - Changed mispelled text "Reset Email Has Been send to" to Reset email has been sent to". Gael

   include_once("_framework/_nemo.basic.cls.php");
   include_once("_framework/_nemo.password.cls.php");

   $NemoBasicObj = new NemoBasic();
   if($SystemSettings["SERVER_NAME"] == "www.sawisonline.co.za" && false)
   {
      if(isset($_REQUEST["test"]) || count($_POST) > 0){
      }else{
         header("Location: server.error.php?MID=uc");
      }
   }

   $Session = $_SESSION["USERADMIN"];
   session_destroy();

   $Action = isset($_POST["Action"]) ? $_POST["Action"] : $_GET["Action"];

   $Nav = isset($_POST["Nav"]) ? $_POST["Nav"] : $_GET["Nav"];
   switch($Action) 
   {
      case "Load Draft": 
         $row = $xdb->getRowSQL("SELECT  *
                              FROM sysUser INNER JOIN sysSecurityGroup ON sysSecurityGroup.SecurityGroupID = sysUser.refSecurityGroupID
                              WHERE strEmail = ".$xdb->qs($strUsername)." AND sysSecurityGroup.blnActive = 1",0);

         unset($_SESSION["S3REGISTRATION"]);

         if(($row->refMemberID != 0) && ($row->refMemberID != ""))
         {
            $_SESSION["ContinueS3"]->MemberID = $row->refMemberID;
            $_SESSION["S3REGISTRATION"]->MemberID = $row->refMemberID;
            $rowMember = $xdb->getRowSQL("SELECT * FROM tmpMember WHERE MemberID = $row->refMemberID");
            $rowMember->RegistrationArgs = str_replace("'", '"', $rowMember->RegistrationArgs);
            $Args = unserialize($rowMember->RegistrationArgs);
         }

         $_SESSION["ContinueS3"]->UserID = $row->UserID;
         $_SESSION["ContinueS3"]->IsActive = $row->blnActive;

         $_SESSION["S3REGISTRATION"]->ChangeOwnMemberID = $Args["ChangeOwnMemberID"];
         $_SESSION["S3REGISTRATION"]->blnAllWine = $Args["blnAllWine"];
         $_SESSION["S3REGISTRATION"]->refMembershipType = $Args["refMembershipType"];
         $_SESSION["S3REGISTRATION"]->refMembershipType2 = $Args["refMembershipType2"];
         $_SESSION["S3REGISTRATION"]->bMemberID = '';

         windowlocation("registration.member.php?Action=LoadDraft");

         break;
   }

   if(isset($username))
   {
      $strUsername = $username;
   }
   else
   {
      $strUsername = $_POST["strUsername"];
   }
   if(isset($_GET["strUsername"]))
   {
      $strUsername = $_GET["strUsername"];
   }
   
   //20170802 - changed login process to user API loginUser function - maanie
   if($Action == "Login")
   {
      /*do the login process
         if username
            if memberID
               if status
                  if authenticate
                     if loginUser API call
                        set session
      */
      session_start();
      $_SESSION["USERADMIN"] = $Session;

      $row = $xdb->getRowSQL("SELECT  *
                              FROM sysUser 
                              INNER JOIN sysSecurityGroup ON sysSecurityGroup.SecurityGroupID = sysUser.refSecurityGroupID
                              WHERE 
                                 strEmail = ".$xdb->qs($strUsername)." 
                                 AND sysSecurityGroup.blnActive = 1", 0);

      $SystemMessage = new stdClass();

      if(isset($row->refMemberID))
      {
         $rowMember = $xdb->getRowSQL("SELECT * FROM tmpMember WHERE MemberID = $row->refMemberID", 0);
      }

      if($row)
      {
         if(($row->refMemberID != 0) || ($row->refMemberID == null))
         {
            if($rowMember->strStatus != "1.0 - New")
            {
               if($row->blnActive == 1)
               {
                  //switch to API DB
                  $rst = switchBD($DATABASE_SETTINGS_API);
                  if($rst == false)
                  { 
                     die($SystemMessage->Message);
                  } 

                  $rowVendor =  $xdb->getRowSQL("SELECT * FROM apiVendor WHERE VendorKey = '".$DATABASE_SETTINGS[$SystemSettings["SERVER_NAME"]]->vendorkey."'", 0);
                  
                  $_SESSION["VENDOR"] = $rowVendor;

                  $np = new NemoPassword();
                  $np->getLastPassword("User", $row->UserID, 0);

                  // print_rr("Last User Password Details:");
                  // print_rr($np);

                  switchBD($DATABASE_SETTINGS);

                  //call authenticate to get token
                  $authenticate_url = $SystemSettings["BASE_URL_API"] ."/api.php?VendorKey=".urlencode($DATABASE_SETTINGS[$SystemSettings["SERVER_NAME"]]->vendorkey)."&call=authenticate&Password=". urlencode($_SESSION["VENDOR"]->strPassword) ."";
                  $_SESSION["VENDOR"]->strPassword = Obfuscate(); //hide pw
                  $responseAuth = get_url($authenticate_url); 

                  // print_rr("authenticate url: ".$authenticate_url);
                  // print_rr("response Auth: ");
                  // print_rr($responseAuth);

                  if($responseAuth != "AUTHENTICATION FAILED" && $responseAuth != "INVALID VENDOR KEY")
                  {
                     $xml = "";
                     $UserHash = "";
                     
                     if(isset($_GET["strHash"]))
                     {
                        $UserHash = $_GET["strHash"];
                     }

                     //call loginUser method and handle response
                     //20171204 - Clean URL string using urlencode - maanie
                     $strPassword = $_POST["strPassword"];
                     $strPasswordHashed = hash("sha256", $_POST["strPassword"]);
                     $request_url = $SystemSettings["BASE_URL_API"] ."/api.php?VendorKey=".urlencode($DATABASE_SETTINGS[$SystemSettings["SERVER_NAME"]]->vendorkey)."&call=loginUser&Username=". urlencode($strUsername) ."&Password=". urlencode($strPassword) ."&Token=$responseAuth";
                     $responseLoginUser = get_url($request_url); 
                     $xml = simplexml_load_string($responseLoginUser);

                     // print_rr("request url: ");
                     // print_rr($request_url);
                     // print_rr("response Login User: ");
                     // print_rr($responseLoginUser);
                     // print_rr("xml:");
                     // print_rr($xml);
                     // print_rr(gettype($xml));
                     // print_rr("UserHash1: ".$UserHash);
                     // print_rr("CustomHash: ".$strPasswordHashed);
                     // print_rr("UserHash2: ".$np->hash);

                     if($xml != null || ($UserHash == $np->hash))
                     {
                        $rowMember = $xdb->getRowSql("SELECT * FROM tblMember WHERE MemberID = ". $row->refMemberID, 0);

                        $LoggedInUserID = $row->UserID;

                        $_SESSION["USER"] = new stdClass();
                        $_SESSION["USER"]->ID = $LoggedInUserID;

                        if(isset($_SESSION["USERADMIN"]->USERNAME))
                        {
                           $_SESSION["USER"]->USERNAME = $_SESSION["USERADMIN"]->USERNAME;
                        }
                        else
                        {
                           $_SESSION["USER"]->USERNAME = $row->strUser;
                        }

                        $_SESSION["USER"]->EMAIL = $row->strEmail;
                        $_SESSION["USER"]->SECURITYGROUPID =
                        $_SESSION["USER"]->SECURITYGROUPID_IN = $row->refSecurityGroupID; //20160513 - Multi level security groups [SecurityGroupID IN()] - pj
                        $_SESSION["USER"]->COMPANYID = $row->refMemberID; //20160513 - Multi level security groups [SecurityGroupID IN()] - pj
                        $_SESSION["USER"]->COMPANY = $rowMember->strMember;
                        $_SESSION["USER"]->PROFILEIMG = $row->{'Profile:PicturePath'} ;

                        //sawis only
                        //20171011: Set default language to be english on the Admin side. Gael
                        $strSettingLanguage = "strSetting:Language";
                        $_SESSION["USER"]->LANGUAGE = "EN"; 
                        $_SESSION["USER"]->MEMBERID = $row->refMemberID;

                        if(($row->strSecurityGroup == "Admin Dev") || ($row->strSecurityGroup == "Sawis Admin"))
                        {
                           // $rowData = (array) $xml->rows->row;

                           if(!isset($_SESSION["USERADMIN"]->EMAIL))
                           {
                              $_SESSION["USERADMIN"] = new stdClass();
                           }

                           //swtich to API DB
                           switchBD($DATABASE_SETTINGS_API);

                           $np = new NemoPassword();
                           $np->getLastPassword("User", $LoggedInUserID, 0);
                           $_SESSION["USERADMIN"]->EMAIL = $row->strEmail;
                           $_SESSION["USERADMIN"]->USERNAME = $row->strUser;
                           $_SESSION["USERADMIN"]->ADMINACCESS = "index.php?Action=Login&Nav=home&strUsername=$row->strEmail&strHash=$np->hash";

                           //switch back to sawis DB
                           switchBD($DATABASE_SETTINGS);
                        } 

                        $sysUserCompanyGroupUsername = "System ".$_SESSION["USER"]->USERNAME;

                        // 20171020 - if UCG doesnt exist  create one. jacques
                        $xdb->doQuery("INSERT IGNORE INTO sysUserCompanyGroup (refUserID, refCompanyID, refSecurityGroupID, blnActive, strLastUser)
                           VALUES ('$row->UserID', '$row->refMemberID', '$row->refSecurityGroupID', 1, '$sysUserCompanyGroupUsername')");

                        switch($Nav)
                        {
                           case "SAWIS2":
                              $nav = "registration.farm.php";
                              break;
                           default:
                              $nav = "home.php";
                        }

                        tblLoginInsert("Login successful");
                        header("Location: $nav"); //20150611 - changed to home from index.php - pj
                        die;
                     }
                     else
                     {  
                        $M .= $responseLoginUser;
                        $T = "warning"; 
                     }
                  }
                  else
                  { 
                     $M .= $responseAuth;
                     $T = "error";
                  }
               }
               else
               { 
                  tblLoginInsert("Login failed: Inactive User");
                  $M = "User account is inactive.";
                  $T = "warning";
               }
            }
            else
            { 
               $M = "User does not have a member record. </n> Click Load draft to continue with the registration. ";
               $T = "warning";

               $_SESSION["ContinueS3"]->UserID = $row->UserID;
               $_SESSION["ContinueS3"]->IsActive = $row->blnActive;
            }
         }
         else
         { 
            $M = "User does not have a member record. </n> Click Load draft to continue with the registration. ";
            $T = "warning";

            $_SESSION["ContinueS3"]->UserID = $row->UserID;
            $_SESSION["ContinueS3"]->IsActive = $row->blnActive;
         }
      }
      else
      {   
         tblLoginInsert("Login failed: User not found or SG not active");
         $M = "Login Details are invalid.";
         $T = "warning";
         
         $start_date = new DateTime(date("Y-m-d H:i:s"));  
         $start_date_only  = $start_date->format('Y-m-d H:i:s');

         $end_date = new DateTime($start_date_only);  
         $end_date->modify('-1 min');  
         $end_date_only  = $end_date->format('Y-m-d H:i:s');

         $row = $xdb->doQuery("SELECT * FROM sysLogin WHERE strIP = '".$_SERVER['REMOTE_ADDR']."' AND strResult LIKE '%Login failed%' AND dtLastEdit BETWEEN '$end_date_only' AND '$start_date_only'", 0);
         $num_Rows = $xdb->num_rows($row);

         if($num_Rows > 10)
         {
            // insert record in IP block table
            $IPdb = new NemoDatabase("sysIPBlock", 0, null, 0);
            $IPdb->Fields["strIP"] = $_SERVER['REMOTE_ADDR']; 
            $IPdb->Fields["txtNote"] = "Bot activity detected"; 
            $IPdb->Fields["strBlockDate"] = date("Y-m-d H:i:s"); 
            $IPdb->Fields["strLastUser"] = "$strUsername"; 
            $IPdb->Save(0,0);
         } 
      }
   }

   $LoggedOutUsername = $_GET["UN"];
   if($LoggedOutUsername != "")
   {
      $strUsername = $LoggedOutUsername;
   }

   // SHOW ERROR MESSAGE
   if($M != "")
   {
      //initialise arrays and objects
      $NemoBasicObj->Message = new stdClass();
      $NemoBasicObj->Message->Text = $M;
      $NemoBasicObj->Message->class = $T;
   }

   $attrLogin = new stdClass();
   $attrText = new stdClass();

   $attrLogin->onclick="return Validate();";
   $attrLogin->Class="controlButton";
   $attrText->Class="controlText";

   if($_GET["LoginMsg"] == "resetSuccess")
   {
      $LoginMsg = "  <tr><td colspan='2' style='height:10px;'></td></tr>
                     <tr>
                        <td style='width:25%;' align='right'> </td>
                        <td style='width:75%; color:Green; font-size:12px;'>Password Has Been Reset. Please login with new password.</td>
                     </tr>";
   }
   else if($_GET["LoginMsg"] == "resetError")
   {
      $LoginMsg = "  <tr><td colspan='2' style='height:10px;'></td></tr>
                     <tr>
                        <td style='width:25%;' align='right'> </td>
                        <td style='width:75%; color:red;  font-size:12px;'>Password Reset Failed. Please try again.</td>
                     </tr>";
   }
   else
   {
      $LoginMsg = "";
   }

   if(isset($_SESSION["ContinueS3"]))
   {
      $showLoad = "display:block";
   }
   else
   {
      $showLoad = "display:none;";
   }

   //20210610 - Add ip checker to see if ip is blocked
   $row = $xdb->getRowSQL("SELECT * FROM sysIPBlock WHERE strIP = '".$_SERVER['REMOTE_ADDR']."'");

   if(isset($row->BlockID))
   {
      $a = "35%";
      $NemoBasicObj->Content = "
      <br>
      <center> 
         <div class='dora-LoginBox'>
            <table id='rrr'>
            <caption> Login  </caption>
            <tr>
               <td style='padding:10px;'> 
                  <span style='color:red; font-size:13px;'><b>This IP address Has been flagged</b></span> <br><br>  
                     - For more information please contact support at <u>021 807 5706</u>
                  
               </td>
            </tr>
            </table> 
         </div>
      </center>";
   }
   else
   {
      // $OfflineMsg = "<div> 
      //                <br><span style='color:red; font-size:13px;'>
      //                <u>Server Maintenance Notice</u> <br>
      //                <i>
      //                   <br>We will be upgrading our servers on Friday, October 24th until Sunday, October 26th. During this time, our websites will be offline. We apologize for any inconvenience this may cause.
      //                </i>
      //                </span>
      //                </div> ";

                  

      $OfflineMsg = "";
      $a = "35%";
      $NemoBasicObj->Content = " 
      <br>
      <center>
          
      <div class='dora-LoginBox'> 
         <table id='rrr'>
            <caption>
               Login
               $OfflineMsg 
            </caption>
            $LoginMsg
            <tr><td colspan='2' style='height:10px;'></td></tr>
            <tr>
               <td style='width:25%;' align='right'>Email:</td>
               <td style='width:75%;'>". $NemoBasicObj->controls->createControl("", "strUsername","",$strUsername, $attrText) ."</td>
            </tr>
            <tr><td colspan='2' style='height:10px;'></td></tr>
            <tr>
               <td align='right'>Password:</td>
               <td>". $NemoBasicObj->controls->createControl("password", "strPassword","","", $attrText) ."</td>
            </tr>
            <tr><td colspan='2' style='height:10px;'></td></tr>
            <tr>
               <td></td>
               <td>
                  ". $NemoBasicObj->controls->createControl("submit", "Action","","Login", $attrLogin) ."
                  <a style='margin-left:10px;' href='#' onclick='jsResetPassword();'>Forgot Password?</a>
                  <a style='margin-left:10px;' href='registration.member.php' >Register User?</a>
                  <span style='margin-left:10px; cursor:pointer; color:darkgreen; text-decoration:underline;' onclick='jsOpenPrivacyNotice();'>Privacy Notice</span>
               </td>
            </tr>
            <tr><td colspan='2' style='height:10px;'></td></tr>

         </table>
         <input type='hidden' id='MemberID' name='MemberID' value='$row->refMemberID' />
         <input type='hidden' id='UserID' name='UserID' value='$row->UserID' />
         <input type='hidden' id='RegistrationStatus' name='RegistrationStatus' value='$RegistrationStatus' />
         <input type='hidden' id='IsActive' name='IsActive' value='$IsActive' />
         <div align='center' id='msgError' >".$_TRANSLATION[$_SESSION["LANGUAGE"]]["DraftError"]."</div>
         <div align='center' id='msgPendingDraft' style='$showLoad'>User does not have a member record. Click <input class='controlButtonMSG' type='submit' value='Load Draft' name='Action' /> to continue with the registration. </div>

         <div id='resetPassword' style='display:none; '>
            <table  style='background-color:#eaeaea !important; border-top:solid 1px #999 !important; margin-bottom:0px !important;'>
               <tr><td colspan='2' style='height:10px;'></td></tr>
               <tr>
                  <td colspan='2' align='center' style='width:75%;'>Please submit your email in order to receive the password reset process.</td>
               </tr>
               <tr><td colspan='2' style='height:10px;'></td></tr>
               <tr>
                  <td style='width:25%;' align='right'>Email:</td>
                  <td style='width:75%;'>". $NemoBasicObj->controls->createControl("", "strEmail","",$strEmail, $attrText) ."</td>
               </tr>
               <tr><td colspan='2' style='height:10px;'></td></tr>
               <tr>
                  <td></td>
                  <td><input class='controlButton' type='button' value='Reset Password' name='resetPassword' onclick='jsStartResetProcedure();''> <img id='loaderGif' style='display:none; margin: -10px 20px;' width='30px' height='30px' src='images/loadingAnimation.gif' /></td>
               </tr>
               <tr><td colspan='2' style='height:10px;'></td></tr>
            </table>
         </div>
         <div align='center' id='success' style='display:none; background-color:#2ba800; color:#ffffff;padding:10px; '>
             Reset Email Has Been send.
         </div>
         <div align='center' id='error' style='display:none; background-color:#c80000; color:#ffffff;padding:10px; font-weight:bold;'>

         </div>
      </div>
   
      "
      .js("
            function jsOpenPrivacyNotice()
            { 
               (function (w,d,s,o,f,js,fjs) { w['365Compliance']=o;w[o] = w[o] || function () { (w[o].q = w[o].q || []).push(arguments) };js = d.createElement(s), fjs = d.getElementsByTagName(s)[0];js.id = o; js.src = f; js.async = 1; fjs.parentNode.insertBefore(js, fjs);}(window, document, 'script', 'mw', 'https://app.priviq.com/js/365Compliance.min.js'));mw('init',{container:'your-element-id',key:'b10bda09-6813-4a1f-af25-555dfc87e8c5'});mw('pn'); 
       
            }

            function jsStartResetProcedure()
            {
               $('#loaderGif').show('fast').delay( 800 );
               $('#success').slideUp('fast');
               $('#error').slideUp('fast');

               Email = trim($('#strEmail').val());
               if(Email == '')
               {
                  $('#error').html('Please type in your email address.');
                  $('#error').slideDown('fast');
               }
               else
               {
                  $.ajax(
                  {
                     type: 'GET',
                     url: 'ajaxfunctions.php',
                     data: 'header=text&type=SendResetEmail&strEmail=' + Email,
                     success: function(data)
                     {
                        if(data == 1)
                        {
                           $('#success').html('Reset email has been sent to <span style=\"font-weight:bold\">' + Email + '</span>.')
                           $('#success').slideDown('fast').delay( 800 );
                        }
                        else if(data == 0)
                        {
                           $('#error').html('<span style=\"font-weight:bold\">' + Email + '</span> does not exist in our database.')
                           $('#error').slideDown('fast').delay( 800 );
                        }
                        else if(data == 2)
                        {
                           $('#error').html('Authentication Failed');
                           $('#error').slideDown('fast').delay( 800 );
                        }
                     }
                  });
               }
                $('#loaderGif').hide('fast');
            }

            function jsResetPassword()
            {
               if($('#resetPassword').is(':visible'))
               {
                  $('#resetPassword').slideUp('fast');
               }
               else
               {
                  $('#resetPassword').slideDown('fast');
               }

            }

            function Validate()
            {
               msg = '';

               return true;
            }

            if(d('strUsername').value == '')
            {
               d('strUsername').focus();
            }else{
               d('strPassword').focus();
            }

            ");      
   }
   
   $NemoBasicObj->Display();
?>