<?php
/**
 * Newsletter module
 * 
 * Modify given newsletter from back-office. Available if the newsletter has not been send already 
 * 
 * @package linea21\modules\newsletter
 * @author $Author$ - linea21 <info@linea21.com>
 * @version $Id$ 
 * @access public
 * @license http://opensource.org/licenses/gpl-3.0.html
 */

//////////// Check Inclusion de pages ////////////
if (!class_exists('auth')) {
  include_once("../lib/lib_common.php");
  ReloadIndex('admin');
}
////////////

//////////// Check Droits utilisateur ////////////
if (!$l21auth->isSuperAdmin()) ReloadIndex('admin');
////////////

if (isset($_GET['id']))	$id=$_GET['id'];
if (isset($_POST['id'])) $id=$_POST['id'];

$newsletter_object = new newsletter;

$mask_statut_D='';
$mask_statut_W='';



if(isset($_POST['enregistrer'])) {
  $data_table=unserialize(urldecode($_POST['data_table']));
  $result=$newsletter_object->ModifyNewsletter($id, $data_table, $sql_object);
  $link_confirm="confirm.php?rub=".$rub."&todo=".$todo;
  if($result) {
      header("Location: ".safe_redirect($link_confirm));
      exit;
  }
  else  system_error();
}

// Titre de la newsletter en cours de modification
$requete=SQL_getNewsletterTitle($id);
$result=$sql_object->DBSelect($requete);

// Do record exists?
if(!isset($result[0]['newsletter_title'])) redirect_to('@module_default');

$news_current_title=formatText($result[0]['newsletter_title'],'2HTML');


// Obtention des données  de la BDD
$req_det= SQL_getoneCompleteNewsletter($id);
$result = $sql_object->DBSelect($req_det);
if($result==0 || count($result)!=1) exit;

$form_title=formatText($result[0]['newsletter_title'], '2FIELD');

// Getting html content from template file
$html = file_get_contents(override("../newsletter/input/template.html", THEME_PUBLIC_PATH));
$html = str_replace('##SITEURL##', SITE_ROOT_URL, $html);

// get content with SIMPLEHTMLDOM
$dom = str_get_html($html);


// we get newsletter body
$body_field =  formatText($result[0]['newsletter_body'], '2FIELD');
$body_field =  $result[0]['newsletter_body'];

// get content with SIMPLEHTMLDOM
$dom_field = str_get_html($body_field);

// we do replace the content from template with content stored id db inside <div id="main">
if($dom->find('div[id=main]', 0)) {
    // _debug('div[id=main] is found !!!!', 'SIMPLEHTMLDOM');
    $dom->find('div[id=main]', 0)->innertext= $body_field;
    $html = $dom->save(); // we finally save changes to apply them
}

// @todo to remove
// we check if a div #inputs is already present in body_field
// if yes we remove div ID in default template t
// if($dom_field->find('div[id=inputs]', 0)) {
//     // _debug('div[id=inputs] is found !!!!', 'SIMPLEHTMLDOM');
//     $dom->find('div[id=inputs]', 0)->id= null; // we rename div[id=inputs] to new random id if found    
//     $html = $dom->save(); // we finally save changes to apply them
// }

// ##CONTENTS## placeholder is not used anymore but we replace itdynamically for old config 
// instead we use if($dom->find('div[id=main]', 0)), see above
$form_body = str_replace('##CONTENTS##', '', $html);  // @todo not used anymore since 2.6 - remove later
$form_statut=$result[0]['newsletter_statut'];
$news_owner = $result[0]['newsletter_posted_by'];

//////////// Check Droits utilisateur + statut newsletter courante ////////////
if (!$l21auth->isSuperAdmin()) ReloadIndex('admin');
////////////


// radio statut
if($form_statut=='W') $mask_statut_W='checked="checked"';
if($form_statut=='D') $mask_statut_D='checked="checked"';

if(isset($_POST['valider'])) {
    
  $table = array();
  $table[0]=$_POST['newsletter_title'];

  $html = $_POST['newsletter_body'];
  if (version_compare(phpversion(), '7.4.0', '<'))  {
      if (get_magic_quotes_gpc()) $html=stripslashes($html);
  }
  $html = removeEmptyP($html);

  // we get only the text contained into #main div
  $flow = str_get_html($html);
  $body_content = $flow->find('#main', 0)->innertext;

  $table[1]=$body_content;

  $table[2]=$_POST['newsletter_statut'];

  $integrity=$newsletter_object->CheckDataIntegrity($table);

  if(is_string($integrity)) {
    $text_format='2FIELD';
    $body_content=$_POST['newsletter_body'];
  } else {
    $text_format='2HTML';
  }
  $form_title=formatText($_POST['newsletter_title'],$text_format);
  $form_body=formatText($body_content, $text_format);
  $form_statut=$_POST['newsletter_statut'];


  if($_POST['newsletter_statut']=='D') $mask_statut_D='checked="checked"'; else $mask_statut_D='';
  if($_POST['newsletter_statut']=='P') $mask_statut_P='checked="checked"'; else $mask_statut_W='';
  $table=urlencode(serialize($table));
}

?>


<div id="chemin">
<ul>
	<li><a href="index.php" class="chemin_home"><?php echo _t('way','home'); ?></a></li>
	<li><a href="<?php echo $rub_link; ?>" id="chemin_<?php echo $rub; ?>" class="chemin_rub"><?php echo _t('menu','newsletter');?></a></li>
	<li><span><?php echo formatNavTitle(_t('newsletter','mod'). ' : '.$news_current_title); ?></span></li>
