<?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 — Deal Page Manager (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 = '';

// ── Create Deal Page ──────────────────────────────────────────────────────
if ( $is_pro && isset( $_POST['gtbogo_create_deal_page'] ) && check_admin_referer( 'gtbogo_create_deal_page' ) ) {
	$title    = sanitize_text_field( $_POST['deal_page_title'] ?? 'Our Deals' );
	$slug     = sanitize_title( $_POST['deal_page_slug'] ?? 'bogo-deals' );
	$layout   = sanitize_text_field( $_POST['deal_page_layout'] ?? 'grid' );
	$show     = array_map( 'sanitize_text_field', (array) ( $_POST['deal_page_show'] ?? array( 'active' ) ) );
	$heading  = sanitize_textarea_field( $_POST['deal_page_heading'] ?? '' );
	$sub      = sanitize_textarea_field( $_POST['deal_page_subtext'] ?? '' );
	$existing = get_page_by_path( $slug );
	if ( $existing ) {
		$message      = 'A page with this slug already exists. Edit it below or choose a different slug.';
		$message_type = 'warn';
	} else {
		$page_id = wp_insert_post(
			array(
				'post_title'   => $title,
				'post_name'    => $slug,
				'post_content' => '[gt_bogo_deals layout="' . $layout . '" show="' . implode( ',', $show ) . '" heading="' . esc_attr( $heading ) . '" subtext="' . esc_attr( $sub ) . '"]',
				'post_status'  => 'publish',
				'post_type'    => 'page',
			)
		);
		if ( $page_id && ! is_wp_error( $page_id ) ) {
			update_option( 'gtbogo_deal_page_id', $page_id );
			update_option( 'gtbogo_deal_page_layout', $layout );
			update_option( 'gtbogo_deal_page_show', $show );
			if ( function_exists( 'gt_bogo_log' ) ) {
				gt_bogo_log( 'Deal page created', 'Page ID ' . $page_id . ' — ' . $title, 'success' );
			}
			$message      = 'Deal page created successfully.';
			$message_type = 'success';
		} else {
			$message      = 'Failed to create page. Please check WordPress permissions.';
			$message_type = 'error';
		}
	}
}

// ── Update Deal Page Settings ─────────────────────────────────────────────
if ( $is_pro && isset( $_POST['gtbogo_update_deal_page'] ) && check_admin_referer( 'gtbogo_update_deal_page' ) ) {
	$page_id = intval( $_POST['existing_page_id'] ?? 0 );
	if ( $page_id && get_post( $page_id ) ) {
		$layout  = sanitize_text_field( $_POST['deal_page_layout'] ?? 'grid' );
		$show    = array_map( 'sanitize_text_field', (array) ( $_POST['deal_page_show'] ?? array( 'active' ) ) );
		$heading = sanitize_textarea_field( $_POST['deal_page_heading'] ?? '' );
		$sub     = sanitize_textarea_field( $_POST['deal_page_subtext'] ?? '' );
		wp_update_post(
			array(
				'ID'           => $page_id,
				'post_title'   => sanitize_text_field( $_POST['deal_page_title'] ?? get_the_title( $page_id ) ),
				'post_content' => '[gt_bogo_deals layout="' . $layout . '" show="' . implode( ',', $show ) . '" heading="' . esc_attr( $heading ) . '" subtext="' . esc_attr( $sub ) . '"]',
			)
		);
		update_option( 'gtbogo_deal_page_id', $page_id );
		update_option( 'gtbogo_deal_page_layout', $layout );
		update_option( 'gtbogo_deal_page_show', $show );
		if ( function_exists( 'gt_bogo_log' ) ) {
			gt_bogo_log( 'Deal page updated', 'Page ID ' . $page_id, 'info' );
		}
		$message      = 'Deal page updated.';
		$message_type = 'success';
	}
}

// ── Save display settings ─────────────────────────────────────────────────
if ( $is_pro && isset( $_POST['gtbogo_save_display'] ) && check_admin_referer( 'gtbogo_deal_display' ) ) {
	update_option(
		'gtbogo_deal_display',
		array(
			'show_countdown'  => isset( $_POST['show_countdown'] ),
			'show_savings'    => isset( $_POST['show_savings'] ),
			'show_badge'      => isset( $_POST['show_badge'] ),
			'show_expiry'     => isset( $_POST['show_expiry'] ),
			'badge_text'      => sanitize_text_field( $_POST['badge_text'] ?? 'Deal' ),
			'empty_message'   => sanitize_text_field( $_POST['empty_message'] ?? 'No active deals at this time.' ),
			'columns_desktop' => intval( $_POST['columns_desktop'] ?? 3 ),
			'columns_mobile'  => intval( $_POST['columns_mobile'] ?? 1 ),
			'sort_by'         => sanitize_text_field( $_POST['sort_by'] ?? 'priority' ),
			'cards_per_page'  => intval( $_POST['cards_per_page'] ?? 12 ),
			'show_pagination' => isset( $_POST['show_pagination'] ),
		)
	);
	if ( function_exists( 'gt_bogo_log' ) ) {
		gt_bogo_log( 'Deal page display settings updated', '', 'info' );
	}
	$message      = 'Display settings saved.';
	$message_type = 'success';
}

// ── Delete deal page link ─────────────────────────────────────────────────
if ( $is_pro && isset( $_POST['gtbogo_unlink_page'] ) && check_admin_referer( 'gtbogo_unlink_page' ) ) {
	delete_option( 'gtbogo_deal_page_id' );
	$message      = 'Deal page unlinked. The WordPress page was not deleted.';
	$message_type = 'success';
}

$deal_page_id = get_option( 'gtbogo_deal_page_id', 0 );
$deal_page    = $deal_page_id ? get_post( $deal_page_id ) : null;
$display      = get_option(
	'gtbogo_deal_display',
	array(
		'show_countdown'  => true,
		'show_savings'    => true,
		'show_badge'      => true,
		'show_expiry'     => true,
		'badge_text'      => 'Deal',
		'empty_message'   => 'No active deals at this time.',
		'columns_desktop' => 3,
		'columns_mobile'  => 1,
		'sort_by'         => 'priority',
		'cards_per_page'  => 12,
		'show_pagination' => true,
	)
);
$saved_layout = get_option( 'gtbogo_deal_page_layout', 'grid' );
$saved_show   = get_option( 'gtbogo_deal_page_show', array( 'active' ) );

// WordPress pages list for linking existing
$wp_pages = get_pages(
	array(
		'post_status' => 'publish',
		'sort_column' => 'post_title',
	)
);

// Shortcode builder vars
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 FROM {$wpdb->prefix}gtbogo_rules WHERE status='active' 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

require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>
<div class="gt-page-header gt-animate-in">
	<div>
		<h1 class="gt-page-title">📄 Deal Page Manager</h1>
		<p class="gt-page-subtitle">Create and manage a public-facing deals page powered by the <code>[gt_bogo_deals]</code> shortcode</p>
	</div>
	<?php if ( $deal_page ) : ?>
	<div style="display:flex;gap:8px">
		<a href="<?php echo esc_url( get_permalink( $deal_page_id ) ); ?>" target="_blank" class="gt-btn gt-btn-ghost gt-btn-sm">👁 View Page ↗</a>
		<a href="<?php echo esc_url( get_edit_post_link( $deal_page_id ) ); ?>" target="_blank" class="gt-btn gt-btn-ghost gt-btn-sm">✎ Edit in WordPress ↗</a>
	</div>
	<?php endif; ?>
</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 Deal Page Manager creates a branded, public-facing deals page where customers can browse all active BOGO promotions — no theme coding required.</p>
	<div style="display:grid;grid-template-columns:repeat(2,1fr);gap:12px;max-width:480px;margin:24px auto 0">
		<?php foreach ( array( 'One-click deal page creation', 'Grid and list layout options', 'Countdown timers and savings badges', 'Fully theme-aware — inherits your store design' ) 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 else : ?>

<!-- STATUS BANNER -->
	<?php if ( $deal_page ) : ?>
<div class="gt-notice gt-notice-success gt-animate-in" style="margin-bottom:20px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px">
	<span>✓ Deal page active: <strong><?php echo esc_html( $deal_page->post_title ); ?></strong> — <a href="<?php echo esc_url( get_permalink( $deal_page_id ) ); ?>" target="_blank" style="color:inherit;font-weight:700"><?php echo esc_url( get_permalink( $deal_page_id ) ); ?> ↗</a></span>
	<form method="post" action="" style="margin:0">
		<?php wp_nonce_field( 'gtbogo_unlink_page' ); ?>
		<button type="submit" name="gtbogo_unlink_page" class="gt-btn gt-btn-ghost gt-btn-sm" onclick="return confirm('Unlink this page? It will remain on your site but no longer be tracked here.')">✕ Unlink</button>
	</form>
</div>
<?php else : ?>
<div class="gt-notice gt-animate-in" style="background:rgba(245,158,11,0.07);border-color:rgba(245,158,11,0.25);color:#fcd34d;margin-bottom:20px">
	⚠ No deal page configured. Create one below or link an existing page.
</div>
<?php endif; ?>

<!-- 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">Page Status</div>
		<div class="gt-metric-value" style="font-size:16px"><?php echo $deal_page ? esc_html( ucfirst( $deal_page->post_status ) ) : 'None'; ?></div>
		<div class="gt-metric-trend"><?php echo $deal_page ? '#' . esc_html( $deal_page_id ) : 'Not created'; ?></div>
	</div>
	<div class="gt-metric" style="--gt-metric-c:#22c55e">
		<span class="gt-metric-icon">🎯</span>
		<div class="gt-metric-label">Active Rules</div>
		<div class="gt-metric-value"><?php echo esc_html( count( $rules ) ); ?></div>
		<div class="gt-metric-trend">Shown on deal page</div>
	</div>
	<div class="gt-metric" style="--gt-metric-c:#3b82f6">
		<span class="gt-metric-icon">📐</span>
		<div class="gt-metric-label">Layout</div>
		<div class="gt-metric-value" style="font-size:16px"><?php echo esc_html( ucfirst( $saved_layout ) ); ?></div>
		<div class="gt-metric-trend"><?php echo esc_html( $display['columns_desktop'] ); ?> col desktop</div>
	</div>
	<div class="gt-metric" style="--gt-metric-c:#8b5cf6">
		<span class="gt-metric-icon">🔖</span>
		<div class="gt-metric-label">WordPress Pages</div>
		<div class="gt-metric-value"><?php echo esc_html( count( $wp_pages ) ); ?></div>
		<div class="gt-metric-trend">Available to link</div>
	</div>
</div>

<!-- TABS -->
<div style="display:flex;gap:0;border-bottom:1px solid var(--gt-border);margin-bottom:24px">
	<?php
	foreach ( array(
		'create'    => '➕ Create New',
		'link'      => '🔗 Link Existing',
		'display'   => '🎨 Display Settings',
		'shortcode' => '〈/〉 Shortcode Builder',
	) as $t => $l ) :
		?>
	<button onclick="document.querySelectorAll('.dp-tab').forEach(e=>e.style.display='none');document.getElementById('dp-<?php echo esc_html( $t ); ?>').style.display='block';document.querySelectorAll('.dp-tab-btn').forEach(b=>b.setAttribute('data-active','false'));this.setAttribute('data-active','true')"
			class="dp-tab-btn" data-active="<?php echo $t === 'create' && ! $deal_page || ( $t === 'display' && $deal_page ) ? 'true' : 'false'; ?>"
			style="padding:10px 20px;font-size:13px;font-weight:600;border:none;background:none;cursor:pointer;color:var(--gt-soft);border-bottom:2px solid transparent;transition:all 0.2s"
			onfocus="this.style.outline='none'"
			onmouseover="this.style.color='var(--gt-white)'"
			onmouseout="this.style.color=this.getAttribute('data-active')==='true'?'var(--gt-white)':'var(--gt-soft)'"><?php echo esc_html( $l ); ?></button>
	<?php endforeach; ?>
</div>
<style>.dp-tab-btn[data-active="true"]{color:var(--gt-white)!important;border-bottom-color:var(--gt-red)!important}</style>

<!-- TAB: CREATE -->
<div class="dp-tab" id="dp-create" style="display:<?php echo ( ! $deal_page ) ? 'block' : 'none'; ?>">
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header"><h2 class="gt-card-title">➕ Create Deal Page</h2><span class="gt-text-soft" style="font-size:13px">Creates a new published WordPress page with the BOGO shortcode</span></div>
	<form method="post" action="">
		<?php wp_nonce_field( 'gtbogo_create_deal_page' ); ?>
		<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:20px">
			<div class="gt-form-group">
				<label class="gt-form-label">Page Title</label>
				<input type="text" name="deal_page_title" class="gt-input" value="Our Deals" placeholder="e.g. Current Promotions" id="gtbogo_deal_page_title" aria-label="Deal Page Title">
				<div class="gt-form-hint">Displayed as the H1 on the page and in browser tabs</div>
			</div>
			<div class="gt-form-group">
				<label class="gt-form-label">Page Slug (URL)</label>
				<div style="display:flex;align-items:center;gap:0">
					<span style="padding:10px 12px;background:rgba(255,255,255,0.03);border:1px solid var(--gt-border);border-right:none;border-radius:8px 0 0 8px;font-size:13px;color:var(--gt-subtle);white-space:nowrap"><?php echo esc_url( trailingslashit( home_url() ) ); ?></span>
					<input type="text" name="deal_page_slug" class="gt-input" value="bogo-deals" placeholder="bogo-deals" style="border-radius:0 8px 8px 0;flex:1" id="gtbogo_deal_page_slug" aria-label="Deal Page Slug">
				</div>
				<div class="gt-form-hint">Your deal page URL</div>
			</div>
		</div>
		<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:20px">
			<div class="gt-form-group">
				<label class="gt-form-label">Page Heading (optional)</label>
				<input type="text" name="deal_page_heading" class="gt-input" placeholder="e.g. Exclusive Offers" id="gtbogo_deal_page_heading" aria-label="Deal Page Heading">
				<div class="gt-form-hint">Short headline shown above deal cards</div>
			</div>
			<div class="gt-form-group">
				<label class="gt-form-label">Subtitle / Description (optional)</label>
				<input type="text" name="deal_page_subtext" class="gt-input" placeholder="e.g. Add qualifying items to your cart" id="gtbogo_deal_page_subtext" aria-label="Deal Page Subtext">
				<div class="gt-form-hint">Supporting text shown below the heading</div>
			</div>
		</div>
		<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:24px">
			<div class="gt-form-group">
				<label class="gt-form-label">Layout</label>
				<select name="deal_page_layout" class="gt-select">
					<option value="grid">Grid — cards in columns</option>
					<option value="list">List — full-width rows</option>
					<option value="compact">Compact — minimal detail</option>
					<option value="hero">Hero — large featured card first</option>
				</select>
			</div>
			<div class="gt-form-group">
				<label class="gt-form-label">Show Rules</label>
				<div style="display:flex;flex-direction:column;gap:6px;margin-top:4px">
					<?php
					foreach ( array(
						'active'    => 'Active rules only',
						'scheduled' => 'Scheduled (upcoming) rules',
						'all'       => 'All non-expired rules',
					) as $k => $v ) :
						?>
					<label style="display:flex;align-items:center;gap:8px;cursor:pointer;font-size:13px;color:var(--gt-soft)">
						<input type="checkbox" name="deal_page_show[]" value="<?php echo esc_html( $k ); ?>" <?php checked( in_array( $k, array( 'active' ) ) ); ?> style="accent-color:var(--gt-red)">
																																																								<?php echo esc_html( $v ); ?>
					</label>
					<?php endforeach; ?>
				</div>
			</div>
		</div>
		<div style="text-align:right">
			<button type="submit" name="gtbogo_create_deal_page" class="gt-btn gt-btn-primary" style="padding:12px 32px">🚀 Create Deal Page</button>
		</div>
	</form>
</div>
</div>

<!-- TAB: LINK EXISTING -->
<div class="dp-tab" id="dp-link" style="display:none">
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header"><h2 class="gt-card-title">🔗 Link an Existing Page</h2><span class="gt-text-soft" style="font-size:13px">Track an existing WordPress page that already uses the deal shortcode</span></div>
	<form method="post" action="">
		<?php wp_nonce_field( 'gtbogo_update_deal_page' ); ?>
		<div style="display:grid;grid-template-columns:1fr auto;gap:12px;align-items:end">
			<div class="gt-form-group" style="margin:0">
				<label class="gt-form-label">Select Existing Page</label>
				<select name="existing_page_id" class="gt-select">
					<option value="0">— Select a page —</option>
					<?php foreach ( $wp_pages as $p ) : ?>
					<option value="<?php echo esc_html( $p->ID ); ?>" <?php selected( $deal_page_id, $p->ID ); ?>><?php echo esc_html( $p->post_title ); ?> (<?php echo esc_url( get_permalink( $p->ID ) ); ?>)</option>
					<?php endforeach; ?>
				</select>
			</div>
			<button type="submit" name="gtbogo_update_deal_page" class="gt-btn gt-btn-primary" style="padding:12px 24px">🔗 Link Page</button>
		</div>
		<div style="margin-top:16px;padding:12px 16px;background:rgba(255,255,255,0.02);border-radius:8px;font-size:13px;color:var(--gt-soft)">
			ℹ️ Linking a page does not change its content. You must manually add <code style="background:rgba(255,255,255,0.06);padding:2px 6px;border-radius:4px;font-size:13px">[gt_bogo_deals]</code> to the page content via the WordPress editor if it is not already there.
		</div>
	</form>
</div>

<!-- SHORTCODE REFERENCE for manual pages -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header"><h2 class="gt-card-title">〈/〉 Manual Shortcode</h2></div>
	<p style="font-size:13px;color:var(--gt-soft);margin-bottom:12px">Add this to any page, post, or widget to display your active deals:</p>
	<div style="background:rgba(0,0,0,0.3);border-radius:8px;padding:14px 18px;font-family:'DM Mono',monospace;font-size:13px;color:#86efac;border:1px solid rgba(255,255,255,0.06);word-break:break-all">
		[gt_bogo_deals layout="grid" show="active" heading="Current Promotions" subtext="Add qualifying items to enjoy complimentary products"]
	</div>
</div>
</div>

<!-- TAB: DISPLAY SETTINGS -->
<div class="dp-tab" id="dp-display" style="display:<?php echo esc_html( $deal_page ) ? 'block' : 'none'; ?>">
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header"><h2 class="gt-card-title">🎨 Display Settings</h2><span class="gt-text-soft" style="font-size:13px">Controls how deal cards render on your deal page</span></div>
	<form method="post" action="">
		<?php wp_nonce_field( 'gtbogo_deal_display' ); ?>
		<?php
		if ( $deal_page ) :
			?>
			<input type="hidden" name="existing_page_id" value="<?php echo esc_html( $deal_page_id ); ?>"><?php endif; ?>

		<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px">
			<div>
				<div style="font-size:13px;font-weight:700;color:var(--gt-white);text-transform:uppercase;letter-spacing:1px;margin-bottom:12px">Deal Card Elements</div>
				<?php
				foreach ( array(
					array( 'show_countdown', 'Show Countdown Timer', 'Displays time remaining for rules with an end date' ),
					array( 'show_savings', 'Show Savings Amount', 'Shows estimated savings (e.g. "Save up to $20")' ),
					array( 'show_badge', 'Show Deal Badge', 'Renders a coloured badge on each deal card' ),
					array( 'show_expiry', 'Show Expiry Date', 'Displays the end date below the deal title' ),
					array( 'show_pagination', 'Enable Pagination', 'Paginate deals if more than the per-page limit' ),
				) as $s ) :
					?>
				<div class="gt-setting-row" style="padding:10px 0">
					<div><div class="gt-setting-label"><?php echo esc_html( $s[1] ); ?></div><div class="gt-setting-desc"><?php echo esc_html( $s[2] ); ?></div></div>
					<label class="gt-toggle"><input type="checkbox" name="<?php echo esc_html( $s[0] ); ?>" value="1" <?php checked( ! empty( $display[ $s[0] ] ) ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
				</div>
				<?php endforeach; ?>
			</div>
			<div>
				<div style="font-size:13px;font-weight:700;color:var(--gt-white);text-transform:uppercase;letter-spacing:1px;margin-bottom:12px">Layout Options</div>
				<div class="gt-form-group">
					<label class="gt-form-label">Desktop Columns</label>
					<select name="columns_desktop" class="gt-select">
						<?php
						foreach ( array( 1, 2, 3, 4 ) as $c ) :
							?>
							<option value="<?php echo esc_html( $c ); ?>" <?php selected( $display['columns_desktop'], $c ); ?>><?php echo esc_html( $c ); ?> column<?php echo $c > 1 ? 's' : ''; ?></option><?php endforeach; ?>
					</select>
				</div>
				<div class="gt-form-group">
					<label class="gt-form-label">Mobile Columns</label>
					<select name="columns_mobile" class="gt-select">
						<?php
						foreach ( array( 1, 2 ) as $c ) :
							?>
							<option value="<?php echo esc_html( $c ); ?>" <?php selected( $display['columns_mobile'], $c ); ?>><?php echo esc_html( $c ); ?> column<?php echo $c > 1 ? 's' : ''; ?></option><?php endforeach; ?>
					</select>
				</div>
				<div class="gt-form-group">
					<label class="gt-form-label">Deals Per Page</label>
					<input type="number" name="cards_per_page" class="gt-input" value="<?php echo esc_attr( $display['cards_per_page'] ); ?>" min="1" max="100" id="gtbogo_cards_per_page" aria-label="Cards Per Page">
				</div>
				<div class="gt-form-group">
					<label class="gt-form-label">Sort Deals By</label>
					<select name="sort_by" class="gt-select">
						<option value="priority"   <?php selected( $display['sort_by'], 'priority' ); ?>>Priority (highest first)</option>
						<option value="name"       <?php selected( $display['sort_by'], 'name' ); ?>>Name (A-Z)</option>
						<option value="expiry"     <?php selected( $display['sort_by'], 'expiry' ); ?>>Expiry (soonest first)</option>
						<option value="newest"     <?php selected( $display['sort_by'], 'newest' ); ?>>Newest First</option>
						<option value="discount"   <?php selected( $display['sort_by'], 'discount' ); ?>>Largest Discount First</option>
					</select>
				</div>
				<div class="gt-form-group">
					<label class="gt-form-label">Badge Text</label>
					<input type="text" name="badge_text" class="gt-input" value="<?php echo esc_attr( $display['badge_text'] ); ?>" placeholder="Deal" maxlength="20" id="gtbogo_badge_text" aria-label="Badge Text">
					<div class="gt-form-hint">Short label on each deal card badge. Keep under 12 characters.</div>
				</div>
				<div class="gt-form-group">
					<label class="gt-form-label">Empty State Message</label>
					<input type="text" name="empty_message" class="gt-input" value="<?php echo esc_attr( $display['empty_message'] ); ?>" placeholder="No active deals at this time." id="gtbogo_empty_message" aria-label="Empty Message">
					<div class="gt-form-hint">Shown when no matching rules are active</div>
				</div>
			</div>
		</div>
		<div style="margin-top:24px;text-align:right">
			<button type="submit" name="gtbogo_save_display" class="gt-btn gt-btn-primary" style="padding:12px 32px">💾 Save Display Settings</button>
		</div>
	</form>
</div>
</div>

<!-- TAB: SHORTCODE BUILDER -->
<div class="dp-tab" id="dp-shortcode" style="display:none">
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header"><h2 class="gt-card-title">〈/〉 Visual Shortcode Builder</h2><span class="gt-text-soft" style="font-size:13px">Build a custom shortcode to embed anywhere</span></div>
	<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:20px" id="sc-builder">
		<div>
			<div class="gt-form-group">
				<label class="gt-form-label">Layout</label>
				<select class="gt-select sc-field" data-key="layout" onchange="buildSC()">
					<option value="grid">Grid</option><option value="list">List</option>
					<option value="compact">Compact</option><option value="hero">Hero</option>
				</select>
			</div>
			<div class="gt-form-group">
				<label class="gt-form-label">Heading</label>
				<input type="text" class="gt-input sc-field" data-key="heading" placeholder="Leave blank to hide" oninput="buildSC()" id="gtbogo_leave_blank_to_hide" aria-label="Leave blank to hide">
			</div>
			<div class="gt-form-group">
				<label class="gt-form-label">Subtext</label>
				<input type="text" class="gt-input sc-field" data-key="subtext" placeholder="Supporting description" oninput="buildSC()" id="gtbogo_supporting_description" aria-label="Supporting description">
			</div>
			<div class="gt-form-group">
				<label class="gt-form-label">Max Deals to Show</label>
				<input type="number" class="gt-input sc-field" data-key="limit" value="12" min="1" max="100" oninput="buildSC()" id="gtbogo_dk_limit" aria-label="Limit">
			</div>
		</div>
		<div>
			<div class="gt-form-group">
				<label class="gt-form-label">Show Rules</label>
				<div style="display:flex;flex-direction:column;gap:6px;margin-top:4px">
					<?php
					foreach ( array(
						'active'    => 'Active only',
						'scheduled' => 'Include scheduled',
						'all'       => 'All non-expired',
					) as $k => $v ) :
						?>
					<label style="display:flex;align-items:center;gap:8px;cursor:pointer;font-size:13px;color:var(--gt-soft)">
						<input type="checkbox" class="sc-multi" data-key="show" value="<?php echo esc_html( $k ); ?>" <?php checked( $k === 'active' ); ?> onchange="buildSC()" style="accent-color:var(--gt-red)">
																						<?php echo esc_html( $v ); ?>
					</label>
					<?php endforeach; ?>
				</div>
			</div>
			<div class="gt-form-group">
				<label class="gt-form-label">Specific Rule IDs (optional)</label>
				<input type="text" class="gt-input sc-field" data-key="rule_ids" placeholder="e.g. 3,7,12" oninput="buildSC()" id="gtbogo_e_g__3_7_12" aria-label="e.g. 3,7,12">
				<div class="gt-form-hint">Comma-separated IDs to show only specific rules</div>
			</div>
			<div class="gt-form-group">
				<label class="gt-form-label">Sort By</label>
				<select class="gt-select sc-field" data-key="sort" onchange="buildSC()">
					<option value="priority">Priority</option><option value="name">Name</option>
					<option value="expiry">Expiry</option><option value="newest">Newest</option>
				</select>
			</div>
			<div class="gt-form-group">
				<label class="gt-form-label">Hide When Empty</label>
				<select class="gt-select sc-field" data-key="hide_empty" onchange="buildSC()">
					<option value="0">Show empty state message</option>
					<option value="1">Hide entire block if no deals</option>
				</select>
			</div>
		</div>
	</div>
	<!-- Live Output -->
	<div style="font-size:13px;font-weight:700;color:var(--gt-white);text-transform:uppercase;letter-spacing:1px;margin-bottom:8px">Generated Shortcode</div>
	<div id="sc-output" onclick="var r=document.createRange();r.selectNode(this);window.getSelection().removeAllRanges();window.getSelection().addRange(r)"
		style="background:rgba(0,0,0,0.35);border-radius:8px;padding:14px 18px;font-family:'DM Mono',monospace;font-size:13px;color:#86efac;border:1px solid rgba(255,255,255,0.06);word-break:break-all;cursor:pointer;user-select:all"
		title="Click to select all"></div>
	<div style="font-size:13px;color:var(--gt-subtle);margin-top:6px">Click the shortcode to select it, then Ctrl/Cmd+C to copy</div>
	<script>
	function buildSC() {
		var fields = document.querySelectorAll('.sc-field');
		var attrs = {};
		fields.forEach(function(f) {
			if (f.value && f.value !== '') attrs[f.dataset.key] = f.value;
		});
		var multiKeys = {};
		document.querySelectorAll('.sc-multi:checked').forEach(function(c) {
			if (!multiKeys[c.dataset.key]) multiKeys[c.dataset.key] = [];
			multiKeys[c.dataset.key].push(c.value);
		});
		Object.keys(multiKeys).forEach(function(k) { attrs[k] = multiKeys[k].join(','); });
		var sc = '[gt_bogo_deals';
		Object.keys(attrs).forEach(function(k) { if (attrs[k]) sc += ' ' + k + '="' + attrs[k] + '"'; });
		sc += ']';
		document.getElementById('sc-output').textContent = sc;
	}
	buildSC();
	</script>
</div>
</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">🧠 Deal Page 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">Link From Your Navigation</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Add your deal page to your site's primary navigation menu. Customers who see a "Deals" link in the nav convert at 2–4x the rate of customers who discover deals only through cart notification. The page pays for itself.</div></div>
		<div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Hero Layout for Flagship Campaigns</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">During major campaigns (Black Friday, holiday), switch to Hero layout. Your highest-priority rule renders as a large featured card at the top, creating an immediate focal point. Switch back to Grid after the campaign ends.</div></div>
		<div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Countdown Timers Drive Urgency</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Enable countdown timers for all rules that have an end date. Visible countdown timers on deal pages increase click-through by showing customers the deal is genuinely time-limited — not a permanent "sale" that erodes brand value.</div></div>
		<div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Sort by Expiry for Urgency Stacking</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Setting sort order to "Expiry (soonest first)" means the deal that ends first always shows at the top. This creates natural urgency stacking — as each deal expires, the next one rises to top position, continuously drawing customers back to check what is ending soon.</div></div>
	</div>
</div>

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