<?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 — Pack Configuration
 * Per-pack settings allowing store owners to customise thresholds,
 * amounts, email templates, and trigger settings for every active pack.
 *
 * @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 = '';

// ── Save handler ──────────────────────────────────────────────────────────────
if ( $is_pro && isset( $_POST['gtbogo_pack_config_nonce'] )
	&& wp_verify_nonce( $_POST['gtbogo_pack_config_nonce'], 'gtbogo_pack_config_save' ) ) {

	$pack_id = sanitize_text_field( $_POST['pack_id'] ?? '' );
	if ( $pack_id ) {
		$config = array(
			// Threshold amounts
			'threshold_1'             => floatval( $_POST['threshold_1'] ?? 0 ),
			'threshold_2'             => floatval( $_POST['threshold_2'] ?? 0 ),
			'threshold_3'             => floatval( $_POST['threshold_3'] ?? 0 ),
			// Discount values
			'discount_1'              => floatval( $_POST['discount_1'] ?? 0 ),
			'discount_2'              => floatval( $_POST['discount_2'] ?? 0 ),
			'discount_3'              => floatval( $_POST['discount_3'] ?? 0 ),
			// Email settings
			'email_enabled'           => (bool) ( $_POST['email_enabled'] ?? false ),
			'email_threshold_nudge'   => (bool) ( $_POST['email_threshold_nudge'] ?? false ),
			'email_deal_confirmation' => (bool) ( $_POST['email_deal_confirmation'] ?? false ),
			'email_deal_expiry'       => (bool) ( $_POST['email_deal_expiry'] ?? false ),
			'email_flash_alert'       => (bool) ( $_POST['email_flash_alert'] ?? false ),
			'email_cart_abandon'      => (bool) ( $_POST['email_cart_abandon'] ?? false ),
			'email_subject_prefix'    => sanitize_text_field( $_POST['email_subject_prefix'] ?? '' ),
			'email_custom_message'    => sanitize_textarea_field( $_POST['email_custom_message'] ?? '' ),
			// Trigger settings
			'threshold_nudge_within'  => floatval( $_POST['threshold_nudge_within'] ?? 15 ),
			'abandon_delay_minutes'   => intval( $_POST['abandon_delay_minutes'] ?? 30 ),
			'expiry_warn_hours'       => intval( $_POST['expiry_warn_hours'] ?? 24 ),
			// Pack label override
			'pack_label_override'     => sanitize_text_field( $_POST['pack_label_override'] ?? '' ),
		);
		update_option( 'gtbogo_pack_config_' . sanitize_key( $pack_id ), $config );
		$message      = 'Pack configuration saved.';
		$message_type = 'success';
	}
}

// ── Load active imported packs ────────────────────────────────────────────────
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
if ( ! $rtbl ) {
	echo '<div class="gt-notice gt-notice-warn">Database tables not found. Please deactivate and reactivate the plugin.</div>';
	require_once __DIR__ . '/../ui-system/wrapper-end.php';
	return;
}

$pack_sources = $wpdb->get_col(
	"SELECT DISTINCT pack_source FROM {$wpdb->prefix}gtbogo_rules WHERE pack_source != '' ORDER BY pack_source ASC"
);

// Current pack being configured
$active_pack = sanitize_text_field( $_GET['pack'] ?? ( $pack_sources[0] ?? '' ) );
$config      = $active_pack ? ( get_option( 'gtbogo_pack_config_' . sanitize_key( $active_pack ), array() ) ) : array();

// Pack rules
$pack_rules = $active_pack ? $wpdb->get_results(
	$wpdb->prepare( // 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
		"SELECT * FROM {$wpdb->prefix}gtbogo_rules WHERE pack_source=%s ORDER BY priority ASC",
		$active_pack
	),
	ARRAY_A
) : array();

require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>
<div class="gt-page-header gt-animate-in">
	<div>
		<h1 class="gt-page-title">⚙️ Pack Configuration</h1>
		<p class="gt-page-subtitle">Customise thresholds, amounts, and email triggers for each pack to match your store's pricing</p>
	</div>
	<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=my-packs' ) ); ?>" class="gt-btn gt-btn-ghost gt-btn-sm">
		← My Packs
	</a>
