<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class AIEO_DMM_Custom_Tabs extends AIEO_DMM_Module_Base {

	const OPTION_KEY      = 'aieo_dmm_custom_tabs';
	const MIGRATED_OPTION = 'aieo_dmm_custom_tabs_migrated_at';
	const SLOT_COUNT      = 5;

	public function get_id()       { return 'custom_tabs'; }
	public function get_label()    { return __( 'Custom Tabs', 'ai-eshop-optimizer' ); }
	public function get_priority() { return 58; }
	public function get_group()    { return 'product_display'; }

	
	
	

	public static function default_config() {
		$d = array();
		for ( $i = 1; $i <= self::SLOT_COUNT; $i++ ) {
			$label = '';
			if ( 1 === $i ) {
				$label = __( 'Application', 'ai-eshop-optimizer' );
			} elseif ( 2 === $i ) {
				$label = __( 'Ingredients', 'ai-eshop-optimizer' );
			}
			$d[ $i ] = array( 'enabled' => false, 'label' => $label );
		}
		return $d;
	}

	public static function get_slots_config() {
		$stored = get_option( self::OPTION_KEY, array() );
		if ( ! is_array( $stored ) ) {
			$stored = array();
		}
		$out = self::default_config();
		foreach ( $out as $i => $def ) {
			if ( isset( $stored[ $i ] ) && is_array( $stored[ $i ] ) ) {
				$out[ $i ] = array(
					'enabled' => ! empty( $stored[ $i ]['enabled'] ),
					'label'   => isset( $stored[ $i ]['label'] ) ? (string) $stored[ $i ]['label'] : $def['label'],
				);
			}
		}
		return $out;
	}

	
	public static function get_enabled_slots() {
		$out = array();
		foreach ( self::get_slots_config() as $i => $s ) {
			if ( ! empty( $s['enabled'] ) && '' !== trim( (string) $s['label'] ) ) {
				$out[ $i ] = $s;
			}
		}
		return $out;
	}

	
	
	

	private static function table() {
		global $wpdb;
		return $wpdb->prefix . 'aieo_dmm_custom_tabs';
	}

	private static function table_ok() {
		global $wpdb;
		static $ok = null;
		if ( null === $ok ) {
			$t  = self::table();
			$ok = ( (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $t ) ) === $t );
		}
		return $ok;
	}

	
	public static function get_all_content( $product_id ) {
		$product_id = (int) $product_id;
		if ( $product_id <= 0 || ! self::table_ok() ) {
			return array();
		}
		global $wpdb;
		$t = self::table();
		
		$rows = (array) $wpdb->get_results( $wpdb->prepare( "SELECT slot_index, content FROM `{$t}` WHERE product_id = %d", $product_id ), ARRAY_A );
		$out  = array();
		foreach ( $rows as $r ) {
			$out[ (int) $r['slot_index'] ] = (string) $r['content'];
		}
		return $out;
	}

	public static function save_content( $product_id, $slot, $html ) {
		$product_id = (int) $product_id;
		$slot       = (int) $slot;
		if ( $product_id <= 0 || $slot < 1 || $slot > self::SLOT_COUNT || ! self::table_ok() ) {
			return;
		}
		global $wpdb;
		$t    = self::table();
		$html = (string) $html;
		if ( '' === trim( $html ) ) {
			$wpdb->delete( $t, array( 'product_id' => $product_id, 'slot_index' => $slot ), array( '%d', '%d' ) );
			return;
		}
		$wpdb->replace(
			$t,
			array(
				'product_id' => $product_id,
				'slot_index' => $slot,
				'content'    => $html,
				'updated_at' => current_time( 'mysql', true ),
			),
			array( '%d', '%d', '%s', '%s' )
		);
	}

	
	
	

	public function register_hooks() {
		add_action( 'wp_ajax_aieo_dmm_custom_tabs_save', array( $this, 'ajax_save' ) );
		add_action( 'wp_ajax_aieo_dmm_custom_tabs_migrate', array( $this, 'ajax_migrate' ) );

		
		add_filter( 'woocommerce_product_data_tabs', array( $this, 'add_product_data_tab' ) );
		add_action( 'woocommerce_product_data_panels', array( $this, 'render_product_data_panel' ) );
		add_action( 'woocommerce_process_product_meta', array( $this, 'save_product_meta' ) );

		
		add_filter( 'woocommerce_product_tabs', array( $this, 'add_tabs' ) );

		
		add_action( 'init', array( $this, 'maybe_replace_legacy_tabs' ), 20 );
	}

	
	public function maybe_replace_legacy_tabs() {
		if ( empty( self::get_enabled_slots() ) ) {
			return;
		}
		if ( function_exists( 'custom_pods_product_tabs' ) ) {
			remove_filter( 'woocommerce_product_tabs', 'custom_pods_product_tabs' );
			remove_filter( 'woocommerce_product_tabs', 'custom_pods_product_tabs', 10 );
		}
	}

	
	
	

	public function add_tabs( $tabs ) {
		global $product;
		if ( ! $product || ! is_a( $product, 'WC_Product' ) ) {
			return $tabs;
		}
		$content = self::get_all_content( $product->get_id() );
		foreach ( self::get_enabled_slots() as $i => $slot ) {
			$html = isset( $content[ $i ] ) ? trim( (string) $content[ $i ] ) : '';
			if ( '' === $html ) {
				continue; 
			}
			$tabs[ 'aieo_custom_tab_' . (int) $i ] = array(
				'title'    => $slot['label'],
				'priority' => 50 + (int) $i, 
				'callback' => static function () use ( $html ) {
					echo wpautop( wp_kses_post( $html ) ); 
				},
			);
		}
		return $tabs;
	}

	
	
	

	public function add_product_data_tab( $tabs ) {
		$tabs['aieo_custom_tabs'] = array(
			'label'    => __( 'Custom Tabs', 'ai-eshop-optimizer' ),
			'target'   => 'aieo_custom_tabs_product_data',
			'priority' => 66,
			'class'    => array(),
		);
		return $tabs;
	}

	public function render_product_data_panel() {
		global $post;
		echo '<div id="aieo_custom_tabs_product_data" class="panel woocommerce_options_panel hidden">';
		$enabled = self::get_enabled_slots();
		if ( empty( $enabled ) ) {
			echo '<p style="padding:12px;">' . esc_html__( 'No custom tabs are enabled yet — enable + name them under e-shop Manager → Storefront Display → Custom Tabs.', 'ai-eshop-optimizer' ) . '</p></div>';
			return;
		}
		$content = self::get_all_content( (int) $post->ID );
		echo '<div style="padding:10px 12px;">';
		foreach ( $enabled as $i => $slot ) {
			echo '<p style="margin:10px 0 4px;"><strong>' . esc_html( $slot['label'] ) . '</strong></p>';
			wp_editor(
				isset( $content[ $i ] ) ? (string) $content[ $i ] : '',
				'aieo_custom_tab_' . (int) $i,
				array(
					'textarea_name' => 'aieo_custom_tab_' . (int) $i,
					'media_buttons' => true,
					'tinymce'       => true,
					'quicktags'     => true,
					'textarea_rows' => 8,
				)
			);
		}
		echo '</div></div>';
	}

	public function save_product_meta( $product_id ) {
		$product_id = (int) $product_id;
		if ( ! current_user_can( 'edit_product', $product_id ) ) {
			return;
		}
		foreach ( self::get_enabled_slots() as $i => $slot ) {
			$key = 'aieo_custom_tab_' . (int) $i;
			
			if ( ! isset( $_POST[ $key ] ) ) {
				continue;
			}
			
			$html = wp_kses_post( wp_unslash( $_POST[ $key ] ) );
			self::save_content( $product_id, (int) $i, $html );
		}
	}

	
	
	

	public function render_subtab() {
		$slots = self::get_slots_config();
		$nonce = wp_create_nonce( AIEO_DMM::NONCE_ACTION );
		$ajax  = admin_url( 'admin-ajax.php' );

		global $wpdb;
		$t         = self::table();
		$table_ok  = ( (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $t ) ) === $t );
		
		$row_count = $table_ok ? (int) $wpdb->get_var( "SELECT COUNT(*) FROM `{$t}`" ) : 0;
		$migrated  = (int) get_option( self::MIGRATED_OPTION, 0 );
		?>
		<div class="aieo-dmm-section">
			<h2><?php esc_html_e( 'Custom Tabs', 'ai-eshop-optimizer' ); ?></h2>
			<p class="description" style="max-width:840px;">
				<?php esc_html_e( 'Up to five extra product tabs with rich-text content per product. Enable + rename the ones you want, then edit each product\'s content in the "Custom Tabs" panel on the product edit screen. A tab with no content for a given product is hidden automatically.', 'ai-eshop-optimizer' ); ?>
			</p>

			<form id="aieo-dmm-custom-tabs-form" class="aieo-dmm-card">
				<table class="form-table">
					<thead><tr><th style="width:90px;"><?php esc_html_e( 'Enabled', 'ai-eshop-optimizer' ); ?></th><th><?php esc_html_e( 'Tab name', 'ai-eshop-optimizer' ); ?></th></tr></thead>
					<tbody>
					<?php foreach ( $slots as $i => $s ) : ?>
						<tr>
							<td><label><input type="checkbox" name="enabled_<?php echo (int) $i; ?>" value="1" <?php checked( ! empty( $s['enabled'] ) ); ?>></label></td>
							<td><input type="text" name="label_<?php echo (int) $i; ?>" value="<?php echo esc_attr( $s['label'] ); ?>" class="regular-text" placeholder="<?php printf( esc_attr__( 'Tab %d', 'ai-eshop-optimizer' ), (int) $i ); ?>"></td>
						</tr>
					<?php endforeach; ?>
					</tbody>
				</table>
				<p>
					<button type="button" class="button button-primary" id="aieo-ct-save"><?php esc_html_e( 'Save tabs', 'ai-eshop-optimizer' ); ?></button>
					<span id="aieo-ct-status" style="margin-left:10px;font-weight:600;"></span>
				</p>
			</form>

			<div class="aieo-dmm-card">
				<h3><?php esc_html_e( 'Migrate from Pods', 'ai-eshop-optimizer' ); ?></h3>
				<table class="form-table">
					<tr><th><?php esc_html_e( 'Storage', 'ai-eshop-optimizer' ); ?></th><td>
						<?php
						if ( $table_ok ) {
							echo '<span style="color:#15803d;">✓ ' . esc_html( sprintf(  __( '%d rows', 'ai-eshop-optimizer' ), $row_count ) ) . '</span>';
						} else {
							echo '<span style="color:#b91c1c;">✗ ' . esc_html__( 'table missing', 'ai-eshop-optimizer' ) . '</span>';
						}
						?>
					</td></tr>
					<tr><th><?php esc_html_e( 'Last migration', 'ai-eshop-optimizer' ); ?></th><td>
						<?php echo $migrated ? esc_html( sprintf(  __( '%s ago', 'ai-eshop-optimizer' ), human_time_diff( $migrated ) ) ) : esc_html__( 'Never', 'ai-eshop-optimizer' ); ?>
					</td></tr>
				</table>
				<p class="description"><?php esc_html_e( 'Copies the legacy Pods fields into Custom Tabs: usage → Tab 1, specification → Tab 2 (and enables + names those two if they are still at their defaults). Re-running is safe — it overwrites, never duplicates.', 'ai-eshop-optimizer' ); ?></p>
				<p>
					<button type="button" class="button button-primary" id="aieo-ct-migrate"><?php esc_html_e( 'Migrate from Pods (usage / specification)', 'ai-eshop-optimizer' ); ?></button>
					<span id="aieo-ct-migrate-status" style="margin-left:10px;font-weight:600;"></span>
				</p>
			</div>
		</div>
		<script>
		(function(){
			var nonce = <?php echo wp_json_encode( $nonce ); ?>, ajax = <?php echo wp_json_encode( $ajax ); ?>;
			function post(action, form, cb){
				var fd = form ? new FormData(form) : new FormData();
				fd.set('action', action); fd.set('nonce', nonce);
				fetch(ajax, { method:'POST', credentials:'same-origin', body: fd })
					.then(function(r){ return r.json(); }).then(cb)
					.catch(function(){ cb({ success:false, data:{ message:'Network error.' } }); });
			}
			var sBtn=document.getElementById('aieo-ct-save'), sS=document.getElementById('aieo-ct-status');
			if (sBtn) sBtn.addEventListener('click', function(){
				sS.style.color='#6b7280'; sS.textContent='<?php echo esc_js( __( 'Saving…', 'ai-eshop-optimizer' ) ); ?>';
				post('aieo_dmm_custom_tabs_save', document.getElementById('aieo-dmm-custom-tabs-form'), function(j){
					if (j && j.success){ sS.style.color='#15803d'; sS.textContent=j.data.message; }
					else { sS.style.color='#b91c1c'; sS.textContent=(j&&j.data&&j.data.message)||'Save failed.'; }
				});
			});
			var mBtn=document.getElementById('aieo-ct-migrate'), mS=document.getElementById('aieo-ct-migrate-status');
			if (mBtn) mBtn.addEventListener('click', function(){
				mBtn.disabled=true; mS.style.color='#6b7280'; mS.textContent='<?php echo esc_js( __( 'Migrating…', 'ai-eshop-optimizer' ) ); ?>';
				post('aieo_dmm_custom_tabs_migrate', null, function(j){
					mBtn.disabled=false;
					if (j && j.success){ var st=j.data.stats||{}; mS.style.color='#15803d'; mS.textContent='✓ '+(st.migrated||0)+' / '+(st.processed||0); setTimeout(function(){ location.reload(); }, 900); }
					else { mS.style.color='#b91c1c'; mS.textContent=(j&&j.data&&j.data.message)||'Migration failed.'; }
				});
			});
		})();
		</script>
		<?php
	}

	public function ajax_save() {
		AIEO_DMM::verify_ajax_request();
		$clean = array();
		for ( $i = 1; $i <= self::SLOT_COUNT; $i++ ) {
			$clean[ $i ] = array(
				'enabled' => ! empty( $_POST[ 'enabled_' . $i ] ),
				'label'   => isset( $_POST[ 'label_' . $i ] ) ? sanitize_text_field( wp_unslash( $_POST[ 'label_' . $i ] ) ) : '',
			);
		}
		update_option( self::OPTION_KEY, $clean, false );
		wp_send_json_success( array( 'message' => __( 'Custom Tabs saved.', 'ai-eshop-optimizer' ) ) );
	}

	public function ajax_migrate() {
		AIEO_DMM::verify_ajax_request();
		@ob_end_clean(); 
		$stats = self::run_migration();
		wp_send_json_success( array( 'stats' => $stats, 'migrated_at' => time() ) );
	}

	
	public static function run_migration() {
		global $wpdb;
		$stats = array( 'processed' => 0, 'migrated' => 0, 'skipped' => 0 );
		if ( ! self::table_ok() ) {
			return $stats;
		}

		$map  = array( 'usage' => 1, 'specification' => 2 );
		
		$rows = (array) $wpdb->get_results(
			"SELECT post_id, meta_key, meta_value FROM {$wpdb->postmeta}
			 WHERE meta_key IN ('usage','specification') AND TRIM(meta_value) <> ''",
			ARRAY_A
		);
		foreach ( $rows as $r ) {
			$stats['processed']++;
			$slot = isset( $map[ $r['meta_key'] ] ) ? (int) $map[ $r['meta_key'] ] : 0;
			if ( ! $slot ) {
				$stats['skipped']++;
				continue;
			}
			self::save_content( (int) $r['post_id'], $slot, wp_kses_post( (string) $r['meta_value'] ) );
			$stats['migrated']++;
		}

		
		
		
		$cfg     = self::get_slots_config();
		$changed = false;
		$seed    = array( 1 => 'Εφαρμογή', 2 => 'Συστατικά' );
		foreach ( $seed as $i => $greek ) {
			if ( empty( $cfg[ $i ]['enabled'] ) ) {
				$cfg[ $i ]['enabled'] = true;
				if ( '' === trim( (string) $cfg[ $i ]['label'] )
					|| in_array( $cfg[ $i ]['label'], array( 'Application', 'Ingredients' ), true ) ) {
					$cfg[ $i ]['label'] = $greek;
				}
				$changed = true;
			}
		}
		if ( $changed ) {
			update_option( self::OPTION_KEY, $cfg, false );
		}

		update_option( self::MIGRATED_OPTION, time(), false );
		return $stats;
	}
}
