<?php

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

require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
$form = new Form($db);
$weblangs->loadLangs(array("main", "companies"));
?>
<?php
    if(!empty(GETPOST('action')) && GETPOST('action') == "register") {
        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/modules/security/generate/modGeneratePassStandard.class.php';
        $id_website = $website->id;
        $marketplace_third_parties_category = getDolGlobalInt("MARKETPLACE_PROSPECTCUSTOMER_ID");
        

        $customer_firstname = GETPOST('firstname');
        $customer_lastname = GETPOST('lastname');
        $customer_email = GETPOST('email');
        $customer_passwd = GETPOST('passwd');
        $customer_address = GETPOST('address');
        $customer_city = GETPOST('city');
        $customer_postalcode = GETPOST('postalcode');
        $customer_country = GETPOSTINT('country_id');
        $customer_company = GETPOST('company');
        $customer_siret = GETPOST('siret');
        $customer_tin = GETPOST('tin');
        $back = GETPOST('back');
        
        $error = 0;
        $error_messages = array();
        
        // Check Captcha return if captcha is activated
        if (!empty(getDolGlobalInt("MARKETPLACE_GOOGLE_RECAPTCHA_REGISTER_FORM"))) {
            include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
            
            $recaptchaSecretKey = getDolGlobalString("MARKETPLACE_GOOGLE_RECAPTCHA_SECRET_KEY");
            $recaptchaResponse = GETPOST('g-recaptcha-response');
        
            $responseDataRecaptcha = getURLContent("https://www.google.com/recaptcha/api/siteverify?secret=$recaptchaSecretKey&response=$recaptchaResponse");
            $responseDataRecaptcha = json_decode($responseDataRecaptcha['content']);
            
            if (!$responseDataRecaptcha->success || $responseDataRecaptcha->score < 0.5) {
                $error++;
                $error_messages[] = $weblangs->trans("captchaFail", ($responseDataRecaptcha->score ?? 'N/A'));
            }
        }
        
        if (!isValidEmail($customer_email)) {
    		$error++;
    		$error_messages[] = $weblangs->trans("emailInvalid");
    	}
    	
    	
    	$sql  = "select lsa.rowid ";
        $sql .= "from ".MAIN_DB_PREFIX."societe_account lsa ";
        $sql .= "where lsa.login = '". $db->escape($customer_email) ."' ";
        $sql .= "and lsa.fk_website = ". ((int) $id_website) . " ";
        $sql .= "limit 1";
        
        $result = $db->query($sql);
		$objsql = $db->fetch_object($result);
		
		if (!empty($objsql)) {
    		$error++;
    		$error_messages[] = $weblangs->trans("emailAlreadyRegistered");
        }
    	
    	if (empty($customer_firstname)) {
    		$error++;
    		$error_messages[] = $weblangs->trans("fieldRequired", $weblangs->transnoentitiesnoconv("Firstname"));
    	}
    	
    	//if (ctype_alpha(str_replace(array("\n", "\t", ' '), '', $customer_firstname)) === false) {
    	if (!preg_match('/^[a-zA-ZÀ-ÖØ-öø-ÿ\- ]+$/u', $customer_firstname)) {
    	    $error++;
            $error_messages[] = $weblangs->trans("firstnameContainsLettersOnly");
        }
    	
    	if (empty($customer_lastname)) {
    		$error++;
    		$error_messages[] = $weblangs->trans("fieldRequired", $weblangs->transnoentitiesnoconv("Lastname"));
    	}
    	
    	//if (ctype_alpha(str_replace(array("\n", "\t", ' '), '', $customer_lastname)) === false) {
    	if (!preg_match('/^[a-zA-ZÀ-ÖØ-öø-ÿ\- ]+$/u', $customer_lastname)) {
    	    $error++;
            $error_messages[] = $weblangs->trans("lastnameContainsLettersOnly");
        }
    	
    	$check_pass = new modGeneratePassStandard($db, $conf, $langs, $user);
    	$is_valid = $check_pass->validatePassword($customer_passwd);
    	if(!$is_valid){
    	    $error++;
    	    $weblangs->load("other");
    		$error_messages[] = $weblangs->trans("YourPasswordMustHaveAtLeastXChars", (string) $check_pass->length2);
    	}
    	
    	if (empty($customer_address)) {
    		$error++;
    		$error_messages[] = $weblangs->trans("fieldRequired", $weblangs->transnoentitiesnoconv("Address"));
    	}
    	
    	if (empty($customer_city)) {
    		$error++;
    		$error_messages[] = $weblangs->trans("fieldRequired", $weblangs->transnoentitiesnoconv("Town"));
        } elseif (!preg_match('/^[a-zA-ZÀ-ÖØ-öø-ÿ\- ]+$/u', $customer_city)) {
            $error++;
            $error_messages[] = $weblangs->trans("cityContainsLettersOnly");
        }
        
        if (empty($customer_postalcode)) {
    		$error++;
    		$error_messages[] = $weblangs->trans("fieldRequired", $weblangs->transnoentitiesnoconv("Zip"));
        } elseif (!preg_match('/^[a-z0-9\.\- ]+$/i', $customer_postalcode)) {
            $error++;
            $error_messages[] = $weblangs->trans("postalCodeContainsDigitsOnly");
        }
    	
    	if (empty($customer_country)) {
    		$error++;
    		$error_messages[] = $weblangs->trans("fieldRequired", $weblangs->transnoentitiesnoconv("Country"));
    	}
        
        if($error == 0){
            // Start of transaction
            $db->begin();
            
            $customer = new Societe($db);
        
        	if (!empty($customer_company)) {
        		$customer->name = $customer_company;
        	} else {
        		$customer->name = dolGetFirstLastname($customer_firstname, $customer_lastname);
        	}
        	$customer->name_alias = '';

        	$customer->address = $customer_address;
        	$customer->town = $customer_city;
        	$customer->zip = $customer_postalcode;
        	$customer->country_id = $customer_country;
        
        	$customer->idprof2 = $customer_siret;
        	$customer->tva_intra = $customer_tin;

        	$customer->client = '2';    // Set as prospect by default.
        	$customer->code_client = 'auto';

        	$customer->fournisseur = '0';
        	$customer->code_fournisseur = 'auto';
        
        	//$customer->default_lang = $obj->dol_lang_code;
        	
        	$customer->ip = getUserRemoteIP();
        	
        	$result = $customer->create($user);
        	if ($result < 0) {
    			$error++;
    			$error_messages[] = $weblangs->trans("errorOccurred");
    		}
        	$rowid_soc = $result;
        
            if ($error == 0) {
    			// Add  groups
    			$ret_cat = $customer->setCategories($marketplace_third_parties_category, 'customer');
    			if ($ret_cat < 0) {
    				$error++;
    				$error_messages[] = $weblangs->trans("errorOccurred");
    			}
    
    
    			// Add default contact
    			$customer->name_bis = $customer_lastname;
    			$customer->email = $customer_email;
    			$customer->firstname = $customer_firstname;
    			$customer->address = $customer_address;
    			$customer->town = $customer_city;
        	    $customer->zip = $customer_postalcode;
    			$customer->country_id = $customer_country;
    
            	$customer->ip = getUserRemoteIP();

    			$ret_contact = $customer->create_individual($user);
    			if ($ret_contact < 0) {
    				$error++;
    				$error_messages[] = $weblangs->trans("errorOccurred");
    			} else {
    			    $currentContactId = $ret_contact;
    			}
    
    
    			// Add connection credentials for a specific website	
    			if(!empty($id_website)) {
    				$societeaccount = new SocieteAccount($db);
    				$societeaccount->login = $customer_email;
    				$societeaccount->pass_encoding = "dolibarr";
    				$societeaccount->pass = $customer_passwd;
    				$societeaccount->fk_soc = $rowid_soc;
    				$societeaccount->fk_website = $id_website;
    				$societeaccount->site = "dolibarr_website";
    				$societeaccount->status = "1";
		        	$societeaccount->ip = getUserRemoteIP();

    				$ret_account = $societeaccount->create($user);
    				if ($ret_account < 0) {
    					$error++;
    					$error_messages[] = $weblangs->trans("errorOccurred");
    				} else {
    					$id_user = $ret_account;
    					
    					// Link contact to account
						$sql = 'UPDATE ' . MAIN_DB_PREFIX . "socpeople  SET ref_ext = '" . $db->escape($id_user) . "', note_private = 'Marketplace contact for website account ID : " . $id_user . "' WHERE rowid = " . ((int) $currentContactId);
						$db->query($sql);
    				}
    			}
    		}
    		
    		if ($error == 0) {
    		    $db->commit();
            	
            	// Send welcome email
    		    $substitutionarray = array(
		            '__USER_NAME__' => $customer->name
		        );
            	marketplace_send_email(getDolGlobalInt("MARKETPLACE_WELCOME_EMAIL_TEMPLATE"), 'thirdparty', $societeaccount, $societeaccount->login, $substitutionarray);
            	

                // Set session after having created the thirdparty            	
            	if(isset($_SESSION['user'])){  //if session var already exist
                    unset($_SESSION['user']);
                }

                $_SESSION['user']['id_user'] = $id_user;
                $_SESSION['user']['socid'] = $rowid_soc;
                $_SESSION['user']['email'] = $customer_email;
                $_SESSION['user']['pseudo'] = $customer->name;
                
                if ($back == 'payement') {
                    redirectToContainer('payment');
                }
                redirectToContainer('myaccount');
            } else {
            	$db->rollback();
            }
        }
    		
    }
