<?php

include_once "authentication.php";
if(!$rights['service']['add']) echo "<script>window.location.replace('accueil.php')</script>";


if(isset($_POST['customer_name'])){

	$ticket_dept = 23;
	$ticket_assign = 0;
	
	#print_r($_POST); exit;
	
		
	
	if($_POST['fibre'] == 1){
		
		if($_POST['fibre_id'] == 0) die("<div class='alert alert-danger'>La validation de l'adresse fibre n'a pas été faite. Recommence.</div>");
			
		$q_fibre_info = "SELECT `terrain`, `rue`, `ville` FROM `fibre` WHERE `id` = '{$_POST['fibre_id']}'";
		$res_fibre_info = $sql->query($q_fibre_info);
		$row_fibre_info = $res_fibre_info->fetch_array();
		
		if($res_fibre_info->num_rows != 1) die("<div class='alert alert-danger'>Adresse fibre introuvé ou non unique</div>");
		
	}

	
	$q_delivery = "UPDATE `$mydbName`.`delivery` SET `email` = '{$_POST['email']}' WHERE `id` = '{$_POST['delivery_id']}'";
	$sql->query($q_delivery);
	
	#print_r($_POST); echo "<br><br>";

	$date = mktime(0,0,0,date('n'),date('d'),date('Y'));
	$time_now = time();

	$subject = change_quote($_POST['city'] . " | " . $_POST['customer_name']);
	if($_POST['select_install'] == 584) $subject = change_quote("Lac des pins | " . $_POST['customer_name']);
	
	$tmp = str_split($_POST['customer_id'],5);
	$customer_id = (is_numeric($_POST['customer_id'])) ? implode(' ',$tmp) : $_POST['customer_id'];
	
	$ticket_msg = "Nom: ".$_POST['customer_name']."\nID: {$customer_id}\nEmail: {$_POST['email']}\n\n";
	$ticket_msg .= "Adresse: " . "{$_POST['address']} {$_POST['city']}" . "\nTéléphone: {$_POST['phone']}\n\n";
	
	
	$d = explode('-',$_POST['date_install']);
	$date = mktime(0,0,0,$d[1],$d[0],$d[2]);
	
	
	$d = explode('-',$_POST['date_invoice']);
	$date_invoice = mktime(0,0,0,$d[1],$d[0],$d[2]);
	
	
	## block install
	
	if(isset($_POST['chk_install'])){
	
		
		$ticket_assign = 3301;
		
		if($_POST['fibre'] == 0)
			$ticket_dept = 12;
		else
			$ticket_dept = 27;
		
		if($_POST['select_install'] == 584) $ticket_dept = 27; //camping
	
		$ticket_msg .= "Installation: {$_POST['install_price']}\n";
		if($_POST['install_credit'] != '') $ticket_msg .= "Crédit: {$_POST['install_credit']}$\n";
	
		$ticket_msg .= "\n";
	
	}
	
	$aCombo = array();
	
	## block service
	
	$service_list = "";

	if(isset($_POST['chk_product'])){
	
		$sku = $_POST['sku']; //product id... not sku -_-'
		$desc = $_POST['desc'];
		$amount = $_POST['amount'];
		$quota_day = $_POST['quota_day'];
		$quota_night = $_POST['quota_night'];
		$contrat = $_POST['contrat'];
		$duration = $_POST['duration'];
		
		
		$ticket_msg .= "Service: \n";
		
		$count_service = 0;
		$fi_count = 0;
		
		$premier_fi_id = 0;
		
		$set_comm = 0;
		
		foreach($sku AS $i=>$value){
		
			//$sku[$i] -- $desc[$i] -- $amount[$i] -- $contrat[$i] -- $duration[$i]
			
			if($sku[$i] == 'default') continue;
			
			$res_prod_comm = $sql->query("SELECT * FROM `product` WHERE `id` = '{$sku[$i]}'");
			$row_prod_comm = $res_prod_comm->fetch_array();
			if($row_prod_comm['commercial'] == 1) $set_comm = 1;
			
			if($row_prod_comm['combo_ready'] AND $amount[$i] > 0) $aCombo['internet'] = 1;
			
			
			$result_pID = $sql->query("SHOW TABLE STATUS LIKE 'service';");
			$row_pID = $result_pID->fetch_array();
			$predic_service_id =  $row_pID['Auto_increment'];
			
			$fi = ($sku[$i] == '7' OR $sku[$i] == '8' OR $sku[$i] == '88' OR $sku[$i] == '117') ? 0 : 1;
			
			$price = ($sku[$i] == '7' OR $sku[$i] == '88') ? abs($amount[$i]) * -1 : $amount[$i];
			
			if($contrat[$i] != ''){
				$contract_month = $contrat[$i];
				$date_end_contract = date("U", strtotime("+$contract_month months",$date_invoice));
			}
			else
				$date_end_contract = 'NULL';

			if($duration[$i] != ''){
				$actif_month = $duration[$i];
				$date_actif_until = mktime(0,0,0,date("n", strtotime("+$actif_month months",$date_invoice)),1,date("Y", strtotime("+$actif_month months",$date_invoice)));
			}
			else
				$date_actif_until = 'NULL';
				
			$day = $quota_day[$i] * 1073741824;
			$night = $quota_night[$i] * 1073741824;
			
			$hijack = $_POST['hij'][$i];
			
			$raduser = $radpwd = '';
			$radconso = 0;
			if($price >= 0){
				if($row_prod_comm['type'] == 1 or $row_prod_comm['type'] == 2){
					$raduser = "tci$predic_service_id";
					for($p=1; $p<=8; $p++){
						$radpwd.=rand(0,9);
					}				
				}
			}
			
			if($raduser != ''){
				$q_radcheck = "INSERT INTO `radcheck` (`username`,`attribute`,`op`,`value`) VALUES ('$raduser','Cleartext-Password',':=','$radpwd')";
				$q_radgroup = "INSERT INTO `radusergroup` (`username`,`groupname`,`priority`) VALUES ('$raduser','residentiel','1')";
				
				
				$sql_vpnradius = new mysqli('10.5.2.25', 'facturation', 'N0HAk4u$', 'radiusdb');
				$sql_vpnradius->query($q_radcheck);
				$sql_vpnradius->query($q_radgroup);
				$sql_vpnradius->close();
				
				$radconso = 1;
			}
			
			$recurrence = ($_POST['select_install'] == 584) ? 5 : 2;
		
			$q_prod = "INSERT INTO `$mydbName`.`service` (`date_orig`, `date_next_invoice`, `delivery_id`, `product_id`, `payment_recurrence`, `status`, `hijack`, `hijack_price`, `hijack_desc`, `hijack_quota_day`, `hijack_quota_night`, `date_end_contract`, `actif_until`, `forfait_internet`, `radius_user`, `radius_pwd`, `radius_conso`) VALUES ";
			$q_prod .= "('$date','$date_invoice','{$_POST['delivery_id']}','{$sku[$i]}','$recurrence','0','$hijack','$price','".change_quote($desc[$i])."','$day','$night',$date_end_contract,$date_actif_until,'$fi','$raduser','$radpwd','$radconso')";
			$sql->query($q_prod);
			#echo "$q_prod <br>";
			
			if($fi){
					
				$snap_date = mktime(0,0,0,date('n'),1,date('Y'));
				$q_insert = "INSERT INTO `$mydbName`.`service_snapshot` (`date`, `account_id`, `service_id`, `quota_day`, `quota_night`) VALUES ('$snap_date','{$_POST['account_id']}','$predic_service_id','$day','$night');";
				$sql->query($q_insert);
			
				if($fi_count == 0){
				
					if($_POST['client_password'] == ''){
						$cli_password = enchsetenev("targo$predic_service_id",10000);
					
						$q_update_password = "UPDATE `$mydbName`.`account` SET `password` = '$cli_password' WHERE `id` = '{$_POST['account_id']}'";
						$sql->query($q_update_password);
					}
					
					$premier_fi_id = $predic_service_id;
					$fi_count++;
				
				}			
			}			
		
			$service_list .= "$predic_service_id;";
		
			$ticket_msg .= "ID: $predic_service_id, {$desc[$i]}, $price $, {$quota_day[$i]} / {$quota_night[$i]} go.";		
			
			if($contrat[$i] != '') $ticket_msg .= "Fin du contrat: " . date("d-m-Y", $date_end_contract) . ". ";
			if($duration[$i] != '') $ticket_msg .= "Actif jusqu&#039;au: " . date("d-m-Y", $date_actif_until) . ". ";
			if($raduser != '')  $ticket_msg .= "\n - Radius: $raduser / $radpwd";
				
			$ticket_msg .= "\n";
			
			
			if($count_service == 0){
			
				$sql_cp = new mysqli($cpHost, $cpUser, $cpPass, $cpName);
				
				$query_cp = "INSERT INTO `cportal`.`valid_user` (`customer_id`, `service_id`) VALUES ('{$_POST['customer_id']}', '$predic_service_id');";
				$sql_cp->query($query_cp);
				
				$sql_cp->close();
				
				$count_service++;
			}
		
		
		}
		
		if($set_comm == 1) $sql->query("UPDATE `account` SET `commercial` = 1 WHERE `id` = '{$_POST['account_id']}'");
		
		$ticket_msg .= "\n";
		
	}
	
	
	## block phone
	
	if(isset($_POST['chk_phone'])){
		
		$aCombo['phone'] = 1;
	
		$q_tel = "SELECT `name` FROM `$mydbName`.`product_translate` WHERE `product_id` = '54' AND `language_id` = 'francais'";
		$res_tel = $sql->query($q_tel);
		$row_tel = $res_tel->fetch_array();
	
		$result_pID = $sql->query("SHOW TABLE STATUS LIKE 'service';");
		$row_pID = $result_pID->fetch_array();
		$predic_service_id =  $row_pID['Auto_increment'];
		$service_list .= "$predic_service_id;";
	
		$q_prod = "INSERT INTO `$mydbName`.`service` (`date_orig`, `date_next_invoice`, `delivery_id`, `product_id`, `payment_recurrence`, `status`, `hijack`, `hijack_price`, `hijack_desc`, `hijack_quota_day`, `hijack_quota_night`, `date_end_contract`, `actif_until`, `forfait_internet`) VALUES ";
		$q_prod .= "('$date','$date_invoice','{$_POST['delivery_id']}','54','2','0','1','{$_POST['price_tel_men']}','{$row_tel['name']}','0','0',NULL,NULL,'0')";
		$sql->query($q_prod);
		
		
		
		#echo "$q_prod <br>";
		
		if(isset($_POST['chk_tel_trans'])){
		
			$trans_num = str_replace('-','',$_POST['trans_number']);
			$trans_num = str_replace(' ','',$trans_num);
			$trans_num = str_replace('(','',$trans_num);
			$trans_num = str_replace(')','',$trans_num);
			
			$q_serv_tel = "INSERT INTO `$mydbName`.`phone` (`service_id`, `phone_num`) VALUES ('$predic_service_id','$trans_num');";
			$sql->query($q_serv_tel);
		}

		$ticket_msg .= "Téléphone:\n";
		$ticket_msg .= "Prix: {$_POST['price_tel_men']}$ ";

		if($_POST['credit_telepmens'] != 0){
			$price = abs($_POST['credit_telepmens']) * -1;
			
			if($_POST['credit_telepmens_time'] != ''){
				$actif_month = $_POST['credit_telepmens_time'];
				$date_actif_until = mktime(0,0,0,date("n", strtotime("+$actif_month months",$date_invoice)),1,date("Y", strtotime("+$actif_month months",$date_invoice)));
			}
			else
				$date_actif_until = 'NULL';
				
			$result_pID = $sql->query("SHOW TABLE STATUS LIKE 'service';");
			$row_pID = $result_pID->fetch_array();
			$predic_service_id =  $row_pID['Auto_increment'];
			$service_list .= "$predic_service_id;";
			
			$q_prod = "INSERT INTO `$mydbName`.`service` (`date_orig`, `date_next_invoice`, `delivery_id`, `product_id`, `payment_recurrence`, `status`, `hijack`, `hijack_price`, `hijack_desc`, `hijack_quota_day`, `hijack_quota_night`, `date_end_contract`, `actif_until`, `forfait_internet`) VALUES ";
			$q_prod .= "('$date','$date_invoice','{$_POST['delivery_id']}','54','2','0','1','$price','Crédit','0','0',NULL,$date_actif_until,'0')";
			$sql->query($q_prod);
			#echo "$q_prod <br>";

			$ticket_msg .= " Crédit de " . abs($_POST['credit_telepmens']) . "$ durant {$_POST['credit_telepmens_time']} mois.";

		}
		
		$q_prod_911 = "INSERT INTO `$mydbName`.`service` (`date_orig`, `date_next_invoice`, `delivery_id`, `product_id`, `payment_recurrence`, `status`, `date_end_contract`, `actif_until`, `forfait_internet`) VALUES ";
		$q_prod_911 .= "('$date','$date_invoice','{$_POST['delivery_id']}','52','2','0',NULL,NULL,'0')";
		$sql->query($q_prod_911);
		$id911 = $sql->insert_id;
		$service_list .= "$id911;";
		
		$ticket_msg .= "\n";
		
		if(isset($_POST['chk_tel_act'])) $ticket_msg .= "Activation: {$_POST['price_tel_act']}$ \n";

		if($_POST['opt_num'] == 'nouveau')
			$ticket_msg .= "Nouveau numéro - préférence: {$_POST['opt_pref']} (ne pas oublier d'associer le numéro avec le service lorsque connu)\n";
		else
			$ticket_msg .= "Porter le numéro ({$_POST['trans_number']}): {$_POST['price_tel_trans']}$ \n";
	
	
		$ticket_msg .= "\n";
	}
	
	
	## block tele
	
	if(isset($_POST['chk_tele'])){
		
		
		$sku_tele = $_POST['t_sku']; //product id... not sku -_-'
		$desc_tele = $_POST['t_desc'];
		$amount_tele = $_POST['t_amount'];
		$contrat_tele = $_POST['t_contrat'];
		$duration_tele = $_POST['t_duration'];
		
		$ticket_msg .= "Tele: \n";
			
		foreach($sku_tele AS $i=>$value){
			
			if($sku_tele[$i] == 'default') continue;
			
			$q_prod_tele = "SELECT * FROM `product` WHERE `id` = {$sku_tele[$i]}";
			$res_prod_tele = $sql->query($q_prod_tele);
			$row_prod_tele = $res_prod_tele->fetch_array();
			
			if($row_prod_tele['combo_ready']) $aCombo['tele'] = 1;
			
			$result_pID = $sql->query("SHOW TABLE STATUS LIKE 'service';");
			$row_pID = $result_pID->fetch_array();
			$predic_service_id =  $row_pID['Auto_increment'];
			
			
			
			$price = $amount_tele[$i];
			
			if($contrat_tele[$i] != ''){
				$contract_month = $contrat_tele[$i];
				$date_end_contract = date("U", strtotime("+$contract_month months",$date_invoice));
			}
			else
				$date_end_contract = 'NULL';

			if($duration_tele[$i] != ''){
				$actif_month = $duration_tele[$i];
				$date_actif_until = mktime(0,0,0,date("n", strtotime("+$actif_month months",$date_invoice)),1,date("Y", strtotime("+$actif_month months",$date_invoice)));
			}
			else
				$date_actif_until = 'NULL';
			
			$hijack = $_POST['t_hij'][$i];
			
			$q_prod = "INSERT INTO `$mydbName`.`service` (`date_orig`, `date_next_invoice`, `delivery_id`, `product_id`, `payment_recurrence`, `status`, `hijack`, `hijack_price`, `hijack_desc`, `hijack_quota_day`, `hijack_quota_night`, `date_end_contract`, `actif_until`, `forfait_internet`, `radius_user`, `radius_pwd`) VALUES ";
			$q_prod .= "('$date','$date_invoice','{$_POST['delivery_id']}','{$sku_tele[$i]}','2','0','$hijack','$price','".change_quote($desc_tele[$i])."','0','0',$date_end_contract,$date_actif_until,'0','','')";
			$sql->query($q_prod);
			#echo "$q_prod <br>";
			
		
		
			$service_list .= "$predic_service_id;";
		
			$ticket_msg .= "ID: $predic_service_id, {$desc_tele[$i]}, $price $. ";		
			
			if($contrat_tele[$i] != '') $ticket_msg .= "Fin du contrat: " . date("d-m-Y", $date_end_contract) . ". ";
			if($duration_tele[$i] != '') $ticket_msg .= "Actif jusqu&#039;au: " . date("d-m-Y", $date_actif_until) . ". ";
				
			$ticket_msg .= "\n";
			
		}
		$ticket_msg .= "\n";
	}
	
	
	## add combo prod
	
	switch(count($aCombo)){
		case 2: $combo_id = '556'; $combo_sku = 'RAB2X'; break;
		case 3: $combo_id = '557'; $combo_sku = 'RAB3X'; break;
		case 4: $combo_id = '558'; $combo_sku = 'RAB4X'; break;
		default: $combo_id = '';	
	}
		
	if($combo_id != ''){		
		
		$result_pID = $sql->query("SHOW TABLE STATUS LIKE 'service';");
		$row_pID = $result_pID->fetch_array();
		$predic_service_id =  $row_pID['Auto_increment'];
		
		$q_combo = "INSERT INTO `$mydbName`.`service` (`date_orig`, `date_next_invoice`, `delivery_id`, `product_id`, `payment_recurrence`, `status`) VALUES ";
		$q_combo .= "('$date','$date_invoice','{$_POST['delivery_id']}','$combo_id','2','0')";
		$sql->query($q_combo);
		
		$service_list .= "$predic_service_id;";
		$ticket_msg .= "Ajout de $combo_sku \n";
		
	}	
	
	$ticket_msg .= "\n" . $_POST['info_supp'];	
	
	$service_list = substr($service_list,0,-1);	
	
	$result_aID = $sql->query("SHOW TABLE STATUS LIKE 'bon_travail';");
	$row_aID = $result_aID->fetch_array();
	$bon_id =  $row_aID['Auto_increment'];
	
	$q_bon = "INSERT INTO `$mydbName`.`bon_travail` (`date`, `account_id`) VALUES ('$date', '{$_POST['account_id']}');";
	$sql->query($q_bon);
	
	$wiz_fibre = "";
	$info_fibre = "";
	if($_POST['fibre'] == 1){
		$wiz_fibre = "{$_POST['delivery_id']}|{$_POST['fibre_id']}|$premier_fi_id";
		
		$q_fibre_info = "SELECT * FROM `fibre` WHERE `id` = '{$_POST['fibre_id']}'";
		$res_fibre_info = $sql->query($q_fibre_info);
		$row_fibre_info = $res_fibre_info->fetch_array();
		
		switch($row_fibre_info['tech']){
			case 2: $tech_fibre = "Raisecom"; break;
			case 3: $tech_fibre = "TP-link"; break;
			default: $tech_fibre = "tech inconnu";
		}
		
		$info_fibre = "\n\n<p>Info pour fibre:\n<b>$tech_fibre</b>\nOLT: {$row_fibre_info['info_connect']}\nVille: {$row_fibre_info['ville']}\nRue: {$row_fibre_info['rue']}\nCivique: {$row_fibre_info['terrain']}</p>";
		
		//ticket tech pour installer le boitier
		if($row_fibre_info['boitier_pas_install'] == 1){			
			
			$date_boitier = date('U',strtotime('+1 day'));
			$q_ticket_boitier = "INSERT INTO `ticket` (`account_id`, `subject`, `dept_id`, `open_by`, `assign_to`, `status`, `date_create`, `last_update`, `due_date`) VALUES ";
			$q_ticket_boitier .= "('{$_POST['account_id']}', '{$row_fibre_info['ville']} | Installation boitier', '27', '$userid', '3301', 'open', $time_now, $time_now, $date_boitier)";
			$sql->query($q_ticket_boitier);
			$ticket_boitier = $sql->insert_id;
			$msg_boitier = "Installation pour un client au {$row_fibre_info['terrain']} {$row_fibre_info['rue']} {$row_fibre_info['ville']} prevu pour le " . date('d-m-Y', $date);
			$msg_boitier .= "\nLe boitier a besoin d'être fait au préalable.\nNe pas oublier de mettre a jour la map pour les adresses affectées par cette intervention";
			$msg_boitier = $sql->real_escape_string($msg_boitier);
			$q_boitier_msg = "INSERT INTO `ticket_msg` (`ticket_id`, `staff_id`, `msg`, `date_orig`) VALUES ('$ticket_boitier','$userid','$msg_boitier','$time_now');";
			$sql->query($q_boitier_msg);
		}
	}
	
	$ticket_msg .= $info_fibre;
	
	$result_aID = $sql->query("SHOW TABLE STATUS LIKE 'ticket';");
	$row_aID = $result_aID->fetch_array();
	$ticket_id =  $row_aID['Auto_increment'];
	
	$q_follow = "SELECT * FROM `ticket_dept` WHERE `id` = $ticket_dept";
	$res_follow = $sql->query($q_follow);
	$row_follow = $res_follow->fetch_assoc();
	
	if($row_follow['default_follow'] == 0)
		$follow = "[]";
	else{
		$thisFollower[$row_follow['default_follow']]['child'] = 0;
		$follow = json_encode($thisFollower);
	}	
	
	
	if($_POST['fibre'] > 0){
		
		$q_ticket_fact = "INSERT INTO `ticket` (`account_id`, `subject`, `dept_id`, `open_by`, `assign_to`, `status`, `date_create`, `last_update`) VALUES ";
		$q_ticket_fact .= "('{$_POST['account_id']}', 'validation paiement installation', '2', '$userid', '0', 'open', $time_now, $time_now)";
		$sql->query($q_ticket_fact);
		$ticket_fact = $sql->insert_id;
		
		$msg_fact = $sql->real_escape_string("Fermer le ticket pour activer le ticket d'installation");
		$q_fac_msg = "INSERT INTO `ticket_msg` (`ticket_id`, `staff_id`, `msg`, `date_orig`) VALUES ('$ticket_fact','$userid','$msg_fact','$time_now');";
		$sql->query($q_fac_msg);
		
		$q_ticket = "INSERT INTO `$mydbName`.`ticket` (`account_id`, `subject`, `dept_id`, `open_by`, `assign_to`, `status`, `waiting_for`, `parent`, `due_date`, `due_time`, `date_create`, `last_update`, `wizard`, `wizard_fibre`, `bon_id`, `followed_by`) VALUES ";
		$q_ticket .= "('{$_POST['account_id']}', '$subject', '$ticket_dept', '$userid', '$ticket_assign', 'pending', '$ticket_fact', '$ticket_fact', '$date', '{$_POST['date_time']}', $time_now, $time_now, '$service_list', '$wiz_fibre', '$bon_id', '$follow')";
	}
	else{	
		$q_ticket = "INSERT INTO `$mydbName`.`ticket` (`account_id`, `subject`, `dept_id`, `open_by`, `assign_to`, `status`, `due_date`, `due_time`, `date_create`, `last_update`, `wizard`, `wizard_fibre`, `bon_id`, `followed_by`) VALUES ";
		$q_ticket .= "('{$_POST['account_id']}', '$subject', '$ticket_dept', '$userid', '$ticket_assign', 'open', '$date', '{$_POST['date_time']}', $time_now, $time_now, '$service_list', '$wiz_fibre', '$bon_id', '$follow')";
	}
	
	
	
	//$q_ticket = "INSERT INTO `$mydbName`.`ticket` (`account_id`, `subject`, `dept_id`, `open_by`, `assign_to`, `status`, `due_date`, `due_time`, `date_create`, `last_update`, `wizard`, `wizard_fibre`, `bon_id`, `followed_by`) VALUES ";
	//$q_ticket .= "('{$_POST['account_id']}', '$subject', '$ticket_dept', '$userid', '$ticket_assign', 'open', '$date', '{$_POST['date_time']}', $time_now, $time_now, '$service_list', '$wiz_fibre', '$bon_id', '$follow')";
	$sql->query($q_ticket);
	$ticket_id = $sql->insert_id;

	$ticket_msg = change_quote($ticket_msg);
	$q_ticket_msg = "INSERT INTO `$mydbName`.`ticket_msg` (`ticket_id`, `staff_id`, `msg`, `date_orig`, `unread_csv`, `public`) VALUES ('$ticket_id','$userid','$ticket_msg','$time_now','$unread_csv','0')";
	$sql->query($q_ticket_msg);

	if(isset($_POST['chk_phone'])){
	
		$result_aID = $sql->query("SHOW TABLE STATUS LIKE 'ticket';");
		$row_aID = $result_aID->fetch_array();
		$ticket_id_t =  $row_aID['Auto_increment'];
				
		$q_ticket = "INSERT INTO `ticket` (`parent`, `account_id`, `subject`, `dept_id`, `open_by`, `assign_to`, `status`, `due_date`, `due_time`, `date_create`, `last_update`, `wizard`) VALUES ";
		$q_ticket .= "('$ticket_id','{$_POST['account_id']}', 'Configuration boitier tel', '23', '$userid', '4661', 'open', '$date', '{$_POST['date_time']}', $time_now, $time_now, '$service_list')";
		$sql->query($q_ticket);	
		$ticket_id_t = $sql->insert_id;
		
		$q_ticket_msg = "INSERT INTO `ticket_msg` (`ticket_id`, `staff_id`, `msg`, `date_orig`, `unread_csv`, `public`) VALUES ('$ticket_id_t','$userid','voir parent','$time_now','$unread_csv','0')";
		$sql->query($q_ticket_msg);	
	}
	
	
	if(isset($_FILES['uploadedfile'])){
		$base_path = "uploads/ticket/$ticket_id/";
		if(!is_dir("uploads/ticket/$ticket_id")) mkdir("uploads/ticket/$ticket_id");
		
		$q = "SELECT `attachment_ext` FROM `compta_setup`";
		$res = $sql->query($q);
		$list_attachement = $res->fetch_array();
		$list_attachement = $list_attachement[0];
		
		for($i=0; $i < count($_FILES['uploadedfile']['name']); $i++){
			$filename = basename( $_FILES['uploadedfile']['name'][$i]);
			$filename = getRewriteString($filename);
			$target_path = $base_path . $filename;

			$tmp = explode('.',$target_path);
			$ext = strtolower($tmp[count($tmp)-1]);

			if(stripos($list_attachement,$ext) !== false){
				copy($_FILES['uploadedfile']['tmp_name'][$i], $target_path);
			}
		}		
	}
	
	
	$log_cf = file_get_contents('/targo/facturation/logs/log');
	$log_cf .= "[" . date('D d M Y H:i:s') . "] [ACCOUNT : WIZARD] <$staff_username> Wizard pour l'adresse {$_POST['delivery_id']} - ticket #$ticket_id \n";
	file_put_contents('/targo/facturation/logs/log', $log_cf);
	

	$_POST['wiz_account'] = $_POST['account_id'];
	$_POST['wiz_delivery'] = $_POST['delivery_id'];
	
	echo "<form id='form_pv' action='accueil.php?menu=client_view' method='POST'><input type='hidden' id='f_id' name='f_id' value='{$_POST['account_id']}'></form><script>document.forms['form_pv'].submit(); </script>";

}