</ul>
</div>
<!--end barre haute -->

<?php
if(!isset($integrity) || is_string($integrity)) {
  ?>
<div class="contentcontainer"><?php
include_once(override($dir.'/menurub.php', THEME_ADMIN_PATH));
?>
<div id="content"><?php
if(isset($integrity) && is_string($integrity)) display_errors($integrity);
?>
<h2><?php echo formatTitleh2($news_current_title); ?></h2>
<form id="modnews" action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method="post" enctype="multipart/form-data">
<p>
  <label for="newsletter_title"><?php echo mb_ucfirst(_t('newsletter','title')); ?>&nbsp;:&nbsp;*</label>
  <input name="newsletter_title" type="text" class="textfield" id="newsletter_title" maxlength="200" value="<?php echo $form_title; ?>" required />
</p>
<p>
  <label for="newsletter_body"><?php echo mb_ucfirst(_t('newsletter','body')); ?>&nbsp;:&nbsp;*</label>
  <textarea id="newsletter_body" name="newsletter_body" class="largetextfield" <?php echo AREA_SETTINGS; ?> required><?php echo $form_body; ?></textarea>
</p>
  <div class="clearfix mrl">
  	<button id="auto-populate" class="small button regular"><?php echo  mb_ucfirst(_t('newsletter','auto_populate')); ?></button>
  </div>
<div class="label"><?php echo mb_ucfirst(_t('newsletter','statut')); ?> : </div>
<div class="rightpanel">
<?php if($form_statut == 'P') { ?>
	<input name="newsletter_statut" type="hidden" id="statut_P" value="P" />
	<div class="info"><?php echo mb_ucfirst(_t('newsletter','already_sent')); ?></div>
<?php } else { ?>
  <input name="newsletter_statut" type="radio" class="radio" id="statut_D" value="D" <?php echo $mask_statut_D; ?> />
  <label for="statut_D"><?php echo mb_ucfirst(_t('statut','draft')); ?></label>
  <input name="newsletter_statut" type="radio" class="radio" id="statut_W" value="W" <?php echo $mask_statut_W; ?> />
  <label for="statut_W"><?php echo mb_ucfirst(_t('newsletter','nightsend')); ?></label>
<?php } ?>
</div>
<div>
  <input name="id" type="hidden" value="<?php echo $id; ?>" id="id" />
  <input name="rub" type="hidden" value="<?php echo $rub; ?>" id="rub" />
  <input name="todo" type="hidden" value="<?php echo $todo; ?>" id="todo" />
  <?php echo cancel_button('javascript:history.go(-1);'); ?>
  <input name="valider" type="submit" value="<?php echo _t('btn','valid'); ?>" class="button" id="valider" />
</div>
</form>
</div> <!-- closing #content -->
</div> <!-- closing .contentcontainer -->
<?php

$str = '$("#auto-populate").click(function() {
					if("'.RICH_TEXT_EDITOR.'" == "cke") var ccontent = $( "textarea.largetextfield").val();
					if("'.RICH_TEXT_EDITOR.'" == "tinymce") var ccontent = tinyMCE.activeEditor.getContent();
	 				$.ajax({
					  url: "'.override('../newsletter/_ajax_auto-populate.php', THEME_ADMIN_PATH).'",
					  type: "POST",
					  dataType: "html",
 						data: { content : ccontent }
					}).done(function ( data ) {
							// Set the editor data.
							if("'.RICH_TEXT_EDITOR.'" == "cke") $( "textarea.largetextfield" ).val( data);
							if("'.RICH_TEXT_EDITOR.'" == "tinymce") tinyMCE.activeEditor.setContent(data);
					});
					return false;
    
				});';
footerAddInlineJS($str);

// Récapitulatif
} else	{
  ?>
<div class="contentcontainer"><?php
include_once(override($dir.'/menurub.php', THEME_ADMIN_PATH));
?>
<div id="content">
<h2><?php echo formatTitleh2(_t('recap','title')); ?></h2>
<?php
echo "<dl class=\"summary\">\n";
echo "<dt>".mb_ucfirst(_t('newsletter','title'))." :</dt>\n";
echo "<dd>".$form_title."</dd>\n";
echo "<dt>".mb_ucfirst(_t('newsletter','body'))." :</dt>\n";
echo "<dd>".$form_body."</dd>\n";
echo "<dt>".mb_ucfirst(_t('divers','statut')) ." :</dt>\n";
echo "<dd>". display_statut($_POST['newsletter_statut']). "</dd>\n";
echo "</dl>\n";
?>
<form id="modscale" action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method="post">
<div>
  <input name="id" type="hidden" value="<?php echo $id; ?>" id="id" />
  <input name="rub" type="hidden" value="<?php echo $rub; ?>" id="rub" />
  <input name="todo" type="hidden" value="<?php echo $todo; ?>" id="todo" />
  <input name="data_table" type="hidden" value="<?php echo $table; ?>" id="data_table" />
  <?php echo cancel_button('?rub=newsletter&amp;todo=list'); ?>
  <input name="retour" type="button" value="<?php echo _t('btn','preview'); ?>" class="button" id="retour" onclick="history.go(-1);" />
  <input name="enregistrer" type="submit" value="<?php echo _t('btn','save'); ?>" class="button" id="valider" />
  </div>
  </form>
</div> <!-- closing #content -->
</div> <!-- closing .contentcontainer -->
<?php
}
?>
