<?php
if (!defined('ABSPATH')) {
	exit;
}
$locked = !IComm_SM_Features::can_use('client_pdf');
$can_mail = IComm_SM_Features::can_use('client_email');
$is_print = !empty($_GET['print']) && (string) $_GET['print'] === '1';
$s = IComm_SM_Settings::get();
$default_mail = sanitize_email((string) ($s['client_report_email'] ?? ''));

$period = IComm_SM_Report_Builder::resolve_period_from_request(wp_unslash($_GET)); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$period_args = IComm_SM_Report_Builder::period_query_args($period);
$month_options = IComm_SM_Report_Builder::list_month_options(12);
$ui_mode = (string) ($period['mode'] ?? 'month');
$ui_month = (string) ($period['month'] ?? substr((string) ($period['start'] ?? ''), 0, 7));
$ui_start = (string) ($period['start'] ?? '');
$ui_end = (string) ($period['end'] ?? '');
if ($ui_mode !== 'custom') {
	$ui_mode = 'month';
}

$last = get_option('icomm_sm_last_client_mail', []);
if (!is_array($last)) {
	$last = [];
}

$mail_flash = isset($_GET['client_mail']) ? sanitize_key((string) $_GET['client_mail']) : '';

if ($is_print) {
	if (!current_user_can('manage_options')) {
		exit;
	}
	$html = '<!DOCTYPE html><html dir="rtl" lang="he"><head><meta charset="UTF-8">'
		. '<meta name="viewport" content="width=device-width, initial-scale=1" />'
		. '<title>' . esc_html__('icomm metrix - דוח חודשי', 'icomm-metrix') . '</title>'
		. '<style>body{margin:0;padding:18px;font-family:Arial,Helvetica,sans-serif;direction:rtl;text-align:right;background:#fff}'
		. '.box{max-width:900px;margin:0 auto} @media print{body{padding:0}.no-print{display:none!important}}</style>'
		. '</head><body><div class="box">' . IComm_SM_Report_Builder::monthly_client_report_html($period)
		. '</div><script>window.addEventListener("load",function(){setTimeout(function(){window.print();},150);});</script></body></html>';
	echo $html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
	exit;
}