$account_id = $_POST['wiz_account'];
$delivery_id = $_POST['wiz_delivery'];


$q_account = "SELECT * FROM `$mydbName`.`account` WHERE `id` = '$account_id'";
$res_account = $sql->query($q_account);
$row_account = $res_account->fetch_array();

$q_delivery = "SELECT * FROM `$mydbName`.`delivery` WHERE `id` = '$delivery_id'";
$res_delivery = $sql->query($q_delivery);
$row_delivery = $res_delivery->fetch_array();



## Telephonie
//sku phone mensu: TELEPMENS
//sku activation: ACTTELEP
//sku transfert: TELEPTRANS
$res_tel_prod = $sql->query("SELECT `price` FROM `product` WHERE `sku` IN ('ACTTELEP','TELEPMENS','TELEPTRANS')" );
$row_tel_prod = $res_tel_prod->fetch_array();
$price_activ = $row_tel_prod['price'];
$row_tel_prod = $res_tel_prod->fetch_array();
$price_tel = $row_tel_prod['price'];
$row_tel_prod = $res_tel_prod->fetch_array();
$price_transf = $row_tel_prod['price'];
#echo "<br> $price_tel -- $price_activ -- $price_transf <br>";

//placeholder prix telephonie en fibre.
$price_tel_fibre = '24.95';
$price_activ_fibre = '0';
$price_transf_fibre = '0';



