<?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/modules/security/generate/modGeneratePassStandard.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');
}

// 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;
$id_website = $website->id;

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

$weblangs->loadLangs(array("main", "companies", "website", "marketplace@marketplace"));

$__PAGE__TITLE__ = $weblangs->trans("accountInformationPageTitle");

// Action to update
if (GETPOST('email')) {
    $customer_firstname = GETPOST('firstname');
    $customer_lastname = GETPOST('lastname');
    $customer_email = GETPOST('email');
    $customer_lang_code = GETPOST('lang_code');
    
    $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');

    
    $customer_passwd = GETPOST('passwd');
    $customer_new_passwd = GETPOST('new_passwd');

    // From logged session    
    $customer_id = $_SESSION['user']['socid'];
    $contact_id = GETPOST('contact');   // TODO This should come from the session

    $error = 0;
    $error_messages = array();
	
	if (empty($customer_firstname)) {
		$error++;
		$error_messages[] = $weblangs->trans("ErrorFieldRequired", $weblangs->transnoentitiesnoconv("Firstname"));
	} elseif (!preg_match('/^[a-zA-ZÀ-ÖØ-öø-ÿ\- ]+$/u', $customer_firstname)) {
	    $error++;
        $error_messages[] = $weblangs->trans("firstnameContainsLettersOnly");
    }
	
	if (empty($customer_lastname)) {
		$error++;
		$error_messages[] = $weblangs->trans("ErrorFieldRequired", $weblangs->transnoentitiesnoconv("Lastname"));
	} elseif (!preg_match('/^[a-zA-ZÀ-ÖØ-öø-ÿ\- ]+$/u', $customer_lastname)) {
	    $error++;
        $error_messages[] = $weblangs->trans("lastnameContainsLettersOnly");
    }
	

	if (!empty($customer_passwd) && !empty($customer_new_passwd)) {
        $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.rowid = ". ((int) $user_id);
        
        $result = $db->query($sql);
		$objsql = $db->fetch_object($result);
		
        if (!empty($objsql)) {
    		if ($objsql->pass_encoding != 'dolistore') {
    			$correct_password = dol_verifyHash($customer_passwd, $objsql->pass_crypted, $objsql->pass_encoding);
    		} else {
    		    $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 modGeneratePassStandard($db, $conf, $langs, $user);
        	$is_valid = $check_pass->validatePassword($customer_new_passwd);
        	if (!$is_valid) {
        	    $error++;
        	    $weblangs->load("other");
        		$error_messages[] = $weblangs->trans("YourPasswordMustHaveAtLeastXChars", (string) $check_pass->length2);
        	}            
        } else {
            $customer_account = new SocieteAccount($db);
            $result = $customer_account->fetch($user_id);

            $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->transnoentitiesnoconv("Address"));
	}
	
    if (!preg_match('/^[a-z0-9\.\- ]+$/i', $customer_postalcode)) {
        $error++;
        $error_messages[] = $weblangs->trans("postalCodeContainsDigitsOnly");
    }
	
	if (empty($customer_country)) {
		$error++;
		$error_messages[] = $weblangs->trans("ErrorFieldRequired", $weblangs->transnoentitiesnoconv("Country"));
	}
    
    if ($error == 0) {
        // Start of transaction
        $db->begin();

        $customer = new Societe($db);
        $result = $customer->fetch($customer_id);
        if ($result <= 0) {
            print "Third party not found using _SESSION['user']['socid']";
            exit;
        }
    
    	if (!empty($customer_company)) {
    		$customer->name = $customer_company;
    	} elseif (empty($customer->name)) {
    		$customer->name = dolGetFirstLastname($customer_firstname, $customer_lastname);
    	}

        if ($customer_email) {
    	    $customer->email = $customer_email;
        }

    	$customer->address = $customer_address;
    	$customer->town = $customer_city;
        $customer->zip = $customer_postalcode;
    	$customer->country_id = $customer_country;
    
        if (GETPOSTISSET('siret')) {
    	    $customer->idprof2 = $customer_siret;
        }
    	if (GETPOSTISSET('tin')) {
    	    $customer->tva_intra = $customer_tin;
    	}

        if ($customer_lang_code){
    	    $customer->default_lang = $customer_lang_code;
        }
    	
    	$result = $customer->update($customer_id, $user);
    	if ($result < 0) {
			$error++;
			$error_messages[] = $weblangs->trans("errorOccurred");
		}
    
        if ($error == 0) {
			// Update contact (but only if linked to a contact)
			if ($contact_id > 0) {
    			$contact = new Contact($db);
    			$result = $contact->fetch($contact_id);
    			if ($result <= 0) {
    			    print "Contact not found using contact_id";
                    exit;
    			}

    			//$contact->name_bis = $customer_lastname;
    			if ($customer_email) {
    			    $contact->email = $customer_email;
    			}
    
    			$contact->firstname = $customer_firstname;
    			$contact->lastname = $customer_lastname;
    			$contact->address = $customer_address;
    			$contact->town = $customer_city;
    			$contact->zip = $customer_postalcode;
    			$contact->country_id = $customer_country;
    
    			$ret_contact = $contact->update($contact_id, $user);
    			if ($ret_contact < 0) {
    				$error++;
    			}
			}


			// Now update the login account to log on the 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->fetch($_SESSION['user']['id_user']);
				
				if ($societeaccount->id > 0) {
    				$societeaccount->login = $customer_email;

    				if ($customer_new_passwd) {
    				    $societeaccount->pass_encoding = "md5";
    				    $societeaccount->pass_crypted = dol_hash($customer_new_passwd, 'md5');
    				}

    				$ret_account = $societeaccount->update($user);
    				if ($ret_account < 0) {
    					$error++;
    				} else {
    				    // Update is ok, we reload the website account
    				    $customer_account = new SocieteAccount($db);
                        $result = $customer_account->fetch($_SESSION['user']['id_user']);
    				}
				}
			}
		}
		
		if ($error == 0) {
        	$db->commit();
        } else {
        	$db->rollback();
        }
    }
		
}


