<?php // BEGIN PHP

//session_set_cookie_params(['lifetime' => 0, 'path' => '/', 'domain' => '', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax');
session_start(); // start session

require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/categories.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
include_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php';
include_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
include_once DOL_DOCUMENT_ROOT.'/core/modules/security/generate/modGeneratePassStandard.class.php';

$tag = GETPOST('tag', 'alpha');
$cat_id = GETPOST('cat', 'alpha');
$search = GETPOST('search_query', 'alpha');

$form = new Form($db);

// END PHP 
?>
<div id="page">
  <div class="header-container">
    <?php includeContainer('header'); ?>
  </div>
  <div class="columns-container">
    <div id="columns" class="container">
        <!--  Breadcrumb  -->
        <div class="breadcrumb clearfix">
        	<a class="home" href="index.php" title="Return to Home"><i class="icon-home"></i></a>
        	<span class="navigation-pipe">&gt;</span> <?php print $weblangs->trans("resetPassword"); ?>
        </div>
        <!--  Breadcrumb  -->
      <div id="slider_row" class="row">
        <div id="top_column" class="center_column col-xs-12 col-sm-12"></div>
      </div>
      <div class="row">
        <!-- include lefet sidebar container -->
        <?php 
            includeContainer('sidebar');
            $__PAGE__TITLE__ = $weblangs->trans("forgotPasswordPageTitle");
        ?>
        <div id="center_column" class="center_column col-xs-12 col-sm-9">
          <div class="clearfix">
                <div class="row">
                    <div class="col-xs-12">
                        <?php
                            $error = 0;
                            $error_messages = array();
                            
                            // Send reset password email
            			    if (!empty(GETPOST('email'))) {

                                $customer_email = GETPOST('email');

                            	if (!isValidEmail($customer_email)) {
                            		$error++;
                            		$error_messages[] = $weblangs->trans("emailInvalid");
                            	}
                            	
                            	$sql  = "select lsa.rowid, lsa.login, lsa.fk_soc ";
                                $sql .= "from ".MAIN_DB_PREFIX."societe_account lsa ";
                                $sql .= "where lsa.login = '". $db->escape($customer_email) ."' ";
                                $sql .= "and lsa.fk_website = ". ((int) $website->id) . " ";
                                $sql .= "limit 1";
                                
                                $result = $db->query($sql);
                            	$objsql = $db->fetch_object($result);
                            	
                            	if (empty($objsql)) {
                            		$error++;
                            		$error_messages[] = $weblangs->trans("emailDoesNotExist");
                                }
                            

                                if($error == 0){
                                    // Start of transaction
                                    $db->begin();
                                    
                                    // Generate a random password
                                    $newpass = getRandomPassword(true, null, 16);
                                    $pass_temp_crypted = dol_hash($newpass, 'md5');
                                    
                                    $societeaccount = new SocieteAccount($db);
                                    $societeaccount->fetch($objsql->rowid);
                                    $societeaccount->id = $objsql->rowid;
                                    $societeaccount->pass_temp = $pass_temp_crypted;
                                    $societeaccount->date_last_reset_password = dol_now();
                            
                                    $result = $societeaccount->update($user);
                                    if ($result < 0) {
                            			$error++;
                            			$error_messages[] = $weblangs->trans("errorOccurred");
                            		}
                            		
                            		if ($error == 0) {
                            		    
                            		    $sql  = "select ls.nom ";
                                        $sql .= "from ".MAIN_DB_PREFIX."societe ls ";
                                        $sql .= "where ls.rowid = '". $objsql->fk_soc ."' ";
                                        $sql .= "limit 1";
                                        
                                        $result = $db->query($sql);
                                		$objsql_customer = $db->fetch_object($result);
                                		
                                		// Generate the link
                                        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
                                        $host = $_SERVER['HTTP_HOST'];
                                        $requestUri = $_SERVER['REQUEST_URI'];
                                        $currentUrl = $protocol . $host . $requestUri;
                                        
                                		// Check if the URL already contains GET parameters
                                        if (strpos($requestUri, '?') !== false) {
                                            // If the URL contains parameters, append the token with &
                                            $resetLink = $currentUrl . "&token=" . urlencode($pass_temp_crypted);
                                        } else {
                                            // If the URL does not contain parameters, append the token with ?
                                            $resetLink = $currentUrl . "?token=" . urlencode($pass_temp_crypted);
                                        }

                            		    // Send welcome email
                            		    $substitutionarray = array(
                            	            '__USER_NAME__' => $objsql_customer->nom,
                            	            '__PASSWORD__RESET_LINK__' => $resetLink
                            	        );
                                    	$email_sended = marketplace_send_email(getDolGlobalInt("MARKETPLACE_FORGOT_PASSWORD_EMAIL_TEMPLATE"), 'thirdparty', $societeaccount, $objsql->login, $substitutionarray);
                                        
                                        $db->commit();
                            		} else {
                            		    $db->rollback();
                            		}
                                }
                            		
                            }


                            // Check token
                            if (!empty(GETPOST('token'))) {
                                
                                $token = GETPOST('token');
                                $sql  = "select lsa.rowid, lsa.pass_encoding, lsa.pass_crypted, lsa.pass_temp, lsa.date_last_reset_password, ls.nom, fk_soc ";
                                $sql .= "from ".MAIN_DB_PREFIX."societe_account lsa ";
                                $sql .= "left join ".MAIN_DB_PREFIX."societe ls on ls.rowid = lsa.fk_soc ";
                                $sql .= "where lsa.pass_temp = '". $db->escape($token) ."' ";
                                $sql .= "and lsa.fk_website = ". ((int) $website->id) . " ";
                                $sql .= "limit 1";
                                
                                $result = $db->query($sql);
                        		$objsql = $db->fetch_object($result);
                                if (!empty($objsql)) {
                                    $dateTokenDateTime = new DateTime($objsql->date_last_reset_password);
                                    $now = new DateTime();
                                    $interval = $now->diff($dateTokenDateTime);
                                    
                                    if ($interval->days < 1 && $interval->h < 24 && $objsql->pass_temp == $token) {
                                        $correct_token = 1;
                                    } else {
                                        $error++;
                            		    $error_messages[] = $weblangs->trans("wrongOrExpiredToken");
                                    }

                                }else{
                                    $error++;
                            		$error_messages[] = $weblangs->trans("wrongOrExpiredToken");
                                }
                                
                            }
                            
                            // Change password
                            if (!empty(GETPOST('token')) && !empty($correct_token) && $correct_token == 1) {
                                $token = GETPOST('token');
                                $new_passwd1 = GETPOST('new_passwd1');
                                $new_passwd2 = GETPOST('new_passwd2');
                                
                                if (empty($new_passwd1) || empty($new_passwd2)) {
                            		$error++;
                            		$error_messages[] = $weblangs->trans("bothFieldsRequired");
                            	}
                            	
                            	if (!empty($new_passwd1) && !empty($new_passwd2) && $new_passwd1 != $new_passwd2) {
                            		$error++;
                            		$error_messages[] = $weblangs->trans("passwordsAreNotTheSame");
                            	}

                                if ($error == 0) {
                                   	$check_pass = new modGeneratePassStandard($db, $conf, $langs, $user);
                                	$is_valid = $check_pass->validatePassword($new_passwd1);
                                	if(!$is_valid){
                                	    $error++;
                                	    $weblangs->load("other");
                                		$error_messages[] = $weblangs->trans("YourPasswordMustHaveAtLeastXChars", (string) $check_pass->length2);
                                	}
                                }
                                
                                if ($error == 0) {
                                    $societeaccount = new SocieteAccount($db);
                                    $societeaccount->fetch($objsql->rowid);
                    				$societeaccount->pass_encoding = "dolibarr";
                    				$societeaccount->pass_crypted = dol_hash($new_passwd1);
                    				$ret_account = $societeaccount->update($user);
                    				if ($ret_account < 0) {
                    					$error++;
                    					$error_messages[] = $weblangs->trans("errorOccurred");
                    				} else {
                    				    $passwordChanged = 1;
                    				}
                                }
                                
                            }
            			?>
            			
            			<?php
            			    // Choose content to display
                			$page_content = "email_form";
                			if (isset($email_sended) && $email_sended != 0) {
                			    $page_content = "email_sent";
                			}
                			if (!empty(GETPOST('token'))) {
                			    $page_content = "password_form";
                			}
                			if (!empty(GETPOST('token')) && !empty($passwordChanged) && $passwordChanged == 1) {
                			    $page_content = "password_changed";
                			}
            			?>
            			
            			<?php if ($page_content == "email_sent"): ?>
                        	<p>
                        	    <div class="account_creation">
                        			<h3 class="page-subheading"><?php print $weblangs->trans("resetPassword"); ?></h3>
                        	        <p class="p_with_margin box"><?php print $weblangs->trans("resetPasswordEmailSent"); ?></p>
                        	    </div>
                        	</p>
                        <?php endif; ?>


                        <?php if ($page_content == "password_form"): ?>
                            <h3 class="page-subheading"><?php print $weblangs->trans("resetPassword"); ?></h3>
                            <form action="" method="post" id="account-creation_form" class="std box">
                                <div class="account_creation">
                                    <?php if (isset($error) && $error != 0): ?>
                        		        <div class='alert alert-danger'>
                            		        <?php $add_s = ($error > 1) ? "s" : ""; ?>
                		                    <p><?php print $weblangs->trans("errorsOccurred", $error, $add_s); ?></p>
                                    		<ol>
                                    		    <?php foreach ($error_messages as $key => $value): ?>
                                            		<li><?php print $weblangs->trans($value); ?></li>
                                            	<?php endforeach ?>
                                    		</ol>
                                    	</div>
                                	<?php endif ?>
                                	
                                	<div class="required password form-group">
                        				<label for="passwd"><?php print $weblangs->trans("newPasswd"); ?> <sup>*</sup></label>
                        				<input type="password" class="is_required validate form-control" required name="new_passwd1" id="passwd" value="">
                        			</div>
                        			<div class="required password form-group">
                        				<label for="passwd"><?php print $weblangs->trans("reEnterNewPassword"); ?><sup>*</sup></label>
                        				<input type="password" class="is_required validate form-control" required name="new_passwd2" id="passwd" value="">
                        			</div>
                                    
                                    <hr>
                        			<button type="submit" name="submitAccount" id="submitAccount" class="btn btn-default button button-medium">
                        				<span><?php print $weblangs->trans("Save"); ?> <i class="icon-chevron-right right"></i></span>
                        			</button>
                			
                                </div>
                            </form>
                        <?php endif; ?>


                        <?php if ($page_content == "password_changed"): ?>
                            <p>
                                <div class="account_creation">
                                    <h3 class="page-subheading"><?php print $weblangs->trans("resetPassword"); ?></h3>
                                    <p class="p_with_margin box"><?php print $weblangs->trans("passwordChangedMessage"); ?></p>
                                </div>
                            </p>
                        <?php endif; ?>
                        
                        
                        <?php if ($page_content == "email_form"): ?>
                            <form action="" method="post" id="account-creation_form" class="std box">
                        		<div class="account_creation">
                        			<h3 class="page-subheading"><?php print $weblangs->trans("resetPassword"); ?></h3>
                        			<?php if (isset($error) && $error != 0): ?>
                                		<div class='alert alert-danger'>
                                    		<?php $add_s = ($error > 1) ? "s" : ""; ?>
                		                    <p><?php print $weblangs->trans("errorsOccurred", $error, $add_s); ?></p>
                                    		<ol>
                                    		    <?php foreach ($error_messages as $key => $value): ?>
                                            		<li><?php print $weblangs->trans($value); ?></li>
                                            	<?php endforeach ?>
                                    		</ol>
                                    	</div>
                                	<?php endif ?>
    
                        			<div class="required form-group">
                        				<label for="email"><?php print $weblangs->trans("email"); ?> <sup>*</sup></label>
                        				<input type="text" class="is_required validate form-control" required id="email" name="email" value="<?php if (isset($customer_email)){print $customer_email;} ?>">
                        			</div>
                        		</div>
    
                        		<input type="hidden" name="action" value="resetpassword">
                        		<div class="submit clearfix">
                        			<hr>
                        			<button type="submit" name="submitAccount" id="submitAccount" class="btn btn-default button button-medium">
                        				<span><?php print $weblangs->trans("submit"); ?> <i class="icon-chevron-right right"></i></span>
                        			</button>
                        		</div>
                        	</form>
                        <?php endif ?>
                        
                    </div>
                </div>
                <ul class="footer_links clearfix">
                	<li>
                		<a class="btn btn-default button button-small" href="myaccount.php">
                			<span>
                				<i class="icon-chevron-left"></i> <?php print $weblangs->trans("backToYourAccount"); ?>
                			</span>
                		</a>
                	</li>
                	<li>
                		<a class="btn btn-default button button-small" href="index.php">
                			<span><i class="icon-chevron-left"></i> <?php print $weblangs->trans("Home"); ?></span>
                		</a>
                	</li>
                </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- .columns-container -->
  <div class="footer-container">
    <?php includeContainer('footer'); ?>
  </div>
</div>