<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals
// phpcs:disable WordPress.Security.NonceVerification
// phpcs:disable WordPress.Security.ValidatedSanitizedInput
// phpcs:disable WordPress.WP.EnqueuedResourceParameters
// phpcs:disable WordPress.DB.PreparedSQL
// phpcs:disable WordPress.DB.PreparedSQLPlaceholders
// phpcs:disable WordPress.DB.DirectDatabaseQuery
// phpcs:disable WordPress.DB.SlowDBQuery
// phpcs:disable PluginCheck.Security.DirectDB
// phpcs:disable PluginCheck.CodeAnalysis
// phpcs:disable WordPressVIPMinimum

/**
 * GT BOGO Engine — Campaign Scheduler (Enterprise)
 *
 * @package GT_BOGO_Engine
 * @since   3.11.0
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
if ( ! current_user_can( 'manage_options' ) ) {
	return;
}

$is_pro       = function_exists( 'gt_bogo_has_pro' ) ? gt_bogo_has_pro() : false;
$message      = '';
$message_type = '';

global $wpdb;
$rtbl  = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->prefix . 'gtbogo_rules' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.PreparedSQLPlaceholders.UnnecessaryPrepare
$rules = $rtbl ? $wpdb->get_results( "SELECT id, name, status FROM {$wpdb->prefix}gtbogo_rules ORDER BY name ASC" ) : array(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.PreparedSQLPlaceholders.UnnecessaryPrepare

// ── Save Schedule ─────────────────────────────────────────────────────────
if ( $is_pro && isset( $_POST['gtbogo_save_schedule'] ) && check_admin_referer( 'gtbogo_save_schedule' ) ) {
	$schedules         = get_option( 'gtbogo_schedules', array() );
	$sid               = sanitize_text_field( $_POST['schedule_id'] ?? uniqid( 'sch_' ) );
	$schedules[ $sid ] = array(
		'name'            => sanitize_text_field( $_POST['sched_name'] ?? 'New Schedule' ),
		'rule_ids'        => array_map( 'intval', (array) ( $_POST['sched_rules'] ?? array() ) ),
		'start_date'      => sanitize_text_field( $_POST['sched_start'] ?? '' ),
		'end_date'        => sanitize_text_field( $_POST['sched_end'] ?? '' ),
		'start_time'      => sanitize_text_field( $_POST['sched_start_time'] ?? '00:00' ),
		'end_time'        => sanitize_text_field( $_POST['sched_end_time'] ?? '23:59' ),
		'days'            => array_map( 'sanitize_text_field', (array) ( $_POST['sched_days'] ?? array() ) ),
		'timezone'        => sanitize_text_field( $_POST['sched_tz'] ?? wp_timezone_string() ),
		'auto_activate'   => isset( $_POST['sched_auto_activate'] ),
		'auto_deactivate' => isset( $_POST['sched_auto_deactivate'] ),
		'repeat'          => sanitize_text_field( $_POST['sched_repeat'] ?? 'none' ),
		'repeat_every'    => intval( $_POST['sched_repeat_every'] ?? 1 ),
		'enabled'         => isset( $_POST['sched_enabled'] ),
		'note'            => sanitize_textarea_field( $_POST['sched_note'] ?? '' ),
		'created'         => $schedules[ $sid ]['created'] ?? current_time( 'mysql', true ),
	);
	update_option( 'gtbogo_schedules', $schedules );
	if ( function_exists( 'gt_bogo_log' ) ) {
		gt_bogo_log( 'Schedule saved', $schedules[ $sid ]['name'], 'success' );
	}
	$message      = 'Schedule saved.';
	$message_type = 'success';
}

// ── Delete Schedule ───────────────────────────────────────────────────────
if ( $is_pro && isset( $_GET['del_sched'] ) && check_admin_referer( 'del_sched_' . sanitize_text_field( $_GET['del_sched'] ) ) ) {
	$schedules = get_option( 'gtbogo_schedules', array() );
	$sid       = sanitize_text_field( $_GET['del_sched'] );
	if ( function_exists( 'gt_bogo_log' ) && isset( $schedules[ $sid ] ) ) {
		gt_bogo_log( 'Schedule deleted', $schedules[ $sid ]['name'], 'warn' );
	}
	unset( $schedules[ $sid ] );
	update_option( 'gtbogo_schedules', $schedules );
	$message      = 'Schedule deleted.';
	$message_type = 'success';
}

// ── Toggle Schedule ───────────────────────────────────────────────────────
if ( $is_pro && isset( $_GET['toggle_sched'] ) && check_admin_referer( 'toggle_sched_' . sanitize_text_field( $_GET['toggle_sched'] ) ) ) {
	$schedules = get_option( 'gtbogo_schedules', array() );
	$sid       = sanitize_text_field( $_GET['toggle_sched'] );
	if ( isset( $schedules[ $sid ] ) ) {
		$schedules[ $sid ]['enabled'] = ! ( $schedules[ $sid ]['enabled'] ?? true );
		update_option( 'gtbogo_schedules', $schedules );
		$message      = 'Schedule ' . ( $schedules[ $sid ]['enabled'] ? 'enabled' : 'disabled' ) . '.';
		$message_type = 'success';
	}
}

// ── Save Scheduler Settings ───────────────────────────────────────────────
if ( $is_pro && isset( $_POST['gtbogo_save_sched_settings'] ) && check_admin_referer( 'gtbogo_sched_settings' ) ) {
	update_option( 'gtbogo_sched_cron_enabled', isset( $_POST['cron_enabled'] ) );
	update_option( 'gtbogo_sched_log_changes', isset( $_POST['log_changes'] ) );
	update_option( 'gtbogo_sched_notify_email', sanitize_email( $_POST['notify_email'] ?? get_option( 'admin_email' ) ) );
	update_option( 'gtbogo_sched_notify_on', isset( $_POST['notify_on'] ) );
	$message      = 'Scheduler settings saved.';
	$message_type = 'success';
}

$schedules    = get_option( 'gtbogo_schedules', array() );
$cron_enabled = get_option( 'gtbogo_sched_cron_enabled', true );
$log_changes  = get_option( 'gtbogo_sched_log_changes', true );
$notify_email = get_option( 'gtbogo_sched_notify_email', get_option( 'admin_email' ) );
$notify_on    = get_option( 'gtbogo_sched_notify_on', false );

$active_schedules = count( array_filter( $schedules, fn( $s )=> ! empty( $s['enabled'] ) ) );
$wp_tz            = wp_timezone_string();
$now_local        = new DateTime( 'now', new DateTimeZone( $wp_tz ) );

// Determine schedule status
function gt_sched_status( $s, $now ) {
	if ( empty( $s['enabled'] ) ) {
		return array( 'inactive', 'Inactive', '#94a3b8' );
	}
	$start = $s['start_date'] ? new DateTime( $s['start_date'] . ' ' . ( $s['start_time'] ?? '00:00' ), $now->getTimezone() ) : null;
	$end   = $s['end_date'] ? new DateTime( $s['end_date'] . ' ' . ( $s['end_time'] ?? '23:59' ), $now->getTimezone() ) : null;
	if ( $start && $now < $start ) {
		return array( 'upcoming', 'Upcoming', '#93c5fd' );
	}
	if ( $end && $now > $end ) {
		return array( 'expired', 'Expired', '#6b7280' );
	}
	return array( 'live', 'Live Now', '#86efac' );
}

// Edit mode
$edit_sid   = isset( $_GET['edit_sched'] ) ? sanitize_text_field( $_GET['edit_sched'] ) : '';
$edit_sched = ( $edit_sid && isset( $schedules[ $edit_sid ] ) ) ? $schedules[ $edit_sid ] : null;

$days_of_week = array(
	'mon' => 'Mon',
	'tue' => 'Tue',
	'wed' => 'Wed',
	'thu' => 'Thu',
	'fri' => 'Fri',
	'sat' => 'Sat',
	'sun' => 'Sun',
);

require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>
<div class="gt-page-header gt-animate-in">
	<div>
		<h1 class="gt-page-title">⏰ Campaign Scheduler</h1>
		<p class="gt-page-subtitle">Schedule BOGO rules to activate and deactivate automatically — by date, time window, or day of week</p>
	</div>
	<div style="display:flex;gap:8px;align-items:center">
		<span class="gt-badge gt-badge-active"><?php echo esc_html( count( $schedules ) ); ?> Schedule<?php echo count( $schedules ) !== 1 ? 's' : ''; ?></span>
		<span class="gt-badge <?php echo esc_html( $cron_enabled ) ? 'gt-badge-active' : 'gt-badge-warn'; ?>"><?php echo esc_html( $cron_enabled ) ? '● Cron Active' : '⚠ Cron Off'; ?></span>
	</div>
</div>
<?php
if ( $message ) :
	?>
	<div class="gt-notice gt-notice-<?php echo esc_attr( $message_type ); ?> gt-animate-in">✓ <?php echo esc_html( $message ); ?></div><?php endif; ?>

<?php if ( ! $is_pro ) : ?>
<div class="gt-pro-gate gt-animate-in">
	<span class="gt-pro-gate-icon">⏰</span>
	<h2>PRO License Required</h2>
	<p>The Campaign Scheduler automates BOGO rule activation and deactivation — run flash sales, weekend deals, and seasonal campaigns without manual intervention.</p>
	<div style="display:grid;grid-template-columns:repeat(2,1fr);gap:12px;max-width:480px;margin:24px auto 0">
		<?php foreach ( array( 'Date range scheduling with time windows', 'Day-of-week recurring schedules', 'Automatic rule activation and deactivation', 'Email notification on schedule changes' ) as $f ) : ?>
		<div style="display:flex;align-items:flex-start;gap:8px;text-align:left"><span style="color:#e10000;font-weight:700">—</span><span style="font-size:13px;color:var(--gt-soft)"><?php echo esc_html( $f ); ?></span></div>
		<?php endforeach; ?>
	</div>
	<div style="margin-top:24px;display:flex;justify-content:center;gap:12px">
		<a href="https://graphictshirts.shop/bogo/" target="_blank" rel="noopener" class="gt-btn gt-btn-primary">Purchase PRO — $499/yr</a>
	</div>
</div>
<?php endif; ?>
<?php $has_sched_pack = function_exists( 'gt_bogo_feature_available' ) && ( gt_bogo_feature_available( 'flash_sale' ) || gt_bogo_feature_available( 'seasonal' ) ); ?>
<?php if ( $is_pro && ! $has_sched_pack ) : ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px;border-color:rgba(225,0,0,0.25);background:rgba(225,0,0,0.04)">
	<div style="display:flex;align-items:center;justify-content:space-between;gap:20px;padding:18px 24px;flex-wrap:wrap">
		<div style="display:flex;align-items:center;gap:14px">
			<span style="font-size:26px">⏰</span>
			<div>
				<div style="font-size:14px;font-weight:800;color:var(--gt-white);margin-bottom:3px">Pack Required to Create Schedules</div>
				<div style="font-size:13px;color:var(--gt-subtle)">Unlock scheduling by purchasing the <strong style="color:var(--gt-white)">Flash Sale Engine</strong> or <strong style="color:var(--gt-white)">Seasonal Promotions</strong> pack</div>
			</div>
		</div>
		<div style="display:flex;gap:10px;flex-shrink:0;flex-wrap:wrap">
			<div id="paypal-container-FR592Y6D8FBML" style="min-height:40px;min-width:150px"></div>
			<div id="paypal-container-H6F4MX7NACP8E" style="min-height:40px;min-width:150px"></div>
		</div>
	</div>
</div>
<?php endif; ?>
<?php if ( $is_pro ) : ?>

<!-- METRICS -->
<div class="gt-metrics gt-animate-in" style="margin-bottom:20px">
	<div class="gt-metric" style="--gt-metric-c:#e10000">
		<span class="gt-metric-icon">⏰</span>
		<div class="gt-metric-label">Total Schedules</div>
		<div class="gt-metric-value"><?php echo esc_html( count( $schedules ) ); ?></div>
		<div class="gt-metric-trend"><?php echo esc_html( $active_schedules ); ?> enabled</div>
	</div>
	<?php
	$live_count     = 0;
	$upcoming_count = 0;
	foreach ( $schedules as $s ) {
		[$status] = gt_sched_status( $s, $now_local );
		if ( $status === 'live' ) {
			++$live_count;
		} if ( $status === 'upcoming' ) {
			++$upcoming_count;
		}
	}
	?>
	<div class="gt-metric" style="--gt-metric-c:#22c55e">
		<span class="gt-metric-icon">🟢</span>
		<div class="gt-metric-label">Live Now</div>
		<div class="gt-metric-value"><?php echo esc_html( $live_count ); ?></div>
		<div class="gt-metric-trend">Actively running</div>
	</div>
	<div class="gt-metric" style="--gt-metric-c:#3b82f6">
		<span class="gt-metric-icon">🔜</span>
		<div class="gt-metric-label">Upcoming</div>
		<div class="gt-metric-value"><?php echo esc_html( $upcoming_count ); ?></div>
		<div class="gt-metric-trend">Scheduled to start</div>
	</div>
	<div class="gt-metric" style="--gt-metric-c:#8b5cf6">
		<span class="gt-metric-icon">🕐</span>
		<div class="gt-metric-label">Store Timezone</div>
		<div class="gt-metric-value" style="font-size:13px"><?php echo esc_html( $now_local->format( 'g:i A' ) ); ?></div>
		<div class="gt-metric-trend"><?php echo esc_html( $wp_tz ); ?></div>
	</div>
</div>

<!-- SCHEDULE LIST -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header">
		<h2 class="gt-card-title">📅 Schedules</h2>
		<a href="?page=gt-bogo-engine&tab=scheduler&new_sched=1" class="gt-btn gt-btn-primary gt-btn-sm">+ New Schedule</a>
	</div>
	<?php if ( ! empty( $schedules ) ) : ?>
	<div style="display:flex;flex-direction:column;gap:10px">
		<?php
		foreach ( $schedules as $sid => $sched ) :
			[$st_key, $st_label, $st_color] = gt_sched_status( $sched, $now_local );
			$assigned_rules                 = array_filter( $rules, fn( $r ) => in_array( $r->id, array_map( 'intval', (array) ( $sched['rule_ids'] ?? array() ) ) ) );
			?>
		<div style="padding:16px 20px;border-radius:10px;border:1px solid <?php echo $st_key === 'live' ? 'rgba(34,197,94,0.3)' : ( $st_key === 'upcoming' ? 'rgba(59,130,246,0.15)' : 'var(--gt-border)' ); ?>;background:rgba(255,255,255,0.01)">
			<div style="display:flex;align-items:flex-start;justify-content:space-between;flex-wrap:wrap;gap:12px">
				<div style="flex:1">
					<div style="display:flex;align-items:center;gap:10px;margin-bottom:6px">
						<span style="font-size:15px;font-weight:800;color:var(--gt-white)"><?php echo esc_html( $sched['name'] ); ?></span>
						<span style="font-size:13px;font-weight:700;color:<?php echo esc_html( $st_color ); ?>;background:rgba(255,255,255,0.04);padding:2px 10px;border-radius:50px;border:1px solid <?php echo esc_html( $st_color ); ?>30"><?php echo $st_key === 'live' ? '● ' : ''; ?><?php echo esc_html( $st_label ); ?></span>
					</div>
					<div style="font-size:13px;color:var(--gt-soft);display:flex;flex-wrap:wrap;gap:12px">
						<?php if ( $sched['start_date'] || $sched['end_date'] ) : ?>
						<span>📅 <?php echo esc_html( $sched['start_date'] ) ? esc_html( $sched['start_date'] . ' ' . $sched['start_time'] ) : 'Any start'; ?> → <?php echo esc_html( $sched['end_date'] ) ? esc_html( $sched['end_date'] . ' ' . $sched['end_time'] ) : 'No end'; ?></span>
						<?php endif; ?>
						<?php if ( ! empty( $sched['days'] ) ) : ?>
						<span>📆 <?php echo esc_html( implode( ', ', array_map( 'strtoupper', (array) $sched['days'] ) ) ); ?></span>
						<?php endif; ?>
						<?php if ( ! empty( $assigned_rules ) ) : ?>
						<span>🎯 <?php echo esc_html( implode( ', ', array_map( fn( $r )=>$r->name, $assigned_rules ) ) ); ?></span>
						<?php endif; ?>
						<?php if ( ! empty( $sched['repeat'] ) && $sched['repeat'] !== 'none' ) : ?>
						<span>↻ Repeats <?php echo esc_html( $sched['repeat'] ); ?></span>
						<?php endif; ?>
					</div>
					<?php
					if ( $sched['note'] ) :
						?>
						<div style="font-size:13px;color:var(--gt-subtle);margin-top:4px;font-style:italic"><?php echo esc_html( $sched['note'] ); ?></div><?php endif; ?>
				</div>
				<div style="display:flex;gap:8px;flex-wrap:wrap">
					<a href="?page=gt-bogo-engine&tab=scheduler&edit_sched=<?php echo esc_attr( $sid ); ?>" class="gt-btn gt-btn-ghost gt-btn-sm">✎ Edit</a>
					<a href="
					<?php
					echo esc_url(
						wp_nonce_url(
							add_query_arg(
								array(
									'toggle_sched' => $sid,
									'page'         => 'gt-bogo-engine',
									'tab'          => 'scheduler',
								),
								admin_url( 'admin.php' )
							),
							'toggle_sched_' . $sid
						)
					);
					?>
								" class="gt-btn gt-btn-ghost gt-btn-sm"><?php echo ! empty( $sched['enabled'] ) ? '⏸ Disable' : '▶ Enable'; ?></a>
					<a href="
					<?php
					echo esc_url(
						wp_nonce_url(
							add_query_arg(
								array(
									'del_sched' => $sid,
									'page'      => 'gt-bogo-engine',
									'tab'       => 'scheduler',
								),
								admin_url( 'admin.php' )
							),
							'del_sched_' . $sid
						)
					);
					?>
								" class="gt-btn gt-btn-ghost gt-btn-sm" style="color:#fca5a5" onclick="return confirm('Delete this schedule?')">✕</a>
				</div>
			</div>
		</div>
		<?php endforeach; ?>
	</div>
	<?php else : ?>
	<div style="text-align:center;padding:48px 24px">
		<div style="font-size:48px;margin-bottom:16px">⏰</div>
		<h3 style="color:var(--gt-white);margin:0 0 8px">No Schedules Yet</h3>
		<p class="gt-text-soft" style="font-size:13px">Create your first schedule to automate rule activation.</p>
		<a href="?page=gt-bogo-engine&tab=scheduler&new_sched=1" class="gt-btn gt-btn-primary gt-btn-sm" style="margin-top:16px">+ Create First Schedule</a>
	</div>
	<?php endif; ?>
</div>

<!-- SCHEDULE FORM -->
	<?php if ( isset( $_GET['new_sched'] ) || $edit_sched ) : ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px;border-color:rgba(225,0,0,0.2)">
	<div class="gt-card-header">
		<h2 class="gt-card-title"><?php echo esc_html( $edit_sched ) ? '✎ Edit: ' . esc_html( $edit_sched['name'] ) : '➕ New Schedule'; ?></h2>
		<a href="?page=gt-bogo-engine&tab=scheduler" class="gt-btn gt-btn-ghost gt-btn-sm">✕ Cancel</a>
	</div>
	<form method="post" action="">
		<?php wp_nonce_field( 'gtbogo_save_schedule' ); ?>
		<?php
		if ( $edit_sched ) :
			?>
			<input type="hidden" name="schedule_id" value="<?php echo esc_attr( $edit_sid ); ?>"><?php endif; ?>

		<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:20px">
			<div class="gt-form-group">
				<label class="gt-form-label">Schedule Name</label>
				<input type="text" name="sched_name" class="gt-input" value="<?php echo esc_attr( $edit_sched['name'] ?? '' ); ?>" placeholder="e.g. Black Friday BOGO" required id="gtbogo_sched_name" aria-label="Sched Name">
			</div>
			<div class="gt-form-group">
				<label class="gt-form-label">Timezone</label>
				<select name="sched_tz" class="gt-select">
					<?php
					$tzs = DateTimeZone::listIdentifiers();
					foreach ( $tzs as $tz ) :
						?>
					<option value="<?php echo esc_attr( $tz ); ?>" <?php selected( $edit_sched['timezone'] ?? $wp_tz, $tz ); ?>><?php echo esc_html( $tz ); ?></option><?php endforeach; ?>
				</select>
			</div>
		</div>

		<!-- DATE RANGE -->
		<div style="font-size:13px;font-weight:700;color:var(--gt-white);text-transform:uppercase;letter-spacing:1px;margin-bottom:10px">Date Range</div>
		<div style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:14px;margin-bottom:20px">
			<div class="gt-form-group" style="margin:0">
				<label class="gt-form-label">Start Date</label>
				<input type="date" name="sched_start" class="gt-input" value="<?php echo esc_attr( $edit_sched['start_date'] ?? '' ); ?>" id="gtbogo_sched_start" aria-label="Sched Start">
				<div class="gt-form-hint">Leave blank for immediate start</div>
			</div>
			<div class="gt-form-group" style="margin:0">
				<label class="gt-form-label">Start Time</label>
				<input type="time" name="sched_start_time" class="gt-input" value="<?php echo esc_attr( $edit_sched['start_time'] ?? '00:00' ); ?>" id="gtbogo_sched_start_time" aria-label="Sched Start Time">
			</div>
			<div class="gt-form-group" style="margin:0">
				<label class="gt-form-label">End Date</label>
				<input type="date" name="sched_end" class="gt-input" value="<?php echo esc_attr( $edit_sched['end_date'] ?? '' ); ?>" id="gtbogo_sched_end" aria-label="Sched End">
				<div class="gt-form-hint">Leave blank for no expiry</div>
			</div>
			<div class="gt-form-group" style="margin:0">
				<label class="gt-form-label">End Time</label>
				<input type="time" name="sched_end_time" class="gt-input" value="<?php echo esc_attr( $edit_sched['end_time'] ?? '23:59' ); ?>" id="gtbogo_sched_end_time" aria-label="Sched End Time">
			</div>
		</div>

		<!-- DAYS OF WEEK -->
		<div style="font-size:13px;font-weight:700;color:var(--gt-white);text-transform:uppercase;letter-spacing:1px;margin-bottom:10px">Active Days of Week</div>
		<div style="display:flex;gap:8px;margin-bottom:20px;flex-wrap:wrap">
				<?php
				foreach ( $days_of_week as $d => $l ) :
					$sel = in_array( $d, (array) ( $edit_sched['days'] ?? array() ) );
					?>
			<label style="cursor:pointer">
				<input type="checkbox" name="sched_days[]" value="<?php echo esc_html( $d ); ?>" <?php checked( $sel ); ?> style="display:none">
				<span onclick="var cb=this.previousElementSibling;cb.checked=!cb.checked;this.style.background=cb.checked?'var(--gt-red)':'rgba(255,255,255,0.04)';this.style.borderColor=cb.checked?'var(--gt-red)':'rgba(255,255,255,0.1)';this.style.color=cb.checked?'#fff':'var(--gt-soft)'"
						style="display:inline-block;padding:8px 16px;border-radius:8px;font-size:13px;font-weight:700;border:1px solid <?php echo esc_html( $sel ) ? 'var(--gt-red)' : 'rgba(255,255,255,0.1)'; ?>;background:<?php echo esc_html( $sel ) ? 'var(--gt-red)' : 'rgba(255,255,255,0.04)'; ?>;color:<?php echo esc_html( $sel ) ? '#fff' : 'var(--gt-soft)'; ?>;transition:all 0.15s">
					<?php echo esc_html( $l ); ?>
				</span>
			</label>
				<?php endforeach; ?>
			<button type="button" class="gt-btn gt-btn-ghost gt-btn-sm" onclick="document.querySelectorAll('[name=\'sched_days[]\']').forEach(cb=>{cb.checked=true;cb.nextElementSibling.style.background='var(--gt-red)';cb.nextElementSibling.style.borderColor='var(--gt-red)';cb.nextElementSibling.style.color='#fff'})">All</button>
			<button type="button" class="gt-btn gt-btn-ghost gt-btn-sm" onclick="document.querySelectorAll('[name=\'sched_days[]\']').forEach(cb=>{cb.checked=false;cb.nextElementSibling.style.background='rgba(255,255,255,0.04)';cb.nextElementSibling.style.borderColor='rgba(255,255,255,0.1)';cb.nextElementSibling.style.color='var(--gt-soft)'})">None</button>
		</div>
		<div style="font-size:13px;color:var(--gt-subtle);margin-bottom:20px">Leave all days unselected to run every day within the date range</div>

		<!-- REPEAT -->
		<div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:20px">
			<div class="gt-form-group">
				<label class="gt-form-label">Repeat Pattern</label>
				<select name="sched_repeat" class="gt-select">
					<option value="none"    <?php selected( $edit_sched['repeat'] ?? 'none', 'none' ); ?>>No repeat — run once</option>
					<option value="weekly"  <?php selected( $edit_sched['repeat'] ?? '', 'weekly' ); ?>>Weekly</option>
					<option value="monthly" <?php selected( $edit_sched['repeat'] ?? '', 'monthly' ); ?>>Monthly</option>
					<option value="custom"  <?php selected( $edit_sched['repeat'] ?? '', 'custom' ); ?>>Custom interval</option>
				</select>
			</div>
			<div class="gt-form-group">
				<label class="gt-form-label">Repeat Every (days)</label>
				<input type="number" name="sched_repeat_every" class="gt-input" value="<?php echo esc_attr( $edit_sched['repeat_every'] ?? 1 ); ?>" min="1" max="365" id="gtbogo_sched_repeat_every" aria-label="Sched Repeat Every">
				<div class="gt-form-hint">Used for "Custom interval" only</div>
			</div>
		</div>

		<!-- RULES -->
			<?php if ( ! empty( $rules ) ) : ?>
		<div class="gt-form-group">
			<label class="gt-form-label">Rules to Schedule</label>
			<div style="max-height:200px;overflow-y:auto;border:1px solid var(--gt-border);border-radius:8px;padding:10px;display:flex;flex-direction:column;gap:6px">
				<?php
				foreach ( $rules as $rule ) :
					$sel = in_array( $rule->id, array_map( 'intval', (array) ( $edit_sched['rule_ids'] ?? array() ) ) );
					?>
				<label style="display:flex;align-items:center;gap:10px;cursor:pointer;padding:4px;border-radius:6px;transition:background 0.15s" onmouseover="this.style.background='rgba(255,255,255,0.03)'" onmouseout="this.style.background='none'">
					<input type="checkbox" name="sched_rules[]" value="<?php echo esc_html( $rule->id ); ?>" <?php checked( $sel ); ?> style="accent-color:var(--gt-red)">
					<span style="font-size:13px;color:var(--gt-white)"><?php echo esc_html( $rule->name ); ?></span>
					<span style="font-size:13px;color:<?php echo $rule->status === 'active' ? '#86efac' : '#94a3b8'; ?>;margin-left:auto"><?php echo esc_html( $rule->status ); ?></span>
				</label>
				<?php endforeach; ?>
			</div>
			<div class="gt-form-hint">Select which rules this schedule controls. If none selected, schedule applies to all rules.</div>
		</div>
		<?php endif; ?>

		<!-- AUTO CONTROL -->
		<div style="font-size:13px;font-weight:700;color:var(--gt-white);text-transform:uppercase;letter-spacing:1px;margin-bottom:10px;margin-top:4px">Automatic Rule Control</div>
		<div class="gt-setting-row">
			<div><div class="gt-setting-label">Auto-Activate Rules on Start</div><div class="gt-setting-desc">Automatically flip assigned rules to "Active" when the schedule start date/time is reached.</div></div>
			<label class="gt-toggle"><input type="checkbox" name="sched_auto_activate" value="1" <?php checked( ! empty( $edit_sched['auto_activate'] ?? true ) ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
		</div>
		<div class="gt-setting-row">
			<div><div class="gt-setting-label">Auto-Deactivate Rules on End</div><div class="gt-setting-desc">Automatically flip assigned rules to "Inactive" when the schedule end date/time is reached. Strongly recommended for flash sales.</div></div>
			<label class="gt-toggle"><input type="checkbox" name="sched_auto_deactivate" value="1" <?php checked( ! empty( $edit_sched['auto_deactivate'] ?? true ) ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
		</div>
		<div class="gt-setting-row" style="border:none">
			<div><div class="gt-setting-label">Schedule Enabled</div><div class="gt-setting-desc">Inactive schedules are saved but not evaluated by the cron runner.</div></div>
			<label class="gt-toggle"><input type="checkbox" name="sched_enabled" value="1" <?php checked( ! empty( $edit_sched['enabled'] ?? true ) ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
		</div>

		<div class="gt-form-group" style="margin-top:12px">
			<label class="gt-form-label">Internal Note</label>
			<textarea name="sched_note" class="gt-input" rows="2" placeholder="Campaign context, who approved this, etc."><?php echo esc_textarea( $edit_sched['note'] ?? '' ); ?></textarea>
		</div>

		<div style="display:flex;gap:12px;justify-content:flex-end;margin-top:8px">
			<a href="?page=gt-bogo-engine&tab=scheduler" class="gt-btn gt-btn-ghost">Cancel</a>
			<button type="submit" name="gtbogo_save_schedule" class="gt-btn gt-btn-primary" style="padding:12px 32px">💾 Save Schedule</button>
		</div>
	</form>
</div>
	<?php endif; ?>

<!-- SCHEDULER SETTINGS -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header"><h2 class="gt-card-title">⚙️ Scheduler Settings</h2></div>
	<form method="post" action="">
		<?php wp_nonce_field( 'gtbogo_sched_settings' ); ?>
		<div class="gt-setting-row">
			<div><div class="gt-setting-label">Enable WP-Cron Runner</div><div class="gt-setting-desc">Schedules are evaluated via WordPress cron. Requires WP-Cron to be running (standard on most hosts). Disable only if you run an external cron via server crontab.</div></div>
			<label class="gt-toggle"><input type="checkbox" name="cron_enabled" value="1" <?php checked( $cron_enabled ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
		</div>
		<div class="gt-setting-row">
			<div><div class="gt-setting-label">Log Schedule Changes</div><div class="gt-setting-desc">Write every automatic rule activation and deactivation to the Audit Log for traceability.</div></div>
			<label class="gt-toggle"><input type="checkbox" name="log_changes" value="1" <?php checked( $log_changes ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
		</div>
		<div class="gt-setting-row">
			<div><div class="gt-setting-label">Email Notification on Change</div><div class="gt-setting-desc">Send an email whenever a schedule auto-activates or deactivates a rule. Useful for high-stakes campaigns where you need to confirm everything fired correctly.</div></div>
			<label class="gt-toggle"><input type="checkbox" name="notify_on" value="1" <?php checked( $notify_on ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
		</div>
		<div class="gt-setting-row" style="border:none">
			<div><div class="gt-setting-label">Notification Email</div></div>
			<input type="email" name="notify_email" class="gt-input" style="width:280px" value="<?php echo esc_attr( $notify_email ); ?>" id="gtbogo_notify_email" aria-label="Notify Email">
		</div>
		<div style="margin-top:20px;text-align:right">
			<button type="submit" name="gtbogo_save_sched_settings" class="gt-btn gt-btn-primary" style="padding:12px 32px">💾 Save Settings</button>
		</div>
	</form>
</div>

<!-- GUIDANCE -->
<div class="gt-card gt-animate-in" style="background:linear-gradient(135deg,rgba(59,130,246,0.06),rgba(7,12,28,0));border-color:rgba(59,130,246,0.15)">
	<div class="gt-card-header"><h2 class="gt-card-title">🧠 Scheduling Strategy Guide</h2></div>
	<div class="gt-feature-grid gt-feature-grid--2col">
		<div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Always Use Auto-Deactivate</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Enable auto-deactivate on every time-limited campaign without exception. A flash sale that runs 72 hours past its intended end date due to a missed manual update is one of the most common and costly mistakes in ecommerce promotions. Auto-deactivate eliminates this risk entirely.</div></div>
		<div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Weekend-Only Recurring Deals</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Create a weekly recurring schedule with Saturday and Sunday selected. This gives customers a reason to visit on weekends without permanently discounting your products. The schedule runs indefinitely until you disable it — no manual management required after initial setup.</div></div>
		<div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Peak Hour Time Windows</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Use the Analytics peak hour data to set precise time windows. If your peak is 7pm–9pm, schedule the deal to start at 6pm and end at 10pm. This creates urgency within your natural high-traffic window rather than running a 24-hour deal that loses its time-pressure effect.</div></div>
		<div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Pre-Schedule Black Friday in October</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Create your Black Friday schedule in October, test it on staging in early November, then leave it ready to auto-fire. This avoids last-minute setup pressure and gives you weeks to refine the rule configuration. Enable email notification so you get confirmed when it goes live on the day.</div></div>
	</div>
</div>

<?php endif; ?>
<?php require_once __DIR__ . '/../ui-system/wrapper-end.php'; ?>
