<?php
/**
 * Newsletter module
 * 
 * Display newsletter list in back-office
 * 
 * @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['statut']) || $_GET['statut'] == -1) $statut = -1;
elseif ($_GET['statut'] != -1) $statut = $_GET['statut'];

if (!isset($_GET['debut'])) $debut = 0;
else $debut = $_GET['debut'];

$mask_statut_1 = '';
$mask_statut_2 = '';
$mask_statut_3 = '';

if ($statut == 'public') $mask_statut_1 = 'selected="selected"';
if ($statut == 'draft') $mask_statut_2 = 'selected="selected"';
if ($statut == 'waiting') $mask_statut_3 = 'selected="selected"';
// Nombre d'enregistrement total dans la bdd
$result_nb_req = $sql_object->DBSelect(SQL_getCountNewsletterList(-1));
$bdd_nb_news = $result_nb_req[0]['num_rows'];
$bdd_nb_news_display = $bdd_nb_news . " " . _t('newsletter','nb_total') . "<br />\n";

if ($statut != -1) {
  $link_back = "<div class=\"filter\"><a href=\"" . $rub_link . "&amp;todo=list\">" . _t('newsletter','all') . "</a></div>";
  $req_count_news = SQL_getCountNewsletterList($statut);
  $result_nb_req = $sql_object->DBSelect($req_count_news);
  $count_request = $result_nb_req[0]['num_rows'];
  $req_list_newsletter = SQL_getNewsletterList($debut, SELECT_LIMIT, $statut);
  $result_newsletter_list = $sql_object->DBSelect($req_list_newsletter);
} else {
  $link_back = '';
  $count_request = $bdd_nb_news;
  $req_list_newsletter = SQL_getNewsletterList($debut, SELECT_LIMIT, $statut);
  $result_newsletter_list = $sql_object->DBSelect($req_list_newsletter);
}

if ($count_request <= 1) $count_request_display = _t('divers','query_result') . " : " . $count_request . " " . _t('divers','record') . "<br />\n";
else $count_request_display = _t('divers','query_result') . " : " . $count_request . " " . _t('divers','records') . "<br />\n";

$link_sup = $rub_link . "&amp;todo=sup&amp;id=";
$link_mod = $rub_link . "&amp;todo=mod&amp;id=";
$link_det = $rub_link . "&amp;todo=det&amp;id=";
$link_statut = $rub_link . "&amp;todo=list&amp;statut=";
$link_self = $link_statut . $statut;
// Liste des statuts disponibles
$select_statut = "<select name=\"statut_filter\" id=\"statut_filter\">\n";
$select_statut .= "<option value=\"-1\">" . _t('newsletter','statut_filter') . "</option>\n";
$select_statut .= "<option value=\"" . $link_statut . "public\"" . $mask_statut_1 . ">"._t('statut','public')."</option>\n";
$select_statut .= "<option value=\"" . $link_statut . "draft\"" . $mask_statut_2 . ">"._t('statut','draft')."</option>\n";
$select_statut .= "<option value=\"" . $link_statut . "waiting\"" . $mask_statut_3 . ">"._t('statut','W')."</option>\n";
$select_statut .= "</select>\n";

$js = "	$('#statut_filter').change(function() {
						if($(this).val() != -1) window.location = $(this).val();
				});";

footerAddInlineJS($js);
?>
<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','list')); ?></span></li>
</ul>
</div>
<!--end barre haute -->

<div class="contentcontainer">
<?php
include_once(override($dir.'/menurub.php', THEME_ADMIN_PATH));
?>
<div id="content">
<div class="mod_link">
<a title="<?php echo mb_ucfirst(_t('newsletter','subscribers_list')); ?>" href="#subscribers-container" id="subscribers" class="cboxElement"><?php echo mb_ucfirst(_t('newsletter','subscribers_list')); ?></a>
</div>
<?php
echo $link_back;
?>
<div class="filterselect"><?php echo $select_statut; ?></div>
<p>
	<?php
	echo $bdd_nb_news_display;
	echo $count_request_display;
	?>
</p>
<?php
echo linkin_page($link_self, $count_request, $debut);

if ($result_newsletter_list != 0) {
  echo "<table class=\"multisort\">\n";
  echo "<thead>\n";
  echo "<tr>\n";
  echo "<td>" . mb_ucfirst(_t('newsletter','title')) . "</td>\n";
  echo "<td>".mb_ucfirst(_t('divers','date_crea'))."</td>\n";
  echo "<td>".mb_ucfirst(_t('divers','date_publi'))."</td>\n";
  echo "<td class=\"sorter-false\">&nbsp;<span class=\"visually-hidden\">" . mb_ucfirst(_t('divers','actions')) . "</span></td>\n";
  echo "</tr>\n";
  echo "</thead>\n";



  echo "<tbody>\n";

  for($i = 0; $i < count($result_newsletter_list); $i++) {
    $newsletter_title = formatText(cutText($result_newsletter_list[$i]['newsletter_title'], 70), '2HTML');
    $newsletter_status = $result_newsletter_list[$i]['newsletter_statut'];
    $newsletter_published_date = $newsletter_status=='P' ? $result_newsletter_list[$i]['newsletter_published_date_display'] : _t('statut','draft');
    echo "<tr>\n";
    echo "<td><a href=\"" . $link_det . $result_newsletter_list[$i]['newsletter_id'] . "\" title=\"" . _t('newsletter','det') . ' : ' . formatText($result_newsletter_list[$i]['newsletter_title'], '2ATT') . "\">" . $newsletter_title . "</a></td>\n";
    echo "<td>" . $result_newsletter_list[$i]['newsletter_date_crea_display'] . "</td>\n";
    echo "<td>" . $newsletter_published_date . "</td>\n";
    echo "<td style=\"width:80px\">\n";
    if ($newsletter_status != 'P') {
      echo "<div class=\"iconetab\">";
      echo "\t<a href=\"" . $link_sup . $result_newsletter_list[$i]['newsletter_id'] . "\" class=\"ico_sup\" title=\"" . _t('newsletter','sup') . "\"><i class=\"icon-trash\"></i><span>" . _t('newsletter','sup') . "</span></a>\n";
      echo "\t<a href=\"" . $link_mod . $result_newsletter_list[$i]['newsletter_id'] . "\" class=\"ico_mod\" title=\"" . _t('newsletter','mod') . "\"><i class=\"icon-pencil\"></i><span>" . _t('newsletter','mod') . "</span></a>\n";
      echo "</div>";
    } else echo '&nbsp;';
    echo "</td>\n";
    echo "</tr>\n";

  }

  echo "</tbody>".PHP_EOL;
  echo "</table>".PHP_EOL;
} else {
  echo "<div class=\"info\">" . _t('newsletter','noresult') . "</div>".PHP_EOL;
}
echo linkin_page($link_self, $count_request, $debut);

// Get subscribers list for displaying in colorbox if link is clicked
// récupération des emails
$emails_batch = $sql_object->DBSelect(SQL_GetEmails4Sending());

$count_emails_display = _t('divers','query_result') . " : " . count($emails_batch) . " " . _t('divers','records') . "<br />".PHP_EOL;

$subscribers  = '<div id="subscribers-container">'.PHP_EOL;
$subscribers .=  "<h2>" . mb_ucfirst(_t('newsletter','subscribers_list'))  . "</h2>".PHP_EOL;
$subscribers .=	 "<p>".$count_emails_display."</p>".PHP_EOL;

if (count($emails_batch) == 1 && $emails_batch[0] == false) {

	$subscribers .=  "<div class=\"info\">" . _t('divers','nodata') . "</div>".PHP_EOL;

} else {


	// Calling JS directly into code
	// using footerAddInlineJS() creat an error
	echo '<script type="text/javascript">
				$(function() {
					$("#emailsearch").on("keyup", function() {
						var value = $(this).val().toLowerCase().trim();

						$("#subscribers-container table tr").each(function(index) {
							if (index != 0) {
							
								$row = $(this);
								var id = $row.find("td:first").text().toLowerCase().trim();

								if (id.indexOf(value) != -1) {
									$(this).show();
								} else {
									$(this).hide();
								}
							}
						});
					});
				});
				</script>​'.PHP_EOL;




	$subscribers .=  "<input type=\"text\" class=\"shorttextfield\" id=\"emailsearch\" value=\"\" placeholder=\"" . mb_ucfirst(_t('newsletter','search_address'))  . "\"></input>".PHP_EOL;
	$subscribers .=  "<table class=\"multisort\">".PHP_EOL;
	$subscribers .=  "<thead>".PHP_EOL;
	$subscribers .=  "<tr>".PHP_EOL;
	$subscribers .=  "<td>" . mb_ucfirst(_t('newsletter','email_address')) . "</td>\n";
	$subscribers .=  "<td>".mb_ucfirst(_t('divers','date_crea'))."</td>\n";
	$subscribers .=  "<td class=\"sorter-false\">&nbsp;<span class=\"visually-hidden\">" . mb_ucfirst(_t('divers','actions')) . "</span></td>\n";
	$subscribers .=  "</tr>\n";
	$subscribers .=  "</thead>\n";

	$subscribers .=  "<tbody>\n";

	for($k = 0; $k < count($emails_batch); $k++) {
		$email_id = $emails_batch[$k]['emailcol_id'];
		$email_recipient = $emails_batch[$k]['emailcol_email'];
		$email_date_crea = $emails_batch[$k]['emailcol_date_crea_display'];
		
		// echo $email_id . ' '. $email_recipient. '<br />';

		$subscribers .=  "<tr id=\"email-".$email_id."\">".PHP_EOL;
		$subscribers .=  "<td>".$email_recipient."</td>".PHP_EOL;
		$subscribers .=  "<td>".$email_date_crea."</td>".PHP_EOL;
		$subscribers .=  "<td width=\"10%\"><div class=\"iconetab subscriber-action\">".PHP_EOL;
		$subscribers .=  "<a href=\"../newsletter/subscribe.php?newsletteremail=".$email_recipient."&amp;id=".$email_id."&amp;del_action=true\" title=\""._t('newsletter','unsubscribe')."\" class=\"ico_sup\"><i class=\"icon-trash\"></i><span>" . _t('newsletter','unsubscribe') . "</span></a>".PHP_EOL;
		$subscribers .=  "</div></td>".PHP_EOL;
		$subscribers .=  "</tr>".PHP_EOL;

	}

	$subscribers .=  "</tbody>".PHP_EOL;
	$subscribers .=  "</table>".PHP_EOL;
}
$subscribers .= '</div>'.PHP_EOL;

echo $subscribers;

// Ability to sort table
addDynamicCSS('../lib/js/jquery.tablesorter/theme.default.css');
footerAddJS('../lib/js/jquery.tablesorter/jquery.tablesorter.min.js');
$str = '$("table.multisort").tablesorter({	});';
footerAddInlineJS($str);

// Newsletter Subscribers - Colorbox
$str = '$("#subscribers").colorbox({inline:true, width:"50%", height:"80%"});';
$str 	.= '$("#subscribers-container").wrap(\'<div style="display:none"><\/div>\');';
footerAddInlineJS($str);

//

// ajax code for unsubscribe user
echo '<script type="text/javascript">
                  $(function() {
                  	$(".subscriber-action a").click(function() {

                  		var url = $(this).attr("href");

                  		if($(this).hasClass("deleted")) {
                  			var extradata = "&restore";
                  		} else {
                  			var extradata = "";
                  		}

	    								$.ajax({
	                      	  type: "GET",
	                          url: url,
	                          data: "call=ajax" + extradata,
	                          dataType: "json",
	                          success: function(data){
	                          	if(data.status == "confirm") {

	                          		$(data.el).removeClass("deleted restored").addClass(data.action);
	                          		$(data.el).find("a").removeClass("deleted restored").addClass(data.action);

	                          		if(data.action == "deleted") {
	                          			$(data.el).find("a > i").removeClass("icon-trash").addClass("icon-level-up");
	                          			$(data.el).find("a").attr("title", "'._t('btn', 'annul').'");
	                          		}
	                          		if(data.action == "restored") {
	                          			$(data.el).find("a > i").removeClass("icon-level-up").addClass("icon-trash");
	                          			$(data.el).find("a").attr("title", "'._t('newsletter', 'unsubscribe').'");
	                          		}
	                          	}
	                          }
	                        });

											return false;
											});

                  	});
          </script>';
?>
</div> <!-- closing #content -->
</div> <!-- closing .contentcontainer -->