<?php

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

class AIEO_DMM_My_Settings extends AIEO_DMM_Module_Base {

	public function get_id()       { return 'my_settings'; }
	public function get_label()    { return __( 'My Settings', 'ai-eshop-optimizer' ); }
	public function get_priority() { return 5; } 
	public function get_group()    { return 'tools'; }

	public function register_hooks() {
		add_action( 'wp_ajax_aieo_dmm_save_my_settings', array( $this, 'ajax_save' ) );
	}

	
	public function ajax_save() {
		AIEO_DMM::verify_ajax_request();

		$uid = get_current_user_id();
		if ( ! $uid ) {
			wp_send_json_error( array( 'message' => __( 'Not logged in.', 'ai-eshop-optimizer' ) ) );
		}

		$landing = isset( $_POST['landing_tab'] ) ? sanitize_key( wp_unslash( $_POST['landing_tab'] ) ) : ''; 

		if ( $landing === '' ) {
			delete_user_meta( $uid, AIEO_DMM::LANDING_USER_META );
			wp_send_json_success( array( 'message' => __( 'Reset — you’ll land on the default card.', 'ai-eshop-optimizer' ) ) );
		}

		if ( $landing === '__resume__' ) {
			update_user_meta( $uid, AIEO_DMM::LANDING_USER_META, '__resume__' );
			wp_send_json_success( array( 'message' => __( 'Saved — you’ll resume where you left off.', 'ai-eshop-optimizer' ) ) );
		}

		$modules = AIEO_DMM::instance()->get_modules();
		if ( ! isset( $modules[ $landing ] ) ) {
			wp_send_json_error( array( 'message' => __( 'That page no longer exists.', 'ai-eshop-optimizer' ) ) );
		}

		update_user_meta( $uid, AIEO_DMM::LANDING_USER_META, $landing );
		wp_send_json_success( array(
			'message' => sprintf(
				
				__( 'Saved — you’ll now land on “%s”.', 'ai-eshop-optimizer' ),
				$modules[ $landing ]->get_label()
			),
		) );
	}

	public function render_subtab() {
		$dmm     = AIEO_DMM::instance();
		$current = (string) get_user_meta( get_current_user_id(), AIEO_DMM::LANDING_USER_META, true );
		$nonce   = wp_create_nonce( AIEO_DMM::NONCE_ACTION );
		$ajax    = admin_url( 'admin-ajax.php' );

		
		$group_labels = array();
		foreach ( $dmm->get_group_definitions() as $g ) {
			$group_labels[ $g['id'] ] = $g['label'];
		}

		
		$by_group = array();
		foreach ( $dmm->get_subtabs() as $tab ) {
			$gid = ! empty( $tab['group'] ) ? $tab['group'] : '';
			$by_group[ $gid ][] = array( 'id' => $tab['id'], 'label' => $tab['label'] );
		}

		
		$order   = array_keys( $group_labels );
		$order[] = '';
		?>
		<div class="aieo-dmm-section">
			<div class="aieo-dmm-card" id="aieo-card-my-settings">
				<h3 style="margin-top:0;"><?php esc_html_e( 'My settings', 'ai-eshop-optimizer' ); ?></h3>
				<p class="description" style="max-width:760px;">
					<?php esc_html_e( 'Personal preferences for your account. These apply only to you — other users of the e-Shop Manager keep their own.', 'ai-eshop-optimizer' ); ?>
				</p>

				<h4 style="margin:20px 0 4px;"><?php esc_html_e( 'Landing card', 'ai-eshop-optimizer' ); ?></h4>
				<p class="description" style="max-width:760px;margin-bottom:10px;">
					<?php esc_html_e( 'The card you see first when you open the e-Shop Manager (when the link has no specific tab). Pick any card below — grouped by its top-level tab.', 'ai-eshop-optimizer' ); ?>
				</p>

				<select id="aieo-my-landing" style="min-width:360px;max-width:100%;padding:4px 6px;">
					<option value=""<?php selected( $current, '' ); ?>><?php esc_html_e( '— Default (first card) —', 'ai-eshop-optimizer' ); ?></option>
					<option value="__resume__"<?php selected( $current, '__resume__' ); ?>><?php esc_html_e( '↻ Resume where I left off (last card I viewed)', 'ai-eshop-optimizer' ); ?></option>
					<?php
					foreach ( $order as $gid ) {
						if ( empty( $by_group[ $gid ] ) ) { continue; }
						$glabel = ( $gid === '' )
							? __( 'Other', 'ai-eshop-optimizer' )
							: ( isset( $group_labels[ $gid ] ) ? $group_labels[ $gid ] : $gid );
						echo '<optgroup label="' . esc_attr( wp_specialchars_decode( (string) $glabel ) ) . '">';
						foreach ( $by_group[ $gid ] as $opt ) {
							echo '<option value="' . esc_attr( $opt['id'] ) . '"' . selected( $current, $opt['id'], false ) . '>'
								. esc_html( wp_specialchars_decode( (string) $opt['label'] ) ) . '</option>';
						}
						echo '</optgroup>';
					}
					?>
				</select>

				<p class="submit" style="margin-top:16px;">
					<button type="button" class="button button-primary" id="aieo-my-settings-save"><?php esc_html_e( 'Save', 'ai-eshop-optimizer' ); ?></button>
					<span id="aieo-my-settings-status" style="margin-left:10px;font-size:13px;color:#646970;"></span>
				</p>
				<p class="description" style="margin-top:6px;"><?php esc_html_e( 'Tip: pick “Default” to go back to the standard first card.', 'ai-eshop-optimizer' ); ?></p>
			</div>
		</div>
		<script>
		(function () {
			var btn = document.getElementById('aieo-my-settings-save');
			if (!btn) { return; }
			btn.addEventListener('click', function () {
				var sel = document.getElementById('aieo-my-landing');
				var status = document.getElementById('aieo-my-settings-status');
				var fd = new FormData();
				fd.set('action', 'aieo_dmm_save_my_settings');
				fd.set('nonce', <?php echo wp_json_encode( $nonce ); ?>);
				fd.set('landing_tab', sel ? sel.value : '');
				status.textContent = <?php echo wp_json_encode( __( 'Saving…', 'ai-eshop-optimizer' ) ); ?>;
				status.style.color = '#646970';
				fetch(<?php echo wp_json_encode( $ajax ); ?>, { method: 'POST', credentials: 'same-origin', body: fd })
					.then(function (r) { return r.json(); })
					.then(function (j) {
						status.textContent = (j && j.data && j.data.message) ? j.data.message : 'Saved.';
						status.style.color = (j && j.success) ? '#15803d' : '#b91c1c';
					})
					.catch(function () { status.textContent = 'Save failed.'; status.style.color = '#b91c1c'; });
			});
		})();
		</script>
		<?php
	}
}