$q_install = "SELECT `id`, `price` FROM `$mydbName`.`product` WHERE `id` IN (42,43,351,362,584) ORDER BY `id`";
$res_install = $sql->query($q_install);
$row_install = $res_install->fetch_array();
$option_install = "<option value='{$row_install['id']}' data-fibre='0' data-instprice='{$row_install['price']}' data-tmensuel='$price_tel' data-tactiv='$price_activ' data-ttransf='$price_transf'>Commercial</option>";
$row_install = $res_install->fetch_array();
$option_install .= "<option value='{$row_install['id']}' data-fibre='0' data-instprice='{$row_install['price']}' data-tmensuel='$price_tel' data-tactiv='$price_activ' data-ttransf='$price_transf' selected>R&eacute;sidentielle</option>";
$install_value = $row_install['price'];
$row_install = $res_install->fetch_array();
$option_install .= "<option value='{$row_install['id']}' data-fibre='1' data-instprice='{$row_install['price']}' data-tmensuel='$price_tel_fibre' data-tactiv='$price_activ_fibre' data-ttransf='$price_transf_fibre'>Fibre R&eacute;sidentielle</option>";
$row_install = $res_install->fetch_array();
$option_install .= "<option value='{$row_install['id']}' data-fibre='1' data-instprice='{$row_install['price']}' data-tmensuel='$price_tel_fibre' data-tactiv='$price_activ_fibre' data-ttransf='$price_transf_fibre'>Fibre Commercial</option>";
$row_install = $res_install->fetch_array();
$option_install .= "<option value='{$row_install['id']}' data-fibre='2' data-instprice='{$row_install['price']}' data-tmensuel='$price_tel_fibre' data-tactiv='$price_activ_fibre' data-ttransf='$price_transf_fibre'>Lac des pins</option>";