if ($result > 0) {
    $id_website = $website->id;
    $marketplace_third_parties_category = getDolGlobalInt("MARKETPLACE_PROSPECTCUSTOMER_ID");
    
    // Get contact record if we found one with same email.
    $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;
            $contact_id = $cContact->id;
        }
    }
    
    $customer_company = $customer->name;
    $customer_address = $customer->address;
    $customer_city = $customer->town;
    $customer_postalcode = $customer->zip;
    $customer_country = $customer->country_id;
    $customer_siret = $customer->idprof2;
    $customer_tin = $customer->tva_intra;
}

$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> <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>
                                
                                <br>
                                
                    			<?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 } ?>
                            	
                            	[EN] Warning - Update of firstname, lastname are not supported yet !!!!<br>
                            	[FR] Attention - La mise à jour du nom, prénom de contact n'est pas encore géré !!!!<br><br>
                            	
                    			<div class="required form-group">
                    				<label for="email"><?php print $weblangs->trans("Login").'/'.$weblangs->trans("Email"); ?> <sup>*</sup></label>
                    				<input type="text" class="is_required validate form-control" id="email" name="email" value="<?php if (isset($customer_account->login)){print $customer_account->login;} ?>">
                    			</div>
                    			<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>
                    		
                    		<br>
                    		
                    		<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($customer_country ? $customer_country : '', '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>
                    		
                    		<br>
                    		
                    		<div class="account_creation">
                    			<h3 class="page-subheading page-subheading-login"><?php print $weblangs->trans("Password"); ?></h3>
                    		
                    			<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="" autocomplete="new-password">
                    			</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="" autocomplete="new-password">
                    			</div>
                            </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"><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>