<?php $__env->startSection('CSS'); ?>
<?php echo HTML::style('bootstrap-select/css/bootstrap-select.min.css'); ?>

<style type="text/css">
	.btnRadius{ border-radius: 4px !important;}
	<?php
		if( !isset($_GET['import']) ){
	?>
	.oculto {
		display: none !important;
	}
	.mdAvatar .modal-dialog .modal-content .modal-header{ background-color: #363B3F; }
	<?php
		}
	?>
</style>
<?php $__env->stopSection(); ?>


<?php $__env->startSection('Contenido'); ?>
<div class="row">
	<div class="col-md-12">
		<h2><i class="fa fa-envelope-o"></i> E-Mail Marketing </h2>
	</div><!--/col-md-12-->
</div><!--/row-->

<div class="row">
	<?php /*
	<div class="col-md-12">
		<nav class="navbar navbar-inverse">
			<ul class="nav navbar-nav">
				<li><a href="<?php echo URL::to('templates'); ?>">Ver todos los Templates</a></li>
				<li><a href="<?php echo URL::to('templates/create'); ?>">Crear un Template</a>
			</ul>
		</nav>
	</div>
	*/ ?>
	<div class="col-md-12">
		<?php if(Session::has('message')): ?>
		<div class="alert alert-info"><?php echo Session::get('message'); ?></div>
		<?php endif; ?>
	</div>
</div>

<div class="row">
	<div class="col-md-12">
		<div class="block-web">
			<div class="header"> <h3 class="content-header"> Listado de formularios de <strong> <?php echo $ListaEmail->nombre; ?> </strong>
				<?php echo HTML::linkRoute('SysWebEmailMarketingFormulariosAgregar', 'Agregar', array($ListaEmail->id), array('class' => 'btn btn-primary btnRadius')); ?>

				<div data-toggle="buttons" class="button-group pull-right">
					<a  onclick="ImportarFormulario()" href="javascript:ImportarFormulario();" style="color: rgba(0, 0, 0, 0.3)"><i class="fa fa-download" aria-hidden="true"></i></a>
				</div>
			</div>
			<div class="porlets-content">
				<div class="table-responsive">
					<table class="table table-striped table-bordered table-hover">
						<thead>
							<tr>
								<th class="col-md-10"> Nombre </th>
								<th class="col-md-2"> Acciones </th>
							</tr>
						</thead>
						<tbody>
							<?php $oculto =  'oculto'; //$oculto = (App::environment() == 'produccion')?'oculto':''; ?>
							<?php $__empty_1 = true; foreach($Formularios as $Formulario): $__empty_1 = false; ?>
							<tr>
								<td> <?php echo $Formulario->nombre; ?> </td>
								<td>
									<a href="<?php echo URL::route('SysWebEmailMarketingFormulariosEditar', array($ListaEmail->id, $Formulario->id)); ?>" class="btn btn-warning tooltips" data-toggle="tooltip" data-original-title="Editar">
										<i class="fa fa-pencil-square-o"></i>
									</a>
									<button type="button" onclick="DuplicarFormulario(<?php echo $Formulario->id; ?>)" class="btn btn-info tooltips" data-toggle="tooltip" data-original-title="Clonar">
										<i class="fa fa-copy"></i>
									</button>
									<a href="<?php echo URL::route('SysWebEmailMarketingFormularioVer', array($Formulario->id)); ?>" class="btn btn-default tooltips" data-toggle="tooltip" data-original-title="Ver en producción">
										<i class="fa fa-eye"></i>
									</a>
									<a href="<?php echo URL::route('SysWebEmailMarketingFormularioExportar', array($Formulario->id)); ?>" class="btn btn-default tooltips <?php echo $oculto; ?>" data-toggle="tooltip" data-original-title="Exportar" download>
										<i class="fa fa-download"></i>
									</a>
									<button type="button" onclick="ReemplazarCodigo(<?php echo $Formulario->id; ?>)" class="btn btn-default tooltips <?php echo $oculto; ?>" data-toggle="tooltip" data-original-title="Reemplazar código">
										<i class="fa fa-upload"></i>
									</button>
									<button type="button" onclick="Eliminar(<?php echo $Formulario->id; ?>)" class="btn btn-danger tooltips" data-toggle="tooltip" data-original-title="Eliminar">
										<i class="fa fa-trash"></i>
									</button>
								</td>
							</tr>
							<?php endforeach; if ($__empty_1): ?>
							<tr class="danger"> <td colspan="3"> No existe ningún formulario creado </td> </tr>
							<?php endif; ?>
						</tbody>
					</table>
				</div>
			</div>
			<div class="bottom">
				<?php echo HTML::linkRoute('SysWebEmailMarketingFormulariosAgregar', 'Agregar', array($ListaEmail->id), array('class' => 'btn btn-primary')); ?>

				<?php
					if( isset($_GET['import']) ){
				?>
				<button type="button" class="btn btn-info" id="btnImportarP" onclick="ImportarPlantilla()"> Importar Plantilla </button>
				<?php
					}
				?>
				<?php
					$idL = $ListaEmail->id;
					$idC =  Cliente::select('id')->where('users_id', '=', Auth::user()->id)->first()->id;
					$Cliente = Cliente::find( $idC );
					$select = 'listas_emails.id, listas_emails.nombre, listas_emails.tipo,
					(
						SELECT
							COUNT(cp.id)
						FROM
							campos_listas_emails AS cle
						INNER JOIN
							campos_personalizados AS cp
							ON cp.id = cle.campos_personalizados_id
						WHERE
							cp.id IN (1, 4, 5)
							AND cle.requerido = 1
							AND cle.listas_emails_id = listas_emails.id
					) AS matchGP, listas_emails.gestion_clientes as tipo';
					$ListasEmails = ListaEmail::select(DB::raw($select))
					->where('clientes_id', '=', $ListaEmail->clientes_id)
					->where('id', '<>', $ListaEmail->id)
					->orderBy('listas_emails.nombre', 'asc')
					->get();

					$Etiquetas = DB::table('etiquetas')
					->where('clientes_id', '=', $ListaEmail->clientes_id)
					->get();

					$Productos = DB::table('productos_servicios')
					->where('clientes_id', '=', $ListaEmail->clientes_id)
					->get();

					$idListProspectos = DB::table('listas_emails')
					->where('clientes_id', '=', $ListaEmail->clientes_id)
					->where('gestion_clientes', '=', 'P')
					->get();

				?>
				<?php echo HTML::linkRoute('SysWebEmailMarketingListasSubscriptores', 'Regresar', array(), array('class' => 'btn btn-default')); ?>

			</div>
		</div>
	</div>
</div><!--/row end-->
<?php $__env->stopSection(); ?>

<?php $__env->startSection('JS'); ?>
<?php echo HTML::script('bootstrap-select/js/bootstrap-select.min.js'); ?>

<?php echo HTML::script('jQueryValidate/jquery.validate.min.js'); ?>

<?php echo HTML::script('jQueryValidate/additional-methods.min.js'); ?>

<?php echo HTML::script('jQueryValidate/jquery.validationEngine-es.js'); ?>


<script type="text/javascript">
	function DuplicarFormulario(idF){
		var idF = idF;
		$.isLoading({ text: "Cargando..." }); NProgress.start();
		$.post(
			"<?php echo URL::route('SysWebEmailMarketingFormulariosClonar'); ?>",
			{idF: idF},
			function(data){
				$.isLoading("hide"); NProgress.done();
				if(data.success){
					new PNotify({ title: "Realizado", text: data.mensaje, type: "success" });
					setTimeout( function(){ window.location.href = "<?php echo URL::route('SysWebEmailMarketingFormularios', array($ListaEmail->id)); ?>"; }, 3000 );
				}
				else{
					if(data.mensaje != ''){ new PNotify({ title: "Error", text: data.mensaje, type: "error" }); }
					$.each(data.errMensajes, function(key, value){ if(value != ''){ $("#err"+key).html(value); } else{ $("#err"+key).html(""); } });
				}
			},
			"json"
		);
	}
	function ImportarFormulario(){
		var mensaje = '<div class="row"> \
			<div class="col-xs-12"> \
				<form id="frmImportarFormularios" class="form-horizontal row-border"> \
					<div class="form-group" style="margin-bottom: 10px"> \
						<?php foreach($idListProspectos as $indice => $idListProspecto): ?> \
							<input hidden id="idlistaProspectos" name="idlistaProspectos" value="<?php echo $idListProspecto->id; ?>"></input>\
						<?php endforeach; ?> \
						<input hidden id="listaActual" name="listaActual" value="<?php echo $ListaEmail->id; ?>"></input>\
						<label class="col-sm-3 control-label" style="text-align: rigth !important; padding-top: 0px;">Lista de suscriptores</label> \
						<div class="col-sm-9"> \
								<select class="form-control selectpicker" id="slListaSuscriptores" data-live-search="true" data-selected-text-format="count" name="slListaSuscriptores"> \
									<option value="">Selecciona una lista de suscripción</option> \
									<?php foreach($ListasEmails as $indice => $LE): ?> \
										<option value="<?php echo $LE->id; ?>" id="op<?php echo $LE->id; ?>" data-tipo="<?php echo $LE->tipo; ?>" data-mgp="<?php echo $LE->matchGP; ?>"> <?php echo $LE->nombre; ?> </option> \
									<?php endforeach; ?> \
								</select> \
							<span class="text-danger" id="errslListaSuscriptores"></span> \
						</div> \
					</div> \
					<div class="form-group" style="margin-bottom: 10px"> \
						<label class="col-sm-3 control-label" style="text-align: rigth !important; padding-top:0px;">Formularios</label> \
						<div class="col-sm-9"> \
							<select class="form-control selectpicker" data-selected-text-format="count" data-live-search="true" data-actions-box="true" id="Listas_Formularios" name="Listas_Formularios" title="Seleccione el formulario..."> \
							</select> \
							<span class="text-danger" id="errListas_Formularios"> </span> \
						</div> \
					</div> \
					<div class="form-group"> \
						<label class="col-sm-3 control-label"> Etiquetas(Opcional) </label> \
							<div class="col-sm-9"> \
								<select class="form-control selectpicker" multiple data-live-search="true" data-actions-box="true" data-selected-text-format="count" id="etiquetasFrm" name="etiquetasFrm"> \
									<option disabled > Seleccione las etiquetas a asociar... </option> \
									<?php foreach($Etiquetas as $indice => $Etiqueta): ?> \
										<option value="<?php echo $Etiqueta->id; ?>" id="op<?php echo $Etiqueta->id; ?>"> <?php echo $Etiqueta->nombre; ?> </option> \
									<?php endforeach; ?> \
								</select> \
								<span class="text-danger" id="erretiquetas"> </span> \
							</div> \
					</div> \
					<div class="form-group hidden" name="ProductoOP" id="ProductoOP"> \
						<label class="col-sm-3 control-label"> Productos/Servicios </label> \
							<div class="col-sm-9"> \
								<select class="form-control selectpicker" data-live-search="true" data-selected-text-format="count" id="ProductosFrm" name="ProductosFrm"> \
									<option value="0" disabled selected> Seleccione producto a asociar... </option> \
									<?php foreach($Productos as $indice => $Producto): ?> \
										<option value="<?php echo $Producto->id; ?>" id="op<?php echo $Producto->id; ?>"> <?php echo $Producto->nombre; ?> </option> \
									<?php endforeach; ?> \
								</select> \
									<span class="text-danger" id="errProductosFrm"> </span> \
							</div> \
					</div> \
				</form> \
			</div> \
		</div>';
		BootstrapDialog.show({
			title: "Importar Formularios",
			type: BootstrapDialog.TYPE_WARNING,
			message: mensaje,
			draggable: true,
			closeByBackdrop: false,
			cssClass: "mdAvatar",
			buttons: [{
				id: "btnImportarFrm",
				label: "Importar",
				cssClass: "btn-success btn-lg btn-block ",
				action: function(dialogItself){
					var ListaA= "<?php echo $ListaEmail->id; ?>";
					var FormularioE = $("#Listas_Formularios").val();
					var Etiquetas = $("#etiquetasFrm").val();
					var vetanaA = dialogItself.getModalBody();
					if(vetanaA.find("#frmImportarFormularios").valid()){
						$.isLoading({ text: "Cargando..." }); NProgress.start();
						$("#btnImportarFrm").prop("disabled", true).html('<i class="fa fa-spinner fa-spin"></i> Importando...');
						var ruta = "<?php echo URL::route('SysWebEmailMarketingFormulariosxListasInsertar', array($ListaEmail->id, 'Formulario','Etiquetas')); ?>";
						ruta = ruta.replace("Formulario", FormularioE).replace("Etiquetas", Etiquetas);
						$.post(
							ruta,
							vetanaA.find("#frmImportarFormularios").serialize(),
							function(data){
								$.isLoading("hide"); NProgress.done();
								confirmacionSalida = false;
								$("button[type='submit']").prop("disabled", false);
								$("#btnImportarFrm").prop("disabled", false).html("Importar");
								if(data.success){
									new PNotify({ title: "Realizado", text: data.mensaje, type: "success" });
									dialogItself.close();
									setTimeout( function(){ window.location.href = "<?php echo URL::route('SysWebEmailMarketingFormularios', array($ListaEmail->id)); ?>"; }, 3000 );
									if(typeof data.MensajeError != "undefined"){ $("#MensajeError2").html(data.MensajeError); $("#MensajeError2").show(); }else{ $("#MensajeError2").hide(); $("#MensajeError2").html(""); }
								}
								else{
									if(typeof data.MensajeError != "undefined"){ $("#Errs").html(data.MensajeError); $("#MensajeError").show(); } else{ $("#MensajeError").hide(); $("#Errs").html("");}
									if(data.mensaje != ""){ new PNotify({ title: "Error", text: data.mensaje, type: "error" });}
									$.each(data.errMensajes, function(key, value){ if(value != ""){ $("#err"+key).html(value); } else{ $("#err"+key).html("");}});
								}
							},
							"json"
						);
					}
				}
			}],
			onshown: function(dialogRef){
				var ventana = dialogRef.getModalBody();
				ventana.css("padding-bottom", "0px");
				ventana.css("margin-top", "0px");
				ventana.find(".selectpicker").selectpicker();
				var ListaA= "<?php echo $ListaEmail->id; ?>";
				ventana.find("#frmImportarFormularios").validate({
						lang: "es",
						ignore: [],
						errorPlacement: function(error, element) {
							var p = error.attr("id").indexOf("-error");
							var elemento = "err"+error.attr("id").substr(0, p);
							$("#"+elemento).html( error.html() );
						},
						success: function(error) {
							var p = error.attr("id").indexOf("-error");
							var elemento = "err"+error.attr("id").substr(0, p);
							$("#"+elemento).html("");
						},
						rules: {
							slListaSuscriptores: {
								required: true
							},
							Listas_Formularios: {
								required: true
							}
						},
						messages: {
							slListaSuscriptores: {
								required: "Este campo es requerido"
							},
							Listas_Formularios: {
								required: "Este campo es requerido"
							}
						}
				});
				if(ListaA == $("#idlistaProspectos").val()){
					$("#ProductoOP").removeClass("hidden");
					$("#ProductosFrm").rules( "add", {
						required: true,
						messages: {
							required: "Este campo es requerido"
						}
					});
				}
				ventana.find("#slListaSuscriptores").on("change", function(){
					$("#Listas_Formularios").selectpicker("refresh");
					if(ListaA != $("#idlistaProspectos").val()){
						if($("#slListaSuscriptores").val() == $("#idlistaProspectos").val()){
							$("#ProductoOP").removeClass("hidden");
						}
						else{
							$("#ProductoOP").addClass("hidden");
						}
					}
					var idLista = $(this).val();
					var ruta = "<?php echo URL::route('SysWebEmailMarketingFormulariosListar', array("idL")); ?>";
					ruta = ruta.replace("idL", idLista);
					$.get(
						ruta,
						function(data){
							var opcionesSL = '';
							if( data.length != 0 ){
								$.each(data, function(index, val) {
									opcionesSL += '<option value="'+index+'">'+val+'</option>';
								});
							}
							$("#Listas_Formularios").html(opcionesSL);
							$("#Listas_Formularios").selectpicker("refresh");
						},
						"json"
					);
				});
				ventana.find("#slListaSuscriptores").selectpicker("refresh");
			},
		});
	}
	function Eliminar(idF){
		var idF = idF;
		var mensaje = "<div class='row'> \
							<div class='col-xs-12'> \
								<form id='frmEliminar'> \
									<h2> ¿Seguro que desea eliminar? </h2> \
									<input type='hidden' name='idF' value='"+idF+"'> \
								</form> \
							</div> \
						</div>";
		BootstrapDialog.show({
			title: "Eliminar registro",
			type: BootstrapDialog.TYPE_DANGER,
			message: mensaje,
			draggable: true,
			closeByBackdrop: false,
			cssClass: "ModalEliminar mdAvatar",
			onshown: function(dialogItself){
				$("body").addClass("modal-open");
			},
			buttons: [{
				id: "btnEliminar",
				label: "Eliminar",
				cssClass: "btn-danger btn-block btn-lg",
				action: function(dialogItself){
					$.isLoading({ text: "Cargando..." }); NProgress.start();
					$.post(
						"<?php echo URL::route('SysWebEmailMarketingFormulariosEliminar'); ?>",
						$("#frmEliminar").serialize(),
						function(data){
							$.isLoading("hide"); NProgress.done();
							if(data.success){
								new PNotify({ title: "Felicidades!", text: data.mensaje, type: "success" });
								dialogItself.close();
								setTimeout( function(){ window.location.href = "<?php echo URL::route('SysWebEmailMarketingFormularios', array($ListaEmail->id)); ?>"; }, 3000 );
							}
							else{
								if(data.mensaje != ''){ new PNotify({ title: "Error", text: data.mensaje, type: "error" }); }
							}
						},
						"json"
					);
				}
			}],
			onhidden: function(dialogItself){
				$("body").removeClass("modal-open");
			}
		});
	}
	<?php
		if( isset($_GET['import']) ){
	?>
	function ImportarPlantilla(){
		var id = id;
		var mensaje = "<div class='row'> \
			<div class='col-xs-12'> \
				<form id='frmImportarPlantilla' enctype='multipart/form-data'> \
					<div class='form-group'> \
						<label for='txtNombre'>Nombre a asignar</label> \
						<input type='text' class='form-control' id='txtNombre' name='txtNombre' placeholder='Nombre a asignar...'> \
						<span class='text-danger' id='errtxtNombre'></span> \
					</div> \
					<div class='form-group'> \
						<label for='txtIDPS'>IdDelPS</label> \
						<input type='text' class='form-control' id='txtIDPS' name='txtIDPS' placeholder='Id del Producto O Servicio...'> \
						<span class='text-danger' id='errtxtIDPS'></span> \
					</div> \
					<div class='form-group'> \
						<label for='flArchivo'>Archivo HTML</label> \
						<input type='file' id='flArchivo' name='flArchivo'> \
						<span class='text-danger' id='errflArchivo'></span> \
					</div> \
					<input type='hidden' name='hdnIdLE' value='<?php echo $ListaEmail->id; ?>'> \
				</form> \
			</div> \
		</div>";
		BootstrapDialog.show({
			title: "Importar Plantilla de archivo HTML",
			type: BootstrapDialog.TYPE_DEFAULT,
			message: mensaje,
			draggable: true,
			cssClass: "ModalImportarPlantilla",
			buttons: [{
				id: "btnImportarPlantilla",
				label: "Importar",
				cssClass: "btn-default",
				action: function(dialogItself){
					$.isLoading({ text: "Cargando..." }); NProgress.start();
					$.isLoading("hide"); NProgress.done();
					$("#btnImportarPlantilla").prop("disabled", true).html('<i class="fa fa-spinner fa-spin"></i> Importando...');
					var formulario = $("#frmImportarPlantilla");
					var formData = new FormData(document.getElementById("frmImportarPlantilla"));
					$.ajax({
						type: "POST",
						url: "<?php echo URL::route('SysWebEmailMarketingFormulariosImportar', array()); ?>",
						data: formData,
						cache: false,
						contentType: false,
						processData: false,
						dataType: "json",
						timeout: 1800000,
						success: function(data){
							$("#btnImportarPlantilla").prop("disabled", false).html("Importar");
							if(data.success){
								new PNotify({ title: "Realizado", text: data.mensaje, type: "success" });
								dialogItself.close();
								setTimeout( function(){ window.location.href = "<?php echo URL::route('SysWebEmailMarketingFormularios', array($ListaEmail->id)); ?>"; }, 3000 );
							}
							else{
								if(typeof data.MensajeError != "undefined"){ $("#Errs").html(data.MensajeError); $("#MensajeError").show(); }else{ $("#MensajeError").hide(); $("#Errs").html(""); }
								if(data.mensaje != ""){ new PNotify({ title: "Error", text: data.mensaje, type: "error" }); }
								$.each(data.errMensajes, function(key, value){ if(value != ""){ $("#err"+key).html(value); } else{ $("#err"+key).html(""); } });
							}
						},
						error: function(jqXHR, textStatus, errorThrown){
							$("#btnImportarPlantilla").prop("disabled", false).html("Importar");
							new PNotify({ title: "Error", text: textStatus + " " + errorThrown, type: "error" });
						}
					});
				}
			}]
		});
	}
	function ReemplazarCodigo(idF){
		var idF = idF;
		var mensaje = "<div class='row'> \
			<div class='col-xs-12'> \
				<form id='frmImportarPlantilla' enctype='multipart/form-data'> \
					<div class='form-group'> \
						<label for='flArchivo'>Archivo HTML</label> \
						<input type='file' id='flArchivo' name='flArchivo'> \
						<span class='text-danger' id='errflArchivo'></span> \
					</div> \
					<input type='hidden' name='hdnIdP' value='"+idF+"'> \
				</form> \
			</div> \
		</div>";
		BootstrapDialog.show({
			title: "Reemplazar Plantilla de archivo HTML",
			type: BootstrapDialog.TYPE_DEFAULT,
			message: mensaje,
			draggable: true,
			cssClass: "ModalImportarPlantilla",
			buttons: [{
				id: "btnImportarPlantilla",
				label: "Reemplazar",
				cssClass: "btn-default",
				action: function(dialogItself){
					$.isLoading({ text: "Cargando..." }); NProgress.start();
					$.isLoading("hide"); NProgress.done();
					$("#btnImportarPlantilla").prop("disabled", true).html('<i class="fa fa-spinner fa-spin"></i> Reemplazando...');
					var formulario = $("#frmImportarPlantilla");
					var formData = new FormData(document.getElementById("frmImportarPlantilla"));
					$.ajax({
						type: "POST",
						url: "<?php echo URL::route('SysWebEmailMarketingFormulariosImportar', array()); ?>",
						data: formData,
						cache: false,
						contentType: false,
						processData: false,
						dataType: "json",
						timeout: 1800000,
						success: function(data){
							$("#btnImportarPlantilla").prop("disabled", false).html("Reemplazar");
							if(data.success){
								new PNotify({ title: "Realizado", text: data.mensaje, type: "success" });
								dialogItself.close();
								setTimeout( function(){ window.location.href = "<?php echo URL::route('SysWebEmailMarketingFormularios', array($ListaEmail->id)); ?>"; }, 3000 );
							}
							else{
								if(typeof data.MensajeError != "undefined"){ $("#Errs").html(data.MensajeError); $("#MensajeError").show(); }else{ $("#MensajeError").hide(); $("#Errs").html(""); }
								if(data.mensaje != ""){ new PNotify({ title: "Error", text: data.mensaje, type: "error" }); }
								$.each(data.errMensajes, function(key, value){ if(value != ""){ $("#err"+key).html(value); } else{ $("#err"+key).html(""); } });
							}
						},
						error: function(jqXHR, textStatus, errorThrown){
							$("#btnImportarPlantilla").prop("disabled", false).html("Reemplazar");
							new PNotify({ title: "Error", text: textStatus + " " + errorThrown, type: "error" });
						}
					});
				}
			}]
		});
	}
	<?php
		}
	?>
</script>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('JSOr'); ?>
<?php if(Session::has('MensajeS')): ?>
new PNotify({ title: "Realizado", text: "<?php echo Session::get('MensajeS'); ?>", type: "success" });
<?php endif; ?>
<?php if(Session::has('MensajeE')): ?>
new PNotify({ title: "Realizado", text: "<?php echo Session::get('MensajeE'); ?>", type: "error" });
<?php endif; ?>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('BaseSistemaWeb', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>