#product

$prod_blacklist = array(556,557,558, 549,551,553); //ne jamais permettre de choisir ces produits

$res_product = $sql->query("SELECT * FROM `$mydbName`.`product` WHERE `active` = '1' AND `category` IN (4,23,32) ORDER BY `sku`");
$option_product = "<option value='default'>-- Select --</option>";
while($row_product = $res_product->fetch_array()){
	if(in_array($row_product['id'],$prod_blacklist)) continue;
	$option_product .= "<option name='".$row_product['id']."' value='".$row_product['id']."'>".$row_product['sku']."</option>";
}


$res_product = $sql->query("SELECT * FROM `$mydbName`.`product` WHERE `active` = '1' AND `category` IN (4,23,32) AND `type` != 2 AND `commercial` = 0 ORDER BY `sku`");
$opt_prod_sfres = "<option value='default'>-- Select --</option>";
while($row_product = $res_product->fetch_array()){
	if(in_array($row_product['id'],$prod_blacklist)) continue;
	$opt_prod_sfres .= "<option name='".$row_product['id']."' value='".$row_product['id']."'>".$row_product['sku']."</option>";
}

$res_product = $sql->query("SELECT * FROM `$mydbName`.`product` WHERE `active` = '1' AND `category` IN (4,23,32) AND ((`type` = 1 AND `commercial` = 1) OR `type` NOT IN (1,2)) ORDER BY `sku`");
$opt_prod_sfcom = "<option value='default'>-- Select --</option>";
while($row_product = $res_product->fetch_array()){
	if(in_array($row_product['id'],$prod_blacklist)) continue;
	$opt_prod_sfcom .= "<option name='".$row_product['id']."' value='".$row_product['id']."'>".$row_product['sku']."</option>";
}

$res_product = $sql->query("SELECT * FROM `$mydbName`.`product` WHERE `active` = '1' AND `category` IN (4,23,26,32) AND `type`!= 1 AND `commercial` = 0 ORDER BY `sku`");
$opt_prod_fibres = "<option value='default'>-- Select --</option>";
while($row_product = $res_product->fetch_array()){
	if(in_array($row_product['id'],$prod_blacklist)) continue;
	$opt_prod_fibres .= "<option name='".$row_product['id']."' value='".$row_product['id']."'>".$row_product['sku']."</option>";
}

$res_product = $sql->query("SELECT * FROM `$mydbName`.`product` WHERE `active` = '1' AND `category` IN (4,23,26,32) AND ((`type` = 2 AND `commercial` = 1) OR `type` NOT IN (1,2)) ORDER BY `sku`");
$opt_prod_fibcom = "<option value='default'>-- Select --</option>";
while($row_product = $res_product->fetch_array()){
	if(in_array($row_product['id'],$prod_blacklist)) continue;
	$opt_prod_fibcom .= "<option name='".$row_product['id']."' value='".$row_product['id']."'>".$row_product['sku']."</option>";
}