</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><?php esc_html_e( 'PRO License Required', 'gt-bogo-engine' ); ?></h2>
	<p><?php esc_html_e( 'Pack Configuration requires a PRO license.', 'gt-bogo-engine' ); ?></p>
</div>
<?php elseif ( empty( $pack_sources ) ) : ?>
<div class="gt-card gt-animate-in" 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"><?php esc_html_e( 'No Packs Imported Yet', 'gt-bogo-engine' ); ?></h3>
	<p class="gt-text-soft" style="font-size:13px" style="margin-bottom:24px"><?php esc_html_e( 'Import a Pro Pack from the vault to configure it here.', 'gt-bogo-engine' ); ?></p>
	<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=pro-rules' ) ); ?>" class="gt-btn gt-btn-primary"><?php esc_html_e( 'Browse Pro Packs', 'gt-bogo-engine' ); ?></a>
</div>
<?php else : ?>

<div style="display:grid;grid-template-columns:260px 1fr;gap:24px;align-items:start">

	<!-- Pack Selector Sidebar -->
	<div class="gt-card gt-animate-in" style="padding:0">
		<div style="padding:16px 20px;border-bottom:1px solid var(--gt-border)">
			<h3 style="margin:0;font-size:13px;font-weight:700;color:var(--gt-subtle);text-transform:uppercase;letter-spacing:.8px">Imported Packs</h3>
		</div>
		<div style="padding:8px 0">
			<?php
			foreach ( $pack_sources as $ps ) :
				$is_active_ps = $ps === $active_pack;
				$pc           = get_option( 'gtbogo_pack_config_' . sanitize_key( $ps ), array() );
				$configured   = ! empty( $pc );
				?>
			<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=pack-config&pack=' . urlencode( $ps ) ) ); ?>"
				style="display:flex;align-items:center;justify-content:space-between;padding:10px 20px;text-decoration:none;background:<?php echo $is_active_ps ? 'rgba(225,0,0,0.08)' : 'transparent'; ?>;border-left:3px solid <?php echo $is_active_ps ? 'var(--gt-red)' : 'transparent'; ?>">
				<span style="color:var(--gt-white);font-size:13px;font-weight:<?php echo $is_active_ps ? '700' : '400'; ?>"><?php echo esc_html( $ps ); ?></span>
				<?php if ( $configured ) : ?>
				<span style="font-size:13px;background:rgba(34,197,94,0.15);color:#4ade80;border:1px solid rgba(34,197,94,0.3);padding:2px 6px;border-radius:10px">Configured</span>
				<?php endif; ?>
			</a>
			<?php endforeach; ?>
		</div>
	</div>

	<!-- Config Panel -->
	<div class="gt-animate-in">
		<?php if ( $active_pack && ! empty( $pack_rules ) ) : ?>
		<form method="post">
			<?php wp_nonce_field( 'gtbogo_pack_config_save', 'gtbogo_pack_config_nonce' ); ?>
			<input type="hidden" name="pack_id" value="<?php echo esc_attr( $active_pack ); ?>">

			<!-- Pack Header -->
			<div class="gt-card" style="margin-bottom:20px">
				<div class="gt-card-header">
					<div>
						<h2 class="gt-card-title"><?php echo esc_html( $config['pack_label_override'] ?? $active_pack ); ?></h2>
						<p class="gt-text-soft" style="font-size:13px"><?php echo count( $pack_rules ); ?> rules imported</p>
					</div>
					<span class="gt-badge gt-badge-active">Configuring</span>
				</div>
				<div class="gt-card-body">
					<div class="gt-setting-row">
						<div>
							<div class="gt-setting-label"><?php esc_html_e( 'Pack Display Name', 'gt-bogo-engine' ); ?></div>
							<div class="gt-setting-desc"><?php esc_html_e( 'Override how this pack appears in your admin. Customers never see this.', 'gt-bogo-engine' ); ?></div>
						</div>
						<input type="text" name="pack_label_override" class="gt-input" style="max-width:260px"
								value="<?php echo esc_attr( $config['pack_label_override'] ?? '' ); ?>"
								placeholder="<?php echo esc_attr( $active_pack ); ?>" id="gtbogo_pack_label_override" aria-label="Pack Label Override">
					</div>
				</div>
			</div>

			<!-- Threshold & Amount Customisation -->
			<div class="gt-card" style="margin-bottom:20px">
				<div class="gt-card-header">
					<h2 class="gt-card-title">💰 Thresholds &amp; Amounts</h2>
					<span class="gt-text-soft" style="font-size:13px">Override the default amounts to match your store's pricing</span>
				</div>
				<div class="gt-card-body">
					<p style="color:var(--gt-subtle);font-size:13px;margin:0 0 20px;line-height:1.6">
						These values override the default pack amounts when the pack rules are applied. Set thresholds to match your average order values and discounts to match your margins. Leave at 0 to use the pack defaults.
					</p>

					<!-- Threshold overrides -->
					<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:16px;margin-bottom:20px">
						<?php
						$thresholds = array(
							array( 'threshold_1', 'Entry Threshold ($)', 'Default cart threshold for the entry-level rule' ),
							array( 'threshold_2', 'Mid Threshold ($)', 'Default cart threshold for the mid-tier rule' ),
							array( 'threshold_3', 'Premium Threshold ($)', 'Default cart threshold for the premium rule' ),
						);
						foreach ( $thresholds as [$name, $label, $desc] ) :
							?>
						<div>
							<div style="font-size:13px;font-weight:600;color:var(--gt-soft);margin-bottom:6px"><?php echo esc_html( $label ); ?></div>
							<div style="font-size:13px;color:var(--gt-subtle);margin-bottom:8px"><?php echo esc_html( $desc ); ?></div>
							<input type="number" name="<?php echo esc_attr( $name ); ?>" class="gt-input" style="width:100%"
									step="0.01" min="0"
									value="<?php echo esc_attr( $config[ $name ] ?? 0 ); ?>"
									placeholder="0 = use pack default" id="gtbogo_0___use_pack_default" aria-label="0 = use pack default">
						</div>
						<?php endforeach; ?>
					</div>

					<!-- Discount overrides -->
					<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:16px">
						<?php
						$discounts = array(
							array( 'discount_1', 'Entry Discount (%)', 'Override the entry-level discount percentage' ),
							array( 'discount_2', 'Mid Discount (%)', 'Override the mid-tier discount percentage' ),
							array( 'discount_3', 'Premium Discount (%)', 'Override the premium discount percentage' ),
						);
						foreach ( $discounts as [$name, $label, $desc] ) :
							?>
						<div>
							<div style="font-size:13px;font-weight:600;color:var(--gt-soft);margin-bottom:6px"><?php echo esc_html( $label ); ?></div>
							<div style="font-size:13px;color:var(--gt-subtle);margin-bottom:8px"><?php echo esc_html( $desc ); ?></div>
							<input type="number" name="<?php echo esc_attr( $name ); ?>" class="gt-input" style="width:100%"
									step="0.01" min="0" max="100"
									value="<?php echo esc_attr( $config[ $name ] ?? 0 ); ?>"
									placeholder="0 = use pack default" id="gtbogo_0___use_pack_default" aria-label="0 = use pack default">
						</div>
						<?php endforeach; ?>
					</div>

					<!-- Active rules reference -->
					<div style="margin-top:20px;padding:16px;background:rgba(255,255,255,0.02);border-radius:8px;border:1px solid var(--gt-border)">
						<p style="margin:0 0 10px;font-size:13px;font-weight:700;color:var(--gt-subtle);text-transform:uppercase;letter-spacing:.8px">Current Pack Rules</p>
						<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:8px">
							<?php
							foreach ( $pack_rules as $pr ) :
								$disc      = $pr['discount_type'] === 'percentage' || $pr['discount_type'] === 'percent'
									? floatval( $pr['discount_value'] ) . '%' : '$' . number_format( floatval( $pr['discount_value'] ), 2 );
								$threshold = floatval( $pr['min_cart_total'] ) > 0 ? ' · Min: $' . number_format( floatval( $pr['min_cart_total'] ), 2 ) : '';
								?>
							<div style="padding:8px 12px;background:rgba(255,255,255,0.03);border-radius:6px;border:1px solid var(--gt-border)">
								<div style="font-size:13px;font-weight:600;color:var(--gt-white);margin-bottom:2px"><?php echo esc_html( $pr['name'] ); ?></div>
								<div style="font-size:13px;color:var(--gt-subtle)">
									Buy <?php echo (int) $pr['buy_quantity']; ?> Get <?php echo (int) $pr['get_quantity']; ?> · <?php echo esc_html( $disc . $threshold ); ?>
								</div>
							</div>
							<?php endforeach; ?>
						</div>
					</div>
				</div>
			</div>

			<!-- Email Trigger Settings -->
			<div class="gt-card" style="margin-bottom:20px">
				<div class="gt-card-header">
					<h2 class="gt-card-title">📧 Email Triggers</h2>
					<span class="gt-text-soft" style="font-size:13px">Control exactly which emails fire for this pack and when</span>
				</div>
				<div class="gt-card-body">

					<div class="gt-setting-row">
						<div>
							<div class="gt-setting-label"><?php esc_html_e( 'Enable Emails for This Pack', 'gt-bogo-engine' ); ?></div>
							<div class="gt-setting-desc"><?php esc_html_e( 'Master toggle for all email triggers from this pack. Requires Customer Emails enabled in Settings.', 'gt-bogo-engine' ); ?></div>
						</div>
						<label class="gt-toggle">
							<input type="checkbox" name="email_enabled" value="1" <?php checked( ! empty( $config['email_enabled'] ) ); ?>>
							<span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span>
						</label>
					</div>

					<?php
					$triggers = array(
						array( 'email_deal_confirmation', 'Order Confirmation Email', 'Sent when customer completes an order with this pack\'s deal applied. Confirms savings and thanks the customer.' ),
						array( 'email_threshold_nudge', 'Threshold Nudge Email', 'Sent when customer\'s cart is within the nudge window of unlocking this pack\'s threshold deal. Encourages one more add to cart.' ),
						array( 'email_flash_alert', 'Flash Sale Alert Email', 'Broadcast to recent customers when a flash rule from this pack is activated. Drives immediate traffic to the deal.' ),
						array( 'email_cart_abandon', 'Cart Abandonment Email', 'Sent after the abandon delay when a customer leaves with this pack\'s deal in their cart. Recovers lost orders.' ),
						array( 'email_deal_expiry', 'Deal Expiry Warning Email', 'Sent to recent customers 24 hours before a scheduled rule from this pack expires. Creates urgency to act.' ),
					);
					foreach ( $triggers as [$name, $label, $desc] ) :
						?>
					<div class="gt-setting-row">
						<div>
							<div class="gt-setting-label"><?php echo esc_html( $label ); ?></div>
							<div class="gt-setting-desc"><?php echo esc_html( $desc ); ?></div>
						</div>
						<label class="gt-toggle">
							<input type="checkbox" name="<?php echo esc_attr( $name ); ?>" value="1" <?php checked( ! empty( $config[ $name ] ) ); ?>>
							<span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span>
						</label>
					</div>
					<?php endforeach; ?>

					<div class="gt-setting-row">
						<div>
							<div class="gt-setting-label"><?php esc_html_e( 'Email Subject Prefix', 'gt-bogo-engine' ); ?></div>
							<div class="gt-setting-desc"><?php esc_html_e( 'Optional prefix added to all emails from this pack. E.g. "[Flash Sale]" or "[Birthday]". Leave blank to use store name only.', 'gt-bogo-engine' ); ?></div>
						</div>
						<input type="text" name="email_subject_prefix" class="gt-input" style="max-width:200px"
								value="<?php echo esc_attr( $config['email_subject_prefix'] ?? '' ); ?>"
								placeholder="e.g. [Flash Sale]" id="gtbogo_email_subject_prefix" aria-label="Email Subject Prefix">
					</div>

					<div class="gt-setting-row" style="border:none">
						<div>
							<div class="gt-setting-label"><?php esc_html_e( 'Custom Email Message', 'gt-bogo-engine' ); ?></div>
							<div class="gt-setting-desc"><?php esc_html_e( 'Optional custom paragraph added to all emails from this pack. Describe the deal, create urgency, or add a personal message from the store.', 'gt-bogo-engine' ); ?></div>
						</div>
						<textarea name="email_custom_message" class="gt-input" style="max-width:320px;height:80px;resize:vertical"
									placeholder="e.g. This is our biggest deal of the year..."><?php echo esc_textarea( $config['email_custom_message'] ?? '' ); ?></textarea>
					</div>
				</div>
			</div>

			<!-- Trigger Timing Settings -->
			<div class="gt-card" style="margin-bottom:20px">
				<div class="gt-card-header">
					<h2 class="gt-card-title">⏱️ Trigger Timing</h2>
					<span class="gt-text-soft" style="font-size:13px">Fine-tune exactly when each email fires</span>
				</div>
				<div class="gt-card-body">
					<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:16px">
						<div>
							<div style="font-size:13px;font-weight:600;color:var(--gt-soft);margin-bottom:6px">Threshold Nudge Window ($)</div>
							<div style="font-size:13px;color:var(--gt-subtle);margin-bottom:8px">Send nudge email when cart is within this amount of the threshold. Default: $15.</div>
							<input type="number" name="threshold_nudge_within" class="gt-input" style="width:100%"
									step="0.01" min="1" max="50"
									value="<?php echo esc_attr( $config['threshold_nudge_within'] ?? 15 ); ?>" id="gtbogo_threshold_nudge_within" aria-label="Threshold Nudge Within">
						</div>
						<div>
							<div style="font-size:13px;font-weight:600;color:var(--gt-soft);margin-bottom:6px">Cart Abandon Delay (Minutes)</div>
							<div style="font-size:13px;color:var(--gt-subtle);margin-bottom:8px">Minutes of cart inactivity before abandonment email fires. Default: 30.</div>
							<input type="number" name="abandon_delay_minutes" class="gt-input" style="width:100%"
									min="5" max="1440"
									value="<?php echo esc_attr( $config['abandon_delay_minutes'] ?? 30 ); ?>" id="gtbogo_abandon_delay_minutes" aria-label="Abandon Delay Minutes">
						</div>
						<div>
							<div style="font-size:13px;font-weight:600;color:var(--gt-soft);margin-bottom:6px">Deal Expiry Warning (Hours Before)</div>
							<div style="font-size:13px;color:var(--gt-subtle);margin-bottom:8px">Hours before deal expires to send the expiry warning email. Default: 24.</div>
							<input type="number" name="expiry_warn_hours" class="gt-input" style="width:100%"
									min="1" max="72"
									value="<?php echo esc_attr( $config['expiry_warn_hours'] ?? 24 ); ?>" id="gtbogo_expiry_warn_hours" aria-label="Expiry Warn Hours">
						</div>
					</div>
				</div>
			</div>

			<div style="display:flex;gap:12px;align-items:center">
				<button type="submit" class="gt-btn gt-btn-primary">Save Pack Configuration</button>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=my-packs' ) ); ?>" class="gt-btn gt-btn-ghost">Cancel</a>
			</div>
		</form>
		<?php else : ?>
		<div class="gt-card" 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"><?php esc_html_e( 'Select a Pack', 'gt-bogo-engine' ); ?></h3>
			<p class="gt-text-soft" style="font-size:13px"><?php esc_html_e( 'Choose a pack from the left to configure its settings.', 'gt-bogo-engine' ); ?></p>
		</div>
		<?php endif; ?>
	</div>
</div>
<?php endif; ?>

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