<?php
/**
 * @copyright (C) 2016 - 2025 Holger Brandt IT Solutions
 * @license GNU/GPL, see license.txt
 * WP Mailster is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License 2
 * as published by the Free Software Foundation.
 *
 * WP Mailster is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with WP Mailster; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 * or see http://www.gnu.org/licenses/.
 */


if ( ! defined( 'ABSPATH' ) ) {
    exit; // Not the droids
}

$log = MstFactory::getLogger();
$model = MstFactory::getMailsModel();
$log->debug('mails.php REQ: '.print_r($_REQUEST, true));
if( array_key_exists('mailpage', $_REQUEST) ) {
	$page = intval($_REQUEST['mailpage']);
} else {
	$page = 1;
}

if(!isset($listId)){ // this may be set via mst_view_mailing_list
    $listId = 0;
}
if( array_key_exists('lid', $_REQUEST) ) {
	$listId = intval($_REQUEST['lid']);
}

if(!$listId) {
	$fromLists = true;
    if( array_key_exists('lid', $_REQUEST) ) {
		$listId = intval( $_REQUEST['lid'] ); // list id
	} else {
        if(!isset($listId)){
		    $listId = 0;
        }
	}
} else {
	$fromLists = false;
}
if(!isset($msgOrder)){ // this may be set via mst_view_mailing_list
    $msgOrder = 'rfirst';
}
if( array_key_exists('message_order', $_REQUEST) ) {
	$msgOrder = sanitize_text_field($_REQUEST['message_order']); // message_order
}
if( array_key_exists('pageclass_sfx', $_REQUEST) ) {
	$pageclass_sfx = sanitize_text_field($_REQUEST['pageclass_sfx']); // thread id
} else {
	$pageclass_sfx = "";
}

if( array_key_exists('show_mailing_list_name_in_list', $_REQUEST) ) {
	$show_mailing_list_name_in_list = intval($_REQUEST['show_mailing_list_name_in_list']); // thread id
} else {
	$show_mailing_list_name_in_list = 0;
}
if( array_key_exists('show_mailing_list_name_in_title', $_REQUEST) ) {
	$showMailingListNameInTitle = intval($_REQUEST['show_mailing_list_name_in_title']); // thread id
} else {
	$showMailingListNameInTitle = 0;
}
if( array_key_exists('show_page_heading', $_REQUEST) ) {
	$menuParamShowHeading = intval($_REQUEST['show_page_heading']); // thread id
} else {
	$menuParamShowHeading = 0;
}
if( array_key_exists('page_heading', $_REQUEST) ) {
	$menuParamPageHeading = sanitize_text_field($_REQUEST['page_heading']); // thread id
} else {
	$menuParamPageHeading = 0;
}

$defaultPageHeading = $menuParamShowHeading ? $menuParamPageHeading : '';
$log->debug('Mails view showMailingListNameInList: '.$show_mailing_list_name_in_list);

$mailingListUtils = MstFactory::getMailingListUtils();
if($listId>0){
	$mList = $mailingListUtils->getMailingList($listId);
	if($showMailingListNameInTitle){
		$mListName = $mList->name;
		$title = $mListName;
	}else{
		$title = $defaultPageHeading;
	}
}else{
	if($showMailingListNameInTitle){
		$allMailingLists = __('- All Mailing Lists -', 'wp-mailster');
		$title =$allMailingLists;
	}else{
		$title = $defaultPageHeading;
	}
}
$log->debug('shortcodes/mails.php listId: '.$listId);
$mails = $model->getData($listId, false, $msgOrder, true, false, $page, false);
$pagination = $model->getPagination();
$total = $model->getTotal();
$totalpages = $total / get_option('posts_per_page', 12);


if( array_key_exists('filter_search', $_REQUEST) ) {
	$filterSearch = sanitize_text_field($_REQUEST['filter_search']); // thread id
} else {
	$filterSearch = "";
}
$filter = ($filterSearch != '' ? '&filter_search='.urlencode($filterSearch) : '');

$currurl = '?subpage=mailstermails' . $filter.($listId > 0 ? '&lid='.intval($listId) : '');
$mstImgPath =  plugins_url( '/asset/images/', dirname(__FILE__) );
$dateUtils = MstFactory::getDateUtils();
$page_sfx_attr = esc_attr($pageclass_sfx);
$formatStr = __('%Y-%M-%D', 'wp-mailster');
MstFactory::getAuthorization();
?>
<div class="mst_container">
	<div class="wrap">
		<h4>
			<?php _e("All Emails", 'wp-mailster');  ?>
			<?php if($fromLists && $listId > 0) { ?>
			<a style="float:right;" class="add-new-h2" href="<?php echo get_permalink( get_the_ID() ); ?>"><?php _e("Go Back", 'wp-mailster'); ?></a>
			<?php } ?>
		</h4>
		<?php if(MstAuthorization::userHasAccess($listId)) { ?>
		<form id="adminForm" name="adminForm" method="post" action="<?php echo esc_url($currurl); ?>">
			<div class="mailster_messages contentpane<?php echo $page_sfx_attr; ?>">
				<div class="input-group searchbox<?php echo $page_sfx_attr; ?> mailster_searchbox">
					<input id="filter_search" name="filter_search" type="text" class="form-control inputbox" placeholder="" value="<?php echo esc_attr($filterSearch); ?>">
					<span class="input-group-btn">
						<input id="filter_search_btn" class="btn btn-default" type="submit" value="<?php _e( 'Search', 'wp-mailster'); ?>"/>
					</span>
				</div>
				<div class="mailster_messages_list_container<?php echo $page_sfx_attr; ?>">
					<table class="mailster_messages_list<?php echo $page_sfx_attr; ?> mailster_std_table table">
						<thead>
							<tr>
								<th class="mailster_messages_list_header_subject<?php echo $page_sfx_attr; ?>"><?php _e( 'Subject', 'wp-mailster'); ?></th>
								<th class="mailster_messages_list_header_sender<?php echo $page_sfx_attr; ?>"><?php _e( 'Sender', 'wp-mailster'); ?></th>
								<th class="mailster_messages_list_header_sender<?php echo $page_sfx_attr; ?>"><?php _e( 'Sender address', 'wp-mailster'); ?></th>
								<?php if($show_mailing_list_name_in_list): ?><th class="mailster_messages_list_header_mailing_list<?php echo $page_sfx_attr; ?>"><?php _e( 'Mailing List', 'wp-mailster'); ?></th><?php endif; ?>
								<th class="mailster_messages_list_header_date<?php echo $page_sfx_attr; ?>"><?php _e( 'Date', 'wp-mailster');?></th>
							</tr>
						</thead>
						<tbody>
						<?php
						for($i=0;$i<count($mails);$i++){
							$mail = &$mails[$i];
							$backlink = base64_encode($currurl);
							$detaillink = '?subpage=mailstermail&amp;id='. intval($mail->id).'&bl='.$backlink;
							$receiveTimestamp = $dateUtils->formatDateAsConfigured($mail->receive_timestamp);
							$hasAttachs = $mail->has_attachments > 0;
                            $attachImg = '<span class="mailster_has_attach" title="' .__( 'Has attachments', 'wp-mailster' ) .'">📎</span>';
							$subject = (is_null($mail->subject) || strlen($mail->subject) == 0) ? '<em>'.__( '(No Subject)', 'wp-mailster' ).'</em>' : $mail->subject;
							?>
							<tr>
								<td class="mailster_messages_list_subject<?php echo $page_sfx_attr; ?>"><?php echo $hasAttachs ? $attachImg : ''; ?><a href="<?php echo esc_url($detaillink); ?>"><?php echo esc_html($subject); ?></a></td>
								<td class="mailster_messages_list_sender<?php echo $page_sfx_attr; ?>"><?php echo esc_html($mail->from_name); ?></td>
								<td class="mailster_messages_list_sender<?php echo $page_sfx_attr; ?>"><?php echo esc_html($mail->from_email); ?></td>
								<?php if($show_mailing_list_name_in_list): ?><td class="mailster_messages_list_mailing_list<?php echo $page_sfx_attr; ?>"><?php echo esc_html($mail->name); ?></td><?php endif; ?>
								<td class="mailster_messages_list_date<?php echo $page_sfx_attr; ?>"><?php echo esc_html($receiveTimestamp); ?></td>
							</tr>
							<?php
						}
						?>
						</tbody>
					</table>
					<?php
					$prevpage = $page -1;
					if($prevpage>0) {
					?>
					<a href="<?php echo esc_url($currurl . "&amp;mailpage=" . $prevpage); ?>"><?php _e("Previous", 'wp-mailster'); ?></a>
					<?php }
					$nextpage = $page+1;
					if($nextpage <= $totalpages) {
					?>
					<a href="<?php echo esc_url($currurl . "&amp;mailpage=" . $nextpage); ?>"><?php _e("Next", 'wp-mailster'); ?></a>
					<?php } ?>
				</div>
			</div>
		</form>
		<?php } else { ?>
			<h3><?php _e("You do not have access to see this.", 'wp-mailster') ?></h3>
		<?php } ?>
	</div>
</div>