## Tele
$res_tele = $sql->query("SELECT * FROM `$mydbName`.`product` WHERE `active` = '1' AND `category` = 33 AND `type` = 4 ORDER BY `sku`");
$option_tele = "<option value='default'>-- Select --</option>";
while($row_tele = $res_tele->fetch_array()){
	if($row_tele['id'] == 561) continue; //package de base, a eviter
	$option_tele .= "<option name='".$row_tele['id']."' value='".$row_tele['id']."'>".$row_tele['sku']."</option>";
}

$option_tele .= "<optgroup label='Seulement si demandé'><option name='561' value='561'>TELEBASE</option></optgroup>";



## fibre id - tente de trouver le id dans la table fibre.

$civic = explode(' ',$row_delivery['address1'],2);
$rue = trim($civic[1]);
$civic = trim(str_replace(',','',$civic[0]));

$zip = str_replace(' ','',$row_delivery['zip']);
	
$q_fibre = "SELECT * FROM `fibre` WHERE `zip` = '$zip' AND `terrain` = '$civic'";
$res_fibre = $sql->query($q_fibre);

$fibre_find = 0;
$fibre_result = '';

if($res_fibre->num_rows > 0){
	$fibre_result .= "Addresse disponible (<b>UN option DOIT être selectionné</b>):<br>Si vous croyez que l'adresse devrait être disponible, valider avec Dominique ou Pierre pour vous assurer que l'adresse a bien été ajoutée via la map infrastructure.<br><br><table class='table table-hover'>";
	while($row_fibre = $res_fibre->fetch_array()){
		
		$boitier = ($row_fibre['boitier_pas_install'] == 1) ? "<span class='alert-warning'>Boitier non installé, ajouter 2 semaines de délais</span>" : '';
		
		if($row_fibre['sn'] != ''){
			$fibre_result .= "<tr title='Sn déja atrtibué pour cette adresse'><td></td><td>{$row_fibre['terrain']}</td><td>{$row_fibre['rue']}</td><td>{$row_fibre['ville']}</td><td>{$row_fibre['zip']}</td><td>{$row_fibre['description']}</td><td>$boitier</td></tr>";
			continue;
		}
		
		$checked = '';
		
		if($row_fibre['rue'] == $rue){
			$checked = 'checked';
			$fibre_find = $row_fibre['id'];
		}
		else{
			$q_check = "SELECT `id` FROM `fibre` WHERE `zip` = '$zip' AND `terrain` = '$civic' AND `rue` = '$rue'";
			$res_check = $sql->query($q_check);
			$row_check = $res_check->fetch_array();
			if($res_check->num_rows == 1 AND $row_check['id'] == $row_fibre['id']){
				$checked = 'checked';
				$fibre_find = $row_fibre['id'];
			}
			
		}

		$fibre_result .= "<tr onclick='fibre_sel({$row_fibre['id']})'><td><input $checked type='radio' id='opt_addr_{$row_fibre['id']}' name='opt_addr' value='{$row_fibre['id']}'></td><td>{$row_fibre['terrain']}</td><td>{$row_fibre['rue']}</td><td>{$row_fibre['ville']}</td><td>{$row_fibre['zip']}</td><td>{$row_fibre['description']}</td><td>$boitier</td></tr>";
	}
	$fibre_result .= "</table>";
}
else
	$fibre_result = "<div class='alert alert-danger'>Aucune adresse trouv&eacute;e. Non disponible.</div>";

?>


<script>

var num_rows = 1;
var account_id = <?php echo $account_id; ?>;
var opt_sf_res = "<?php echo $opt_prod_sfres; ?>";
var opt_sf_com = "<?php echo $opt_prod_sfcom; ?>";
var opt_fibre_res = "<?php echo $opt_prod_fibres; ?>";
var opt_fibre_com = "<?php echo $opt_prod_fibcom; ?>";

function fibre_sel(fibre_id){
	
	$("#opt_addr_" + fibre_id).prop("checked",true);
	$("#fibre_id").val(fibre_id);
	
}

function search_fibre(){
	let cp = $("#cp").val();
	let civic = $("#civic").val();
	$("#fibre_id").val(0);
	
	$.ajax({
		type: "POST",
		async: true,
		url: "account_wizard_ajax.php",
		data: "cp=" + cp + "&civic=" + civic,
		success: function(data){			
			$('#fibre_result').html(data);
		}
	});
	
	
}


function toggle(mod,val){

	var obj_class = "." + mod + "_fld";
	$(obj_class).each(function() {
		this.disabled = !val;
	});
	
}



function addRow(tableID) {

	var table = document.getElementById(tableID);

	var rowCount = table.rows.length;
	var row = table.insertRow(rowCount);
	num_rows++;
	var colCount = table.rows[1].cells.length;

	for(var i=0; i<colCount; i++) {

		var newcell	= row.insertCell(i);

		newcell.innerHTML = table.rows[1].cells[i].innerHTML;
		
		if(tableID == 'datatable_tele')
			newcell.childNodes[0].id = newcell.childNodes[0].id.substr(0,5) + num_rows;
		else
			newcell.childNodes[0].id = newcell.childNodes[0].id.substr(0,4) + num_rows;
		
		//newcell.childNodes[0].name = newcell.childNodes[0].name.replace("_1","_"+num_rows);		
		//alert(newcell.childNodes[0].name);
					
		//alert(newcell.childNodes);
		switch(newcell.childNodes[0].type) {
			case "text":
					if(newcell.childNodes[0].name == "qte[]")
						newcell.childNodes[0].value = "1";
					else if(newcell.childNodes[0].name == "amount[]")
						newcell.childNodes[0].value = "0";
					else 
						newcell.childNodes[0].value = "";
						
					break;
			case "checkbox":
					newcell.childNodes[0].checked = false;
					break;
			case "select-one":
					newcell.childNodes[0].selectedIndex = 0;
					break;
		}
	}
	
	return num_rows;
}


function deleteRow(tableID) {
	try {
	var table = document.getElementById(tableID);
	var rowCount = table.rows.length;

	for(var i=0; i<rowCount; i++) {
		var row = table.rows[i];
		var chkbox = row.cells[0].childNodes[0];
		if(null != chkbox && true == chkbox.checked) {
			if(rowCount <= 2) {
				alert("Vous ne pouvez effacer toutes les lignes");
				break;
			}
			table.deleteRow(i);
			rowCount--;
			i--;
		}


	}
	}catch(e) {
		alert(e);
	}
	
}

function deleteAllRow(tableID) {
	
	$("#"+tableID).find("tr:gt(1)").remove();

}


function fill_product(obj){

	//account_id is global
	var product_id = obj.value
	var line_id = obj.id.substr(4);
			
	var res= $.ajax({
			type: "POST",
			async: false,
			url: "invoice_ajax_product.php",
			data: "account_id=" + account_id + "&product_id=" + product_id,
			succes:function( data ){
				//alert( "Data Saved: " + data );
			}
		}).responseText;

	//alert(res);
	res = res.split("|");
	document.getElementById('hij_' + line_id).selectedIndex = 0;
	document.getElementById('amt_'+line_id).value = $.trim(res[0]);
	document.getElementById('des_'+line_id).value = html_entity_decode(res[1]);
	document.getElementById('qtd_'+line_id).value = res[2] / 1073741824;
	document.getElementById('qtn_'+line_id).value = res[3] / 1073741824;
	document.getElementById('dur_'+line_id).value = '';
	
	//if(product_id == 559) document.getElementById('dur_'+line_id).value = 24; //RAB24M
	//if(product_id == 829) document.getElementById('dur_'+line_id).value = 36; //RAB36M
	
	switch(product_id){
		case '582':
		case '821': $('#dur_'+line_id).prop('readonly',false).removeClass('form-read'); break;
		case '559': $('#dur_'+line_id).prop('readonly',false).removeClass('form-read'); document.getElementById('dur_'+line_id).value = 24; break;
		case '829': $('#dur_'+line_id).prop('readonly',false).removeClass('form-read'); document.getElementById('dur_'+line_id).value = 36; break;
		default: $('#dur_'+line_id).prop('readonly',true).addClass('form-read');
	}

}

function fill_tele(obj){

	//account_id is global
	var product_id = obj.value
	var line_id = obj.id.substr(5);
			
	var res= $.ajax({
			type: "POST",
			async: false,
			url: "invoice_ajax_product.php",
			data: "account_id=" + account_id + "&product_id=" + product_id,
			succes:function( data ){
				//alert( "Data Saved: " + data );
			}
		}).responseText;

	//alert(res);
	res = res.split("|");
	document.getElementById('tamt_'+line_id).value = $.trim(res[0]);
	document.getElementById('tdes_'+line_id).value = html_entity_decode(res[1]);
	document.getElementById('thij_' + line_id).selectedIndex = 0;
	
	
}

function validateAmount(inputNode){

	if(inputNode.value.match(/[^0-9.-]/gi)){
		alert('Ce champ doit être numérique et le séparateur décimal doit être un point (.)');
		setTimeout(function() { inputNode.focus(); }, 50);
	}
}

function changeIstallType(){
	
	let obj = $('#select_install option:selected');
	
	$('#install_price').val(obj.data('instprice'));
	$('.optprod').each(function(){
		switch(obj.val()){
			case '42': $(this).html(opt_sf_com); break;
			case '43': $(this).html(opt_sf_res); break;
			case '351': $(this).html(opt_fibre_res); break;
			case '362': $(this).html(opt_fibre_com); break;
			case '584': $(this).html(opt_fibre_res); break;
		}
		
		fill_product(document.getElementById($(this).attr('id')));
	});
		
		
	
	
}

function flagFibre(id){

	var obj = $('#'+id + ' option:selected');
	$('#fibre').val(obj.data('fibre'));
	$('#price_tel_men').val(obj.data('tmensuel'));
	$('#price_tel_act').val(obj.data('tactiv'));
	$('#price_tel_trans').val(obj.data('ttransf'));
	
	if(obj.data('fibre') == 1){
		//$('#field_tele').removeClass('hide');
		$('#div_fibre').removeClass('hide');
	}
	else{
		$('#field_tele').addClass('hide');
		$('#div_fibre').addClass('hide');
		if($('#chk_tele').prop('checked') === true)
			$('#chk_tele').trigger('click');
	
	}
	
	$('#f_send').validator('validate');
}

function calculInstall(){

	var install = new Number($('#install_price').val());
	var credit = new Number($('#install_credit').val());

	$('#install_sous_total').val(install - credit);
	
	if(install - credit <= 0){
		$('#install_code').removeClass('hide');
	}
	else
		$('#install_code').addClass('hide');
}

function check_lock(date_str){


/*
	var res = jQuery.ajax({
		type: "GET",
		async: false,
		url: "ticket_ajax_day_lock.php?date="+ date_str
	}).responseText;
	
	document.getElementById('day_lock').value = $.trim(res);
	
	alert(date_str + ' - ' + res);
	
	if($.trim(res) == 1) alert('<?php echo utf8_encode("La journée est pleine, aucune autre installation possible.");?>');
	
*/	
	
	
	var res = $.ajax({
		type: "POST",
		async: false,
		url: "ticket_install_ajax.php",
		data: "date_check=" + date_str,
		succes:function( data ){
			//alert( "Data Saved: " + data );
		}
	}).responseText;

	res = $.trim(res);
	res = res.split('|');
	
	alert(res[0]);
	
	document.getElementById('day_lock').value = $.trim(res[1]);
	
	if(res[1] == 1)	alert('La journée est pleine, aucune autre installation possible.');	
	

}

function valid_form(){

	var valid = 1;
		
	if(document.getElementById('date_install').value == '') {valid = 0; alert('Date Installation obligatoire');}
	
	if(document.getElementById('date_invoice').value == '' && (document.getElementById('chk_product').checked || document.getElementById('chk_phone').checked)) {valid = 0; alert('Date Prochaine facture obligatoire');}
	
	if(document.getElementById('day_lock').value == 1){alert('La journée est pleine, aucune autre installation possible.'); valid = 0;}
	
	if(document.getElementById('chk_install').checked){
		var total_install = new Number(document.getElementById('install_price').value) - new Number(document.getElementById('install_credit').value);
		
		/*
		if(total_install <= 0){
			
			var res = jQuery.ajax({
				type: "GET",
				async: false,
				url: "account_wizard_ajax.php?code="+ document.getElementById('install_code').value
			}).responseText;
			
			
			if($.trim(res) == 0){
				alert('Mauvais Code Confirmation');
				valid = 0;
			}
		}
		*/
	}
	if(valid) document.forms['f_send'].submit();


}

function field_changed(id,table='prod'){
	
	if(table == 'tele')		
		document.getElementById('thij_' + id.substr(5)).selectedIndex = 1;
	else
		document.getElementById('hij_' + id.substr(4)).selectedIndex = 1;

}

</script>

<style>
.form-read {
  background-color: #eee;
  opacity: 1;
}
</style>

<h3>Installation Client Wizard</h3>

<br>

<form id='form_cancel' action='accueil.php?menu=client_view' method='POST'>
	<input type='hidden' id='f_cancel_id' name='f_id' value='<?php echo $account_id; ?>'>
</form>


<input type='hidden' id='day_lock' name='day_lock' value='0'>

<form id='f_send' class="form-horizontal" method='post' data-toggle="validator" role="form" enctype='multipart/form-data'>

<input type='hidden' name='account_id' value='<?php echo $account_id; ?>'>
<input type='hidden' name='delivery_id' value='<?php echo $delivery_id; ?>'>
<input type='hidden' name='customer_id' value='<?php echo $row_account['customer_id']; ?>'>
<input type='hidden' name='client_username' value='<?php echo $row_account['username']; ?>'>
<input type='hidden' name='client_password' value='<?php echo $row_account['password']; ?>'>
<input type='hidden' name='customer_name' value='<?php echo trim("{$row_account['first_name']} {$row_account['last_name']} {$row_account['company']}"); ?>'>
<input type='hidden' name='address' value='<?php echo $row_delivery['address1']; ?>'>
<input type='hidden' name='city' value='<?php echo $row_delivery['city']; ?>'>
<input type='hidden' name='zip' value='<?php echo $row_delivery['zip']; ?>'>
<input type='hidden' name='phone' value='<?php echo $row_delivery['tel_home']; ?>'>
<input type='hidden' name='fibre' id='fibre' value='0'>
<input type='hidden' name='fibre_id' id='fibre_id' value='<?php echo $fibre_find; ?>'>

<fieldset>
<legend><label>Info Client</label></legend>
	<div class="form-group">
		<label class="col-sm-2 control-label">Num&eacute;ro Client</label>
		<div class="col-sm-10">
			<p class="form-control-static"><?php echo $row_account['customer_id']; ?></p>
		</div>
	</div>
	<div class="form-group">
		<label class="col-sm-2 control-label">Nom</label>
		<div class="col-sm-10">
			<p class="form-control-static"><?php echo trim("{$row_account['first_name']} {$row_account['last_name']} {$row_account['company']}"); ?></p>
		</div>
	</div>
	<div class="form-group">
		<label class="col-sm-2 control-label">Adresse</label>
		<div class="col-sm-10">
			<p class="form-control-static"><?php echo $row_delivery['address1']; ?></p>
		</div>
	</div>
	<div class="form-group">
		<label class="col-sm-2 control-label">Ville / cp</label>
		<div class="col-sm-10">
			<p class="form-control-static"><?php echo "{$row_delivery['city']} {$row_delivery['zip']}"; ?></p>
		</div>
	</div>
	<div class="form-group">
		<label class="col-sm-2 control-label">T&eacute;l&eacute;hpone</label>
		<div class="col-sm-10">
			<p class="form-control-static"><?php echo $row_delivery['tel_home']; ?></p>
		</div>
	</div>
	<div class="form-group">
		<label class="col-sm-2 control-label">Email</label>
		<div class="col-sm-4">
			<input type='input' class='form-control' id='email' name='email' value='<?php echo $row_delivery['email']; ?>'>
		</div>
	</div>
</fieldset>

<br><br><br>

<fieldset>
<legend><label>Date</label></legend>



<div class="form-group">
	<label for="date_install" class="col-sm-2 control-label">Installation</label>
	<div class="col-sm-2">
		<div class='input-group date' id='dp_date_install'>
			<input type='text' class="form-control" id='date_install' name='date_install' data-checklock="install" required>
			<span class="input-group-addon">
				<span class="glyphicon glyphicon-calendar"></span>
			</span>		
		</div>
	</div>
	<span class="help-block with-errors"></span>
