<?php // BEGIN PHP
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/modules/security/generate/modGeneratePassPerso.class.php';

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

// If not login redirect to login.
if(empty($_SESSION['user']['id_user'])){
    redirectToContainer('login-register');
}

if (!empty(GETPOST('email'))) {
    $customer_firstname = GETPOST('firstname');
    $customer_lastname = GETPOST('lastname');
    $customer_email = GETPOST('email');
    $customer_passwd = GETPOST('passwd');
    $customer_new_passwd = GETPOST('new_passwd');
    $customer_address = GETPOST('address');
    $customer_country = GETPOSTINT('country_id');
    $customer_company = GETPOST('company');
    $customer_siret = GETPOST('siret');
    $customer_tin = GETPOST('tin');
    $contact_id = GETPOST('contact');
    $customer_id = GETPOST('customer');
        
    $error = 0;
    $error_messages = array();
	
	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");
    }
	
	if (!empty($customer_passwd) && !empty($customer_new_passwd)) {
	    $id_website = $website->id;
        
        $sql  = "select lsa.rowid, lsa.pass_encoding, lsa.pass_crypted, 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.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)) {
    		if ($objsql->pass_encoding == 'dolibarr') {
    			$correct_password = dol_verifyHash ($customer_passwd, $objsql->pass_crypted);
    		}
    		if ($objsql->pass_encoding == 'dolistore') {
    		    $dolistore_key = getDolGlobalString("MARKETPLACE_SECRET_KEY");
    		    $to_check = md5($dolistore_key.$customer_passwd);
    		    if ($objsql->pass_crypted === $to_check){
    		        $correct_password = 1;
    		    }
    		}
        }else{
            $error++;
    		$error_messages[] = $weblangs->trans("noValidAccount");
        }
        
        if ($correct_password) {
            $check_pass = new modGeneratePassPerso($db, $conf, $langs, $user);
        	$is_valid = $check_pass->validatePassword($customer_new_passwd);
        	if(!$is_valid){
        	    $error++;
        		$error_messages[] = $weblangs->trans("newPasswordCriteria");
        	}
        } else {
            $error++;
		    $error_messages[] = $weblangs->trans("currentPasswordIncorrect");
        }
	} else {
	    if (!empty($customer_passwd) || !empty($customer_new_passwd)) {
            $error++;
		    $error_messages[] = $weblangs->trans("bothCurrentNewPassRequired");
    	}
	}
	
	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;
    
    	$customer->client = '2';
    	$customer->code_client = 'auto';
    
    	$customer->fournisseur = '0';
    	$customer->code_fournisseur = 'auto';
    
    	//$customer->default_lang = $obj->dol_lang_code;
    	
    	$result = $customer->update($customer_id, $user);
    	if ($result < 0) {
			$error++;
			$error_messages[] = $weblangs->trans("errorOccurred");
		}
    
        if ($error == 0) {
			// Add  groups
			/*$ret_cat = $customer->setCategories($marketplace_third_parties_category, 'customer');
			if ($ret_cat < 0) {
				$error++;
			}*/


			// Add default contact
			$contact = new Contact($db);
			$contact->name_bis = $customer_lastname;
			$contact->email = $customer_email;
			$contact->firstname = $customer_firstname;
			$contact->lastname = $customer_lastname;
			$contact->address = $customer_address;
			$contact->country_id = $customer_country;

			$ret_contact = $contact->update($contact_id, $user);
			if ($ret_contact < 0) {
				$error++;
			} else {
			}


			// Add connection credentials for a specific website	
			if(!empty($id_website)) {
			    // Load user and its permissions
                $result = $user->fetch('', 'admin');	// Load user for login 'admin'. Comment line to run as anonymous user.
                if (!$result > 0) {
                	$error++;
			        $error_messages[] = $weblangs->trans("errorOccurred");
                }
                $user->getrights();
    
				$societeaccount = new SocieteAccount($db);
				$societeaccount->login = $customer_email;
				$societeaccount->pass_encoding = "dolibarr";
				$societeaccount->id = $_SESSION['user']['id_user'];
				$societeaccount->pass_crypted = dol_hash($customer_new_passwd);
				$societeaccount->fk_soc = $customer_id;
				$societeaccount->fk_website = $id_website;
				$societeaccount->site = "dolibarr_website";
				$societeaccount->status = "1";
				$ret_account = $societeaccount->update($user);
				if ($ret_account < 0) {
					$error++;
				} else {
					$id_user = $ret_account;
				}
			}
		}
		
		if ($error == 0) {
        	$db->commit();
        } else {
        	$db->rollback();
        }
    }
		
}


// Get customer ID.
$user_id = $_SESSION['user']['id_user'];
$customer_account = new SocieteAccount($db);
$result = $customer_account->fetch($user_id);
$customer_id = $customer_account->fk_soc;

// Get customer object.
$customer = new Societe($db);
$result = $customer->fetch($customer_id);

if($result > 0) {
    
    $id_website = $website->id;
    $marketplace_third_parties_category = getDolGlobalInt("MARKETPLACE_PROSPECTCUSTOMER_ID");
    
    // Get account info
    $cContacts = $customer->contact_array_objects();
    foreach ($cContacts as $cContact) {
        if ($cContact->email == $customer_account->login) {
            $customer_firstname = $cContact->firstname;
            $customer_lastname = $cContact->lastname;
            $customer_email = $cContact->email;
            $customer_address = $cContact->address;
            $customer_country = $cContact->country_id;
            $contact_id = $cContact->id;
        }
    }
    $customer_company = $customer->name;
    $customer_siret = $customer->idprof2;
    $customer_tin = $customer->idprof3;

}

$form = new Form($db);

// END PHP 
?>
<div id="page">
  <div class="header-container">
    <?php 
        includeContainer('header');
        $__PAGE__TITLE__ = $weblangs->trans("accountInformationPageTitle");
    ?>
  </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> <a href="myaccount.php" title="<?php print $weblangs->trans("myAccount"); ?>" data-gg=""><?php print $weblangs->trans("myAccount"); ?></a>
        	<span class="navigation-pipe">&gt;</span> <?php print $weblangs->trans("yourPersonalInfo"); ?>
        </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'); ?>
        <div id="center_column" class="center_column col-xs-12 col-sm-9">
          <div class="clearfix">
                <div class="row">
                    <div class="col-xs-12">
                    	<form action="" method="post" id="account-creation_form" class="std box">
                    		<div class="account_creation">
                    			<h3 class="page-subheading"><?php print $weblangs->trans("yourPersonalInfo"); ?></h3>
                    			<p class="info-title">
                                    <?php print $weblangs->trans("beSureToUpdateProfil"); ?>
                                </p>
                                
                                <p class="required">
                                    <sup>*</sup> <?php print $weblangs->trans("requiredField"); ?>
                                </p>
        
                    			<?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="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("currentPasswd"); ?> <sup>*</sup></label>
                    				<input type="password" class="is_required validate form-control" name="passwd" id="passwd" value="">
                    			</div>
                    			<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" name="new_passwd" id="passwd" value="">
                    			</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($customer_country ? $customer_country : '', '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; ?>">
                    		<input type="hidden" name="contact" value="<?php print $contact_id; ?>">
                    		<input type="hidden" name="customer" value="<?php print $customer_id; ?>">
                    		<div class="submit clearfix">
                    			<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>
                    			<p class="pull-right required"><span><sup>*</sup> <?php print $weblangs->trans("requiredField"); ?></span></p>
                    		</div>
                    	</form>
                    </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>