<?php
    require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
    $form = new Form($db);
?>
<?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/modGeneratePassPerso.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_country = GETPOSTINT('country_id');
        $customer_company = GETPOST('company');
        $customer_siret = GETPOST('siret');
        $customer_tin = GETPOST('tin');
        $back = GETPOST('back');
        
        $error = 0;
        $error_messages = array();
        
        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 = '". $customer_email ."' ";
        $sql .= "and lsa.fk_website = ". $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->trans("firstname"));
    	}
    	
    	if (ctype_alpha(str_replace(array("\n", "\t", ' '), '', $customer_firstname)) === false) {
    	    $error++;
            $error_messages[] = $weblangs->trans("firstnameContainsLettersOnly");
        }
    	
    	if (empty($customer_lastname)) {
    		$error++;
    		$error_messages[] = $weblangs->trans("fieldRequired", $weblangs->trans("lastname"));
    	}
    	
    	if (ctype_alpha(str_replace(array("\n", "\t", ' '), '', $customer_lastname)) === false) {
    	    $error++;
            $error_messages[] = $weblangs->trans("lastnameContainsLettersOnly");
        }
    	
    	$check_pass = new modGeneratePassPerso($db, $conf, $langs, $user);
    	$is_valid = $check_pass->validatePassword($customer_passwd);
    	if(!$is_valid){
    	    $error++;
    		$error_messages[] = $weblangs->trans("passwordCriteria");
    	}
    	
    	if (empty($customer_address)) {
    		$error++;
    		$error_messages[] = $weblangs->trans("fieldRequired", $weblangs->trans("address"));
    	}
    	
    	if (empty($customer_country)) {
    		$error++;
    		$error_messages[] = $weblangs->trans("fieldRequired", $weblangs->trans("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->address = $customer_address;
        	$customer->country_id = $customer_country;
        
        	$customer->name_alias = '';
        	$customer->idprof2 = $customer_siret;
        	$customer->idprof3 = $customer_tin;
        	
        	// TODO if a valid siret set define customer as a company
        
        	$customer->client = '2';
        	$customer->code_client = 'auto';
        
        	$customer->fournisseur = '0';
        	$customer->code_fournisseur = 'auto';
        
        	//$customer->default_lang = $obj->dol_lang_code;
        	
        	$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->country_id = $customer_country;
    
    			$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";
    				$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 = '" . $id_user . "', note_private = 'Marketplace contact for 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);
            	
            	
            	session_start(); // start session
            	if(isset($_SESSION['user'])){  //if session var already exist
                    unset($_SESSION['user']);
                }
        
                $_SESSION['user']['id_user'] = $id_user;
                $_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">
	<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" value="<?php if (isset($customer_passwd)){print $customer_passwd;} ?>">
			</div>
			<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="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>


		</div>
		<div class="account_creation">
			<h3 class="page-subheading page-subheading-login"><?php print $weblangs->trans("yourCompanyInformation"); ?></h3>
			<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("siret"); ?></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("taxIdentificationNumber"); ?></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; ?>">
		<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 required"><span><sup>*</sup> <?php print $weblangs->trans("requiredField"); ?></span></p>
		</div>
	</form>
</div>