</div>
<div class="form-group">
    <label for="date_time" class="col-sm-2 control-label"></label>
    <div class="col-sm-2">
      <select class="form-control" id='date_time' name='date_time'>
			<option value='day'>Journ&eacute;e</option>
			<!--<option value='am'>AM</option>
			<option value='pm'>PM</option>-->
		</select>
    </div>
</div>
<div class="form-group">
    <label for="date_invoice" class="col-sm-2 control-label">Premi&egrave;re mensualit&eacute; Automatique</label>
    <div class="col-sm-2">
      <div class='input-group date' id='dp_date_invoice'>
			<input type='text' class="form-control" id='date_invoice' name='date_invoice' data-invdate="inv">
			<span class="input-group-addon">
				<span class="glyphicon glyphicon-calendar"></span>
			</span>
	  </div>	
    </div>
	<span class="help-block with-errors"></span>
</div> 

</fieldset>
<br><br><br>

<fieldset>
<legend><label class='control-label'><input type='checkbox' id='chk_install' name='chk_install' checked onclick="toggle('install',this.checked);"> Installation</label></legend>


<div class='row form-group'>
	<div class='col-sm-2 text-right'>
		<label class="control-label">Type</label>
	</div>
	<div class='col-sm-2'>
		<select class='install_fld form-control' id='select_install' name='select_install' onchange="changeIstallType(); flagFibre(this.id); calculInstall();">
			<?php echo $option_install; ?>
		</select>
	</div>
	<div class='col-sm-2'>
		<div class="input-group">
			<input class="form-control install_fld" type='text' id='install_price' name='install_price' onkeyup='calculInstall()' value='<?php echo $install_value; ?>'>
			<span class="input-group-addon">$</span>
		</div>	
	</div>
</div>
<div class='row form-group'>
	<div class='col-sm-2 text-right'>
		<label class="control-label">Cr&eacute;dit</label>
	</div>
	<div class='col-sm-2'>
		<div class="input-group">
			<input class="form-control install_fld" type='text' id='install_credit' name='install_credit' onkeyup='calculInstall()'>
			<span class="input-group-addon">$</span>
		</div>	
	</div>
</div>
<div class='row form-group'>
	<div class='col-sm-2 text-right'>
		<label class="control-label">Sous-Total</label>
	</div>
	<div class='col-sm-2'>
		<div class="input-group">
			<input class="form-control install_fld" type='text' id='install_sous_total' value='<?php echo $install_value; ?>' readonly>
			<span class="input-group-addon">$</span>
		</div>	
	</div>
	<div class='col-sm-3'>
		<input class="form-control install_fld hide" type='password' placeholder='confirmation code' id='install_code'  data-checkcode="helo">
	</div>
	<span class="help-block with-errors"></span>
</div>
<br>
<div id='div_attach' class='row form-group'>
	<div class='col-sm-2 text-right'>
		<label class="control-label">Photo</label>
	</div>
	<div class='col-sm-2'>
		<div class='form-group'><input id='uploadedfile' name='uploadedfile[]' type='file' multiple></div>
	</div>
	<span class="help-block with-errors">Multiple selection possible, tenez 'ctrl'</span>
</div>
<br>
<div id='div_fibre' class='hide'>

	<br><br>
	<h4>Valider adresse fibre</h4>
	
	<div class='row'>
	<div class='col-sm-1 col-sm-offset-1'>
		<input class="form-control install_fld" type='text' id='civic' placeholder='#civic' value='<?php echo $civic; ?>'>
	</div>
	<div class='col-sm-2'>
		<input class="form-control install_fld" type='text' id='cp' placeholder='code postal' value='<?php echo $row_delivery['zip']; ?>'>
	</div>
	<div class='col-sm-1'>
		<button class='btn btn-primary' onclick='search_fibre()'><span class='glyphicon glyphicon-search'></span></button>
	</div>
	<span class="help-block"> Utilisez uniquement si l'adresse civic est érroné</span>
	</div>
	<br>
	<div id='fibre_result' class='col-sm-offset-1'>
		<?php echo $fibre_result; ?>
	</div>


</div>

</fieldset>


<br><br><br>


<fieldset>
<legend><label><input type='checkbox' id='chk_product' name='chk_product' checked onclick="toggle('product',this.checked);$('#f_send').validator('validate');"> Produits</label></legend>
<div class='alert alert-warning <?php if($row_account['invoice_delivery'] == 1) echo 'hide'; ?>'>Client a la facturation par la poste. Ajouter le produit FACT.</div>
<div class='alert alert-warning'>Duration (mois) d&eacute;sactivera le service, Utiliser seulement pour les rabais</div>
<div id='div_product'>
<table id="datatable" class='table table-striped table-condensed table-lineless'>
	<thead>
	<tr>
		<th></th><th>Produit</th><th>Hijack?</th><th>Description</th><th>Montant (CAD)</th><th>Quota Jour</th><th>Quota Nuit</th><th>Contrat (mois)</th><th>Duration (mois)</th>
	</tr>
	</thead>
	<tbody>
	<tr>
		<td><input class='product_fld' type="checkbox" name="chk[]"/></td>
		<td><select class='product_fld optprod' id='sku_1' name="sku[]" onchange="fill_product(this)" ><?php echo $opt_prod_sfres; ?></select></td>
		<td><select class='product_fld' id="hij_1" name="hij[]"><option value='0'>Non</option><option value='1'>Oui</option></select></td>
		<td><input class='product_fld' type="text" id="des_1" name="desc[]" size=85 onchange="field_changed(this.id)"/></td>
		<td><input class='product_fld' type="text" id="amt_1" name="amount[]" value='0' size=5 onchange="field_changed(this.id)" onblur="validateAmount(this)"/></td>
		<td><input class='product_fld' type="text" id="qtd_1" name="quota_day[]" onchange="field_changed(this.id)" value='' size=5 ></td>
		<td><input class='product_fld' type="text" id="qtn_1" name="quota_night[]" onchange="field_changed(this.id)" value='' size=5 ></td>
		<td><input class='product_fld' type="text" id="ctr_1" name="contrat[]" value='' size=5 ></td>
		<td><input class='product_fld form-read' type="text" id="dur_1" name="duration[]" value='' size=5 readonly></td>

	</tr>
	</tbody>
</table>
<br/>

<button class='product_fld btn btn-xs btn-success' type="button" onclick="addRow('datatable')"><span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span> ligne</button>
<button class='product_fld btn btn-xs btn-danger'  type="button" onclick="deleteRow('datatable')" ><span class="glyphicon glyphicon-remove" aria-hidden="true"></span> ligne(s)</button>
</div>
</fieldset>


<br><br><br>


<fieldset>
<legend><label><input type='checkbox' id='chk_phone' name='chk_phone' onclick="toggle('phone',this.checked); $('#f_send').validator('validate');"> T&eacute;l&eacute;phonie</label></legend>

<div class='alert alert-info'>Le service 911 sera &eacute;galement cr&eacute;&eacute;</div>
<div class='row form-group'>
	<div class='col-sm-2 text-right'>
		<label class="control-label">Mensualit&eacute;</label>
	</div>
	<div class="col-sm-2">
		<div class="input-group ">
			<input class='phone_fld form-control'  type='text' id='price_tel_men' name='price_tel_men' value='<?php echo number_format($price_tel,2); ?>'>
			<span class="input-group-addon">$</span>
		</div>
	</div>
</div>
<div class='row form-group'>
	<div class='col-sm-2 text-right'>
		<label class="control-label">Cr&eacute;dit</label>
	</div>
	<div class="col-sm-2">
		<div class="input-group">
			<input class='phone_fld form-control'  type='text' id='credit_telepmens' name='credit_telepmens'>
			<span class="input-group-addon">$</span>
		</div>
	</div>
	<div class='form-control-static col-sm-1'>
		pendant
	</div>
	<div class="col-sm-2">
		<div class="input-group">
			<input type='text' class='phone_fld form-control' id='credit_telepmens_time' name='credit_telepmens_time'> 
			<span class="input-group-addon">mois</span>
		</div>
	</div>
</div>
<br>
<div class='row form-group'>
	<div class="col-sm-1 col-sm-offset-2 checkbox">								
		<label><input type='checkbox' class='phone_fld' id='chk_tel_act' name='chk_tel_act'> Activation</label>
	</div>
	<div class="col-sm-2">
		<div class="input-group ">
			<input class='phone_fld form-control'  type='text' id='price_tel_act' name='price_tel_act' value='<?php echo number_format($price_activ,2);?>'>
			<span class="input-group-addon">$</span>
		</div>
	</div>