?>

<?php
    $back = GETPOST('back');
?>
<div class="col-xs-12 col-sm-7">
    <?php if (!empty(getDolGlobalInt("MARKETPLACE_GOOGLE_RECAPTCHA_REGISTER_FORM"))): ?>
        <script src="https://www.google.com/recaptcha/api.js?render=<?php print getDolGlobalString("MARKETPLACE_GOOGLE_RECAPTCHA_SITE_KEY"); ?>"></script>
    <?php endif ?>
	<form action="login-register.php" method="post" id="account-creation_form" class="std box">
		<div class="account_creation">
			<h3 class="page-subheading"><?php print $weblangs->trans("accountCreation"); ?></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 $value; ?></li>
                    	<?php endforeach ?>
            		</ol>
            	</div>
        	<?php endif ?>
        	
			<div class="required form-group">
				<label for="customer_firstname"><?php print $weblangs->trans("Firstname"); ?> <sup>*</sup></label>
				<input type="text" class="is_required validate form-control"id="firstname" name="firstname" value="<?php if (isset($customer_firstname)){print $customer_firstname;} ?>">
			</div>
			<div class="required form-group">
				<label for="customer_lastname"><?php print $weblangs->trans("Lastname"); ?> <sup>*</sup></label>
				<input type="text" class="is_required validate form-control" id="lastname" name="lastname" value="<?php if (isset($customer_lastname)){print $customer_lastname;} ?>">
			</div>
			<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" id="email" name="email" value="<?php if (isset($customer_email)){print $customer_email;} ?>">
			</div>
			<div class="required password form-group">
				<label for="passwd"><?php print $weblangs->trans("Password"); ?> <sup>*</sup></label>
				<input type="password" class="is_required validate form-control" name="passwd" id="passwd" autocomplete="new-password" value="<?php if (isset($customer_passwd)){print $customer_passwd;} ?>">
			</div>
		</div>
		<div class="account_creation">
			<h3 class="page-subheading page-subheading-login"><?php print $weblangs->trans("yourBillingInformation"); ?></h3>
			
			<div class="required form-group">
				<label for="customer_lastname"><?php print $weblangs->trans("Address"); ?> <sup>*</sup></label>
				<input type="text" class="is_required validate form-control" id="Address" name="address" value="<?php if (isset($customer_address)){print $customer_address;} ?>">
			</div>
			<div class="required form-group">
				<label for="customer_lastname"><?php print $weblangs->trans("Town"); ?> <sup>*</sup></label>
				<input type="text" class="validate form-control" id="City" name="city" value="<?php if (isset($customer_city)){print $customer_city;} ?>">
			</div>
			<div class="required form-group">
				<label for="customer_lastname"><?php print $weblangs->trans("Zip"); ?> <sup>*</sup></label>
				<input type="text" class="validate form-control" id="Postalcode" name="postalcode" value="<?php if (isset($customer_postalcode)){print $customer_postalcode;} ?>">
			</div>
			<div class="required form-group">
    			<label for="email"><?php print $weblangs->trans("Country"); ?> <sup>*</sup></label>
			    <?php print $form->select_country(GETPOSTISSET('country_id') ? GETPOST('country_id') : '', 'country_id', '', 0, 'form-control'); ?>
			</div>
			
			<p class="form-group">
				<label for=""><?php print $weblangs->trans("Company"); ?></label>
				<input type="text" class="form-control" id="company" name="company" value="<?php if (isset($customer_company)){print $customer_company;} ?>">
			</p>
			<p class="form-group">
				<label for="siret"><?php print $weblangs->trans("MarketPlaceBusinessNumber"); ?></label>
				<input type="text" class="form-control" id="siret" name="siret" value="<?php if (isset($customer_siret)){print $customer_siret;} ?>">
			</p>
			<p class="form-group">
				<label for="tin"><?php print $weblangs->trans("MarketPlaceTIN"); ?></label>
				<input type="text" class="form-control" id="tin" name="tin" value="<?php if (isset($customer_tin)){print $customer_tin;} ?>">
			</p>
			
		</div>
		<input type="hidden" name="action" value="register">
		<input type="hidden" name="back" value="<?php print $back; ?>">
		
		<?php if (!empty(getDolGlobalInt("MARKETPLACE_GOOGLE_RECAPTCHA_REGISTER_FORM"))): ?>
            <input type="hidden" name="g-recaptcha-response" id="g-recaptcha-response">
        <?php endif ?>
        
		<div class="submit clearfix">
			<hr>
			<button type="submit" name="submitAccount" id="submitAccount" class="btn btn-default button button-medium">
				<span><?php print $weblangs->trans("register"); ?> <i class="icon-chevron-right right"></i></span>
			</button>
			<p class="pull-right"><span><sup>*</sup> <?php print $weblangs->trans("requiredField"); ?></span></p>
		</div>
	</form>
	
	<?php if (!empty(getDolGlobalInt("MARKETPLACE_GOOGLE_RECAPTCHA_REGISTER_FORM"))): ?>
        <script>
            grecaptcha.ready(function () {
                grecaptcha.execute('<?php print getDolGlobalString("MARKETPLACE_GOOGLE_RECAPTCHA_SITE_KEY"); ?>', { action: 'submit' }).then(function (token) {
                    document.getElementById('g-recaptcha-response').value = token;
                });
            });
        </script>
    <?php endif ?>
</div>