$print_url = add_query_arg(
	array_merge(
		[
			'page' => 'icomm-metrix-client',
			'print' => '1',
		],
		$period_args
	),
	admin_url('admin.php')
);
?>
<div class="wrap icomm-sm-wrap" dir="rtl" lang="he">
	<h1><?php esc_html_e('דוח חודשי ללקוח', 'icomm-metrix'); ?> <span>v<?php echo esc_html(ICOMM_SM_VERSION); ?></span> <?php echo IComm_SM_Features::pro_badge_html(); ?></h1>
	<?php echo IComm_SM_Features::locked_notice_html(__('דוח ללקוח', 'icomm-metrix')); ?>

	<p class="description">
		<?php
		echo esc_html(sprintf(
			__('דוח עבור %s · תקופה: %s', 'icomm-metrix'),
			(string) $period['domain'],
			(string) $period['label']
		));
		?>
	</p>

	<?php if (!$locked) : ?>
		<div style="background:#fff;border:1px solid #c3c4c7;padding:16px 18px;margin:16px 0;max-width:760px;">
			<h2 style="margin-top:0;"><?php esc_html_e('בחירת תקופה', 'icomm-metrix'); ?></h2>
			<p class="description" style="margin-top:0;">
				<?php esc_html_e('ברירת המחדל היא החודש הקלנדרי הקודם. שליחה אוטומטית תמיד שולחת את החודש הקודם.', 'icomm-metrix'); ?>
			</p>
			<form method="get" action="<?php echo esc_url(admin_url('admin.php')); ?>" id="icomm-sm-report-period-form" style="display:flex;flex-wrap:wrap;gap:12px;align-items:flex-end;">
				<input type="hidden" name="page" value="icomm-metrix-client" />
				<p style="margin:0;">
					<label for="report_mode"><strong><?php esc_html_e('סוג תקופה', 'icomm-metrix'); ?></strong></label><br>
					<select name="report_mode" id="report_mode">
						<option value="month" <?php selected($ui_mode, 'month'); ?>><?php esc_html_e('חודש קלנדרי', 'icomm-metrix'); ?></option>
						<option value="custom" <?php selected($ui_mode, 'custom'); ?>><?php esc_html_e('טווח תאריכים', 'icomm-metrix'); ?></option>
					</select>
				</p>
				<p style="margin:0;" class="icomm-sm-period-month" <?php echo $ui_mode === 'custom' ? 'hidden' : ''; ?>>
					<label for="report_month"><strong><?php esc_html_e('חודש', 'icomm-metrix'); ?></strong></label><br>
					<select name="report_month" id="report_month">
						<?php foreach ($month_options as $opt) : ?>
							<option value="<?php echo esc_attr((string) $opt['value']); ?>" <?php selected($ui_month, (string) $opt['value']); ?>>
								<?php echo esc_html((string) $opt['label']); ?>
							</option>
						<?php endforeach; ?>
					</select>
				</p>
				<p style="margin:0;" class="icomm-sm-period-custom" <?php echo $ui_mode !== 'custom' ? 'hidden' : ''; ?>>
					<label for="report_start"><strong><?php esc_html_e('מתאריך', 'icomm-metrix'); ?></strong></label><br>
					<input type="text" class="regular-text" name="report_start" id="report_start" value="<?php echo esc_attr($ui_mode === 'custom' ? IComm_SM_Dates::format($ui_start) : ''); ?>" dir="ltr" placeholder="dd/mm/yyyy" inputmode="numeric" autocomplete="off" pattern="\d{1,2}/\d{1,2}/\d{4}" />
				</p>
				<p style="margin:0;" class="icomm-sm-period-custom" <?php echo $ui_mode !== 'custom' ? 'hidden' : ''; ?>>
					<label for="report_end"><strong><?php esc_html_e('עד תאריך', 'icomm-metrix'); ?></strong></label><br>
					<input type="text" class="regular-text" name="report_end" id="report_end" value="<?php echo esc_attr($ui_mode === 'custom' ? IComm_SM_Dates::format($ui_end) : ''); ?>" dir="ltr" placeholder="dd/mm/yyyy" inputmode="numeric" autocomplete="off" pattern="\d{1,2}/\d{1,2}/\d{4}" />
				</p>
				<p style="margin:0;">
					<button type="submit" class="button button-secondary"><?php esc_html_e('הצג דוח', 'icomm-metrix'); ?></button>
				</p>
				<p class="description icomm-sm-period-custom" style="margin:0;flex-basis:100%;" <?php echo $ui_mode !== 'custom' ? 'hidden' : ''; ?>>
					<?php esc_html_e('פורמט תאריך: dd/mm/yyyy (לדוגמה 18/07/2026)', 'icomm-metrix'); ?>
				</p>
			</form>
			<script>
			(function () {
				var form = document.getElementById('icomm-sm-report-period-form');
				if (!form) return;
				var mode = form.querySelector('#report_mode');
				function sync() {
					var custom = mode && mode.value === 'custom';
					form.querySelectorAll('.icomm-sm-period-month').forEach(function (el) { el.hidden = custom; });
					form.querySelectorAll('.icomm-sm-period-custom').forEach(function (el) { el.hidden = !custom; });
				}
				if (mode) mode.addEventListener('change', sync);
				sync();
			})();
			</script>
		</div>
	<?php endif; ?>

	<?php if ($mail_flash === 'ok') : ?>
		<div class="notice notice-success is-dismissible"><p><?php esc_html_e('הדוח נשלח ללקוח בהצלחה (HTML במייל, כמו בתצוגה כאן).', 'icomm-metrix'); ?></p></div>
	<?php elseif ($mail_flash === 'err') : ?>
		<div class="notice notice-error is-dismissible"><p>
			<?php
			$err = isset($_GET['client_mail_err']) ? sanitize_key((string) $_GET['client_mail_err']) : 'send_failed';
			$msg = __('שליחת הדוח נכשלה.', 'icomm-metrix');
			if ($err === 'invalid_email') {
				$msg = __('כתובת מייל לא תקינה.', 'icomm-metrix');
			} elseif ($err === 'feature_locked') {
				$msg = __('שליחה ללקוח זמינה ב-PRO.', 'icomm-metrix');
			}
			echo esc_html($msg);
			$detail = get_transient('icomm_sm_client_mail_err_' . get_current_user_id());
			if (is_string($detail) && $detail !== '') {
				delete_transient('icomm_sm_client_mail_err_' . get_current_user_id());
				echo ' <code dir="ltr">' . esc_html($detail) . '</code>';
			}
			?>
		</p></div>
	<?php elseif ($mail_flash === 'locked') : ?>
		<div class="notice notice-warning is-dismissible"><p><?php esc_html_e('שליחה ללקוח זמינה ב-PRO.', 'icomm-metrix'); ?></p></div>
	<?php endif; ?>

	<?php if (!$locked && $can_mail) : ?>
		<div style="background:#fff;border:1px solid #c3c4c7;padding:16px 18px;margin:16px 0;max-width:760px;">
			<h2 style="margin-top:0;"><?php esc_html_e('שליחה ללקוח', 'icomm-metrix'); ?></h2>
			<p class="description" style="margin-top:0;">
				<?php if (!empty($s['client_report_enabled'])) : ?>
					<?php
					echo esc_html(sprintf(
						__('שליחה אוטומטית פעילה: כל יום %d בחודש ל-%s', 'icomm-metrix'),
						(int) ($s['client_report_day'] ?? 1),
						$default_mail !== '' ? $default_mail : __('(לא הוגדר מייל)', 'icomm-metrix')
					));
					?>
				<?php else : ?>
					<?php esc_html_e('שליחה אוטומטית כבויה. אפשר לשלוח ידנית כאן, או להפעיל אוטומציה בהגדרות.', 'icomm-metrix'); ?>
				<?php endif; ?>
			</p>
			<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="display:flex;flex-wrap:wrap;gap:10px;align-items:flex-end;">
				<?php wp_nonce_field('icomm_sm_send_client_report'); ?>
				<input type="hidden" name="action" value="icomm_sm_send_client_report" />
				<input type="hidden" name="report_mode" value="<?php echo esc_attr($ui_mode); ?>" />
				<input type="hidden" name="report_month" value="<?php echo esc_attr($ui_month); ?>" />
				<input type="hidden" name="report_start" value="<?php echo esc_attr($ui_start); ?>" />
				<input type="hidden" name="report_end" value="<?php echo esc_attr($ui_end); ?>" />
				<p style="margin:0;">
					<label for="client_mail_to"><strong><?php esc_html_e('מייל לשליחה ידנית', 'icomm-metrix'); ?></strong></label><br>
					<input type="email" class="regular-text" name="client_mail_to" id="client_mail_to" value="<?php echo esc_attr($default_mail); ?>" dir="ltr" required />
				</p>
				<p style="margin:0;">
					<button type="submit" class="button button-primary"><?php esc_html_e('שלח עכשיו', 'icomm-metrix'); ?></button>
				</p>
			</form>
			<?php if (!empty($last['at'])) : ?>
				<p class="description" style="margin:12px 0 0;">
					<?php
					echo esc_html(sprintf(
						__('שליחה אחרונה: %s אל %s (%s)', 'icomm-metrix'),
						wp_date('d/m/Y H:i', (int) $last['at']),
						(string) ($last['to'] ?? ''),
						!empty($last['ok']) ? __('הצלחה', 'icomm-metrix') : __('נכשל', 'icomm-metrix')
					));
					if (!empty($last['period'])) {
						echo ' · ' . esc_html((string) $last['period']);
					}
					?>
				</p>
			<?php endif; ?>
		</div>
	<?php endif; ?>

	<div class="icomm-sm-report-box <?php echo $locked ? 'icomm-sm-locked-preview' : ''; ?>" dir="rtl" lang="he" style="background:#f0f0f1;border:1px solid #c3c4c7;padding:20px;margin-top:16px;direction:rtl;text-align:right;">
		<?php echo IComm_SM_Report_Builder::monthly_client_report_html($period); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
	</div>

	<?php if (!$locked) : ?>
		<p style="margin-top:16px;display:flex;flex-wrap:wrap;gap:8px;align-items:center;">
			<a class="button button-secondary" href="<?php echo esc_url($print_url); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e('הדפס / שמור כ-PDF מהדפדפן', 'icomm-metrix'); ?></a>
			<a class="button" href="<?php echo esc_url(admin_url('admin.php?page=icomm-metrix-settings')); ?>"><?php esc_html_e('הגדרות שליחה אוטומטית', 'icomm-metrix'); ?></a>
		</p>
	<?php endif; ?>
</div>