</div>
<div class='row form-group'>
	<div class="col-sm-2 col-sm-offset-2 checkbox">								
		<!--<label><input type='checkbox' class='phone_fld' id='chk_tel_pref' name='chk_tel_pref'> Nouveau num&eacute;ro</label>-->
		<label class="radio-inline">
			<input class='phone_fld' type='radio' id='opt_num_new' name='opt_num' value='nouveau' checked> Nouveau num&eacute;ro
		</label>
	</div>
</div>
<div class='row form-group'>
	<div class='col-sm-offset-2 col-sm-8' style='padding-left:60px'>
		<label class="radio-inline">
			<input class='phone_fld' type='radio' id='pref_450' name='opt_pref' value='450'> 450
		</label>
		<label class="radio-inline">
			<input class='phone_fld' type='radio' id='pref_514' name='opt_pref' value='514'> 514
		</label>
		<label class="radio-inline">
			<input class='phone_fld' type='radio' id='pref_none' name='opt_pref' value='aucune' checked> Aucune Pr&eacute;f&eacute;rence
		</label>
	</div>
</div>
<div class='row form-group'>
	<div class="col-sm-2 col-sm-offset-2 checkbox">								
		<!--<label><input type='checkbox' class='phone_fld' id='chk_tel_trans' name='chk_tel_trans'> Transfert du num&eacute;ro</label>-->
		<label class="radio-inline">
			<input class='phone_fld' type='radio' id='opt_num_trans' name='opt_num' value='transfert'>  Transfert du num&eacute;ro
		</label>
	</div>
	<div class="col-sm-2">
		<div class="input-group">
			<input class='phone_fld form-control' type='text' id='price_tel_trans' name='price_tel_trans' value='<?php echo number_format($price_transf,2);?>'>
			<span class="input-group-addon">$</span>
		</div>
	</div>
</div>
<div class='row'>
	<div class="form-control-static col-sm-2 col-sm-offset-2" style='padding-left:60px'>
		Num&eacute;ro &agrave; porter
	</div>
	<div class="col-sm-2">
		<input type='text' class='phone_fld form-control' id='trans_number' name='trans_number'>
	</div>	
</div>
<div class='row help-block col-sm-offset-2'>
	<b>IMPORTANT</b> Facture de moins de 30 jours de leur fournisseur n&eacute;cessaire et doit &ecirc;tre sign&eacute;e.<br>
	D&eacute;lais du transfert: 10 jours ouvrables apr&egrave;s r&eacute;ception.
</div>

</fieldset>

<br><br><br>


<fieldset id='field_tele' class='hide'>
<!-- toggle('tele',this.checked);$('#f_send').validator('validate'); -->
<legend><label><input type='checkbox' id='chk_tele' name='chk_tele' onclick=""> Télévision</label></legend>

<div class='alert alert-info'>Utiliser le wizard tele dans l'adresse d'installation</div>

<div id='div_tele'>
<table id="datatable_tele" class='table table-striped table-condensed table-lineless'>
	<thead>
	<tr>
		<th></th><th>Package</th><th>Hijack?</th><th>Description</th><th>Montant (CAD)</th><th>Contrat (mois)</th><th>Duration (mois)</th>
	</tr>
	</thead>
	<tbody>
	<tr>
		<td><input class='tele_fld' type="checkbox" name="t_chk[]"/></td>
		<td><select class='tele_fld' id='tsku_1' name="t_sku[]" onchange="fill_tele(this)" ><?php echo $option_tele; ?></select></td>
		<td><select class='tele_fld' id="thij_1" name="t_hij[]"><option value='0'>Non</option><option value='1'>Oui</option></select></td>
		<td><input class='tele_fld' type="text" id="tdes_1" name="t_desc[]" size=85 onchange="field_changed(this.id,'tele')"/></td>
		<td><input class='tele_fld' type="text" id="tamt_1" name="t_amount[]" value='0' size=5 onchange="field_changed(this.id,'tele')" onblur="validateAmount(this)"/></td>
		<td><input class='tele_fld' type="text" id="tctr_1" name="t_contrat[]" value='' size=5 ></td>
		<td><input class='tele_fld' type="text" id="tdur_1" name="t_duration[]" value='' size=5 ></td>

	</tr>
	</tbody>
</table>
<br/>

<button class='tele_fld btn btn-xs btn-success' type="button" onclick="addRow('datatable_tele')"><span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span> ligne</button>
<button class='tele_fld btn btn-xs btn-danger'  type="button" onclick="deleteRow('datatable_tele')" ><span class="glyphicon glyphicon-remove" aria-hidden="true"></span> ligne(s)</button>
</div>
</fieldset>

<br><br><br>

Information Suppl&eacute;mentaire:<br>
<textarea class='form-control' id='info_supp' name='info_supp' rows=15></textarea>

<br><br><br>
<button type='submit' class="btn btn-success"><span class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></span> Enregistrer</button> <button type='button' class="btn btn-warning" onclick='document.forms["form_cancel"].submit()'><span class="glyphicon glyphicon-ban-circle" aria-hidden="true"></span> Annuler</button>
</form>

<br><br><br>

<script>

if(document.getElementById('email').value == "") alert("Il manque l'adresse email pour la suivi de conso");

<?php

if(!isset($_POST['chk_install'])){
/*	
echo '$(".install_fld").each(function() {
		this.disabled = 1;
	});';
*/
}

/*
if(!isset($_POST['chk_product'])){
	
echo '$(".product_fld").each(function() {
		this.disabled = 1;
	});';

}
*/

if(!isset($_POST['chk_phone'])){
	
echo '$(".phone_fld").each(function() {
		this.disabled = 1;
	});';

}

if(!isset($_POST['chk_tele'])){
	
echo '$(".tele_fld").each(function() {
		this.disabled = 1;
	});';

}

?>


$('#f_send').validator({
			custom: {
				invdate: function($el) {		
				
					if($el.val() == '' && ($('#chk_phone').prop('checked') == true || $('#chk_product').prop('checked') == true)){
						return false
					}
					else
						return true
				
				},
				checklock: function($el){
						
					if($el.val() != ''){
						/*
						var res = jQuery.ajax({
							type: "GET",
							async: false,
							url: "ticket_ajax_day_lock.php?date="+ $el.val()
						}).responseText;
						*/
						
						let dept_install = 12;
						if($('#fibre').val() >= 1) dept_install = 27;
						
						
						var res = $.ajax({
							type: "POST",
							async: false,
							url: "ticket_install_ajax.php",
							data: "date_check=" + $el.val() + "&dept_id=" + dept_install,
							succes:function( data ){
								//alert( "Data Saved: " + data );
							}
						}).responseText;
					
						res = $.trim(res);
						res = res.split('|');
					
						if($.trim(res[1]) == 0)
							return true
						else						
							return false
					}
					else
						return true

				},
				checkcode: function($el){
						
					if($('#install_sous_total').val() <= 0){
						var res = jQuery.ajax({
							type: "GET",
							async: false,
							url: "account_wizard_ajax.php?code="+ $el.val()
						}).responseText;
						
						
						
						if($.trim(res) == 0){
							return false
						}
						else
							return true
					}
					else
						return true
				
				}
			},
			errors:{
				invdate: "Date Obligatoire",
				checklock: "<?php echo "La journée est pleine, aucune autre installation possible.";?>",
				checkcode: "Code Invalide"
			}
		});


$(function () {
	$('#dp_date_install').datetimepicker({
		showTodayButton: true,
		showClear: true,
		showClose: true,
		useCurrent: false,
		format: "DD-MM-YYYY",
		minDate: moment("<?php echo date('Y m d');?>", "YYYY MM DD"),
		locale: 'fr'
	});
});

$("#dp_date_install").on("dp.change", function (e) {
	$('#f_send').validator('validate');
});

$(function () {
	$('#dp_date_invoice').datetimepicker({
		showTodayButton: true,
		showClear: true,
		showClose: true,
		useCurrent: false,
		format: "DD-MM-YYYY",
		minDate: moment("<?php echo date('Y m 01');?>", "YYYY MM DD"),
		locale: 'fr'
	});
});

$("#dp_date_invoice").on("dp.change", function (e) {
	$('#f_send').validator('validate');
});

</script>

