<?php
/**
 * Admin settings page — OurNetHelps Mortgage Q&A Assistant
 *
 * @package OurNetHelps_Mortgage_QA_Assistant
 */

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

add_action( 'admin_menu', 'onhmqa_admin_menu' );
function onhmqa_admin_menu() {
	add_options_page(
		__( 'OurNetHelps Mortgage Q&A Assistant', 'ournethelps-mortgage-qa-assistant' ),
		__( 'Mortgage Q&A', 'ournethelps-mortgage-qa-assistant' ),
		'manage_options',
		'ournethelps-mortgage-qa-assistant',
		'onhmqa_settings_page'
	);
}

add_action( 'admin_enqueue_scripts', 'onhmqa_admin_scripts' );
function onhmqa_admin_scripts( $hook ) {
	if ( 'settings_page_ournethelps-mortgage-qa-assistant' !== $hook ) return;
	wp_enqueue_media();
	wp_enqueue_style(
		'onhmqa-admin',
		ONHMQA_PLUGIN_URL . 'assets/admin.css',
		array(),
		ONHMQA_VERSION
	);
	wp_enqueue_script(
		'onhmqa-admin',
		ONHMQA_PLUGIN_URL . 'assets/admin.js',
		array( 'jquery' ),
		ONHMQA_VERSION,
		true
	);
	// Pass i18n strings to admin JS
	wp_localize_script( 'onhmqa-admin', 'onhmqaAdmin', array(
		'labelQ'      => __( 'Question / Chip Label', 'ournethelps-mortgage-qa-assistant' ),
		'labelK'      => __( 'Keywords (comma-separated, optional)', 'ournethelps-mortgage-qa-assistant' ),
		'labelA'      => __( 'Answer', 'ournethelps-mortgage-qa-assistant' ),
		'labelRemove' => __( 'Remove', 'ournethelps-mortgage-qa-assistant' ),
	) );
}

// ── Save handler ──────────────────────────────────────────────────────────────

function onhmqa_maybe_save() {
	if ( ! isset( $_POST['onhmqa_nonce'] ) ) return;
	if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['onhmqa_nonce'] ) ), 'onhmqa_save' ) ) return;
	if ( ! current_user_can( 'manage_options' ) ) return;

	$tab = isset( $_POST['onhmqa_tab'] ) ? sanitize_text_field( wp_unslash( $_POST['onhmqa_tab'] ) ) : 'general';

	if ( $tab === 'general' ) {
		update_option( 'onhmqa_show_branding', isset( $_POST['onhmqa_show_branding'] ) ? '1' : '0' );
		update_option( 'onhmqa_enabled',       isset( $_POST['onhmqa_enabled'] ) ? '1' : '0' );
		update_option( 'onhmqa_position',      sanitize_text_field( wp_unslash( $_POST['onhmqa_position']      ?? 'bottom-right' ) ) );
		update_option( 'onhmqa_accent',        sanitize_hex_color( wp_unslash( $_POST['onhmqa_accent']         ?? '#1a56db' ) ) ?? '#1a56db' );
		update_option( 'onhmqa_welcome',       sanitize_textarea_field( wp_unslash( $_POST['onhmqa_welcome']   ?? '' ) ) );
		update_option( 'onhmqa_urgency',       sanitize_text_field( wp_unslash( $_POST['onhmqa_urgency']       ?? '' ) ) );
		update_option( 'onhmqa_exclude_pages', sanitize_textarea_field( wp_unslash( $_POST['onhmqa_exclude_pages'] ?? '' ) ) );
		update_option( 'onhmqa_fallback_msg',  sanitize_textarea_field( wp_unslash( $_POST['onhmqa_fallback_msg']  ?? '' ) ) );
		update_option( 'onhmqa_contact_url',   esc_url_raw( wp_unslash( $_POST['onhmqa_contact_url']           ?? '' ) ) );
		update_option( 'onhmqa_popup_enabled', isset( $_POST['onhmqa_popup_enabled'] ) ? '1' : '0' );
		update_option( 'onhmqa_popup_text',    sanitize_text_field( wp_unslash( $_POST['onhmqa_popup_text']    ?? 'Have mortgage questions?' ) ) );
		update_option( 'onhmqa_popup_delay',   absint( $_POST['onhmqa_popup_delay'] ?? 6 ) );
	}

	if ( $tab === 'profile' ) {
		update_option( 'onhmqa_agent_name',      sanitize_text_field( wp_unslash( $_POST['onhmqa_agent_name']      ?? '' ) ) );
		update_option( 'onhmqa_agent_title',     sanitize_text_field( wp_unslash( $_POST['onhmqa_agent_title']     ?? '' ) ) );
		update_option( 'onhmqa_agent_license',   sanitize_text_field( wp_unslash( $_POST['onhmqa_agent_license']   ?? '' ) ) );
		update_option( 'onhmqa_agent_phone',     sanitize_text_field( wp_unslash( $_POST['onhmqa_agent_phone']     ?? '' ) ) );
		update_option( 'onhmqa_agent_email',     sanitize_email(      wp_unslash( $_POST['onhmqa_agent_email']     ?? '' ) ) );
		update_option( 'onhmqa_agent_photo_url', esc_url_raw(         wp_unslash( $_POST['onhmqa_agent_photo_url'] ?? '' ) ) );
	}

	if ( $tab === 'qa' ) {
		$qa_json_raw = isset( $_POST['onhmqa_qa_json'] ) ? sanitize_text_field( wp_unslash( $_POST['onhmqa_qa_json'] ) ) : '[]';
		$qa_decoded  = json_decode( $qa_json_raw, true );
		if ( ! is_array( $qa_decoded ) || empty( $qa_decoded ) ) {
			$qa_decoded = isset( $_POST['onhmqa_qa_pairs'] ) ? wp_unslash( $_POST['onhmqa_qa_pairs'] ) : array();
		}
		update_option( 'onhmqa_qa_pairs', onhmqa_sanitize_qa_pairs( $qa_decoded ) );
	}

	add_settings_error( 'onhmqa_messages', 'onhmqa_saved', __( 'Settings saved.', 'ournethelps-mortgage-qa-assistant' ), 'updated' );
}

// ── Settings page ─────────────────────────────────────────────────────────────

function onhmqa_settings_page() {
	if ( ! current_user_can( 'manage_options' ) ) return;

	onhmqa_maybe_save();

	$active_tab = isset( $_GET['tab'] ) ? sanitize_text_field( wp_unslash( $_GET['tab'] ) ) : 'general';

	$enabled        = get_option( 'onhmqa_enabled',       '1' );
	$position       = get_option( 'onhmqa_position',      'bottom-right' );
	$accent         = get_option( 'onhmqa_accent',        '#1a56db' );
	$welcome        = get_option( 'onhmqa_welcome',       'Hi! Ask me anything about mortgages. Tap a question below or type your own.' );
	$urgency        = get_option( 'onhmqa_urgency',       '' );
	$exclude        = get_option( 'onhmqa_exclude_pages', '' );
	$fallback       = get_option( 'onhmqa_fallback_msg',  'Great question. Please call me directly or use the contact form and I will get back to you as soon as possible.' );
	$contact_url    = get_option( 'onhmqa_contact_url',   '' );
	$popup_enabled  = get_option( 'onhmqa_popup_enabled', '1' );
	$popup_text     = get_option( 'onhmqa_popup_text',    'Have mortgage questions?' );
	$popup_delay    = get_option( 'onhmqa_popup_delay',   6 );
	$agent_name     = get_option( 'onhmqa_agent_name',    '' );
	$agent_title    = get_option( 'onhmqa_agent_title',   'Mortgage Broker' );
	$agent_license  = get_option( 'onhmqa_agent_license', '' );
	$agent_phone    = get_option( 'onhmqa_agent_phone',   '' );
	$agent_email    = get_option( 'onhmqa_agent_email',   '' );
	$photo_url      = get_option( 'onhmqa_agent_photo_url', '' );
	$qa_json        = get_option( 'onhmqa_qa_pairs',      '' );
	$qa_pairs       = ! empty( $qa_json ) ? json_decode( $qa_json, true ) : array();
	if ( ! is_array( $qa_pairs ) ) $qa_pairs = array();

	settings_errors( 'onhmqa_messages' );
	?>
	<div class="wrap onhmqa-wrap">
		<h1><?php esc_html_e( 'OurNetHelps Mortgage Q&A Assistant', 'ournethelps-mortgage-qa-assistant' ); ?></h1>

		<nav class="nav-tab-wrapper onhmqa-tabs">
			<?php
			$tabs = array(
				'general' => __( 'General', 'ournethelps-mortgage-qa-assistant' ),
				'profile' => __( 'Broker Profile', 'ournethelps-mortgage-qa-assistant' ),
				'qa'      => __( 'Q&amp;A Editor', 'ournethelps-mortgage-qa-assistant' ),
				'info'    => __( 'Plugin Info', 'ournethelps-mortgage-qa-assistant' ),
			);
			foreach ( $tabs as $slug => $label ) {
				$class = ( $active_tab === $slug ) ? 'nav-tab nav-tab-active' : 'nav-tab';
				$url   = admin_url( 'options-general.php?page=ournethelps-mortgage-qa-assistant&tab=' . $slug );
				echo '<a href="' . esc_url( $url ) . '" class="' . esc_attr( $class ) . '">' . wp_kses_post( $label ) . '</a>';
			}
			?>
		</nav>

		<form method="post" action="">
			<?php wp_nonce_field( 'onhmqa_save', 'onhmqa_nonce' ); ?>
			<input type="hidden" name="onhmqa_tab" value="<?php echo esc_attr( $active_tab ); ?>" />

			<?php if ( 'general' === $active_tab ) : ?>
			<!-- ── GENERAL TAB ────────────────────────────────────────────── -->
			<table class="form-table onhmqa-table">
				<tr>
					<th><?php esc_html_e( 'Enable Widget', 'ournethelps-mortgage-qa-assistant' ); ?></th>
					<td><label><input type="checkbox" name="onhmqa_enabled" value="1" <?php checked( $enabled, '1' ); ?> /> <?php esc_html_e( 'Show chat widget on all pages', 'ournethelps-mortgage-qa-assistant' ); ?></label></td>
				</tr>
				<tr>
					<th><?php esc_html_e( 'Widget Position', 'ournethelps-mortgage-qa-assistant' ); ?></th>
					<td>
						<select name="onhmqa_position">
							<option value="bottom-right" <?php selected( $position, 'bottom-right' ); ?>><?php esc_html_e( 'Bottom Right', 'ournethelps-mortgage-qa-assistant' ); ?></option>
							<option value="bottom-left"  <?php selected( $position, 'bottom-left' );  ?>><?php esc_html_e( 'Bottom Left',  'ournethelps-mortgage-qa-assistant' ); ?></option>
						</select>
					</td>
				</tr>
				<tr>
					<th><?php esc_html_e( 'Accent Color', 'ournethelps-mortgage-qa-assistant' ); ?></th>
					<td>
						<input type="color" name="onhmqa_accent" value="<?php echo esc_attr( $accent ); ?>" />
						<p class="description"><?php esc_html_e( 'Chat button and header background color.', 'ournethelps-mortgage-qa-assistant' ); ?></p>
					</td>
				</tr>
				<tr><td colspan="2"><hr style="margin:6px 0"><h3 style="margin:4px 0"><?php esc_html_e( 'Popup Chat Bubble', 'ournethelps-mortgage-qa-assistant' ); ?></h3></td></tr>
				<tr>
					<th><?php esc_html_e( 'Enable Popup Bubble', 'ournethelps-mortgage-qa-assistant' ); ?></th>
					<td><label><input type="checkbox" name="onhmqa_popup_enabled" value="1" <?php checked( $popup_enabled, '1' ); ?> /> <?php esc_html_e( 'Show a speech bubble above the chat button after a delay', 'ournethelps-mortgage-qa-assistant' ); ?></label></td>
				</tr>
				<tr>
					<th><?php esc_html_e( 'Bubble Message', 'ournethelps-mortgage-qa-assistant' ); ?></th>
					<td>
						<input type="text" name="onhmqa_popup_text" value="<?php echo esc_attr( $popup_text ); ?>" class="regular-text" maxlength="60" />
						<p class="description"><?php esc_html_e( 'Keep under 40 characters.', 'ournethelps-mortgage-qa-assistant' ); ?></p>
					</td>
				</tr>
				<tr>
					<th><?php esc_html_e( 'Bubble Appears After', 'ournethelps-mortgage-qa-assistant' ); ?></th>
					<td><input type="number" name="onhmqa_popup_delay" value="<?php echo esc_attr( $popup_delay ); ?>" min="1" max="30" style="width:60px" /> <?php esc_html_e( 'seconds', 'ournethelps-mortgage-qa-assistant' ); ?></td>
				</tr>
				<tr><td colspan="2"><hr style="margin:6px 0"><h3 style="margin:4px 0"><?php esc_html_e( 'Messaging', 'ournethelps-mortgage-qa-assistant' ); ?></h3></td></tr>
				<tr>
					<th><?php esc_html_e( 'Welcome Message', 'ournethelps-mortgage-qa-assistant' ); ?></th>
					<td><textarea name="onhmqa_welcome" rows="3" class="large-text"><?php echo esc_textarea( $welcome ); ?></textarea></td>
				</tr>
				<tr>
					<th><?php esc_html_e( 'Fallback Message', 'ournethelps-mortgage-qa-assistant' ); ?></th>
					<td>
						<textarea name="onhmqa_fallback_msg" rows="2" class="large-text"><?php echo esc_textarea( $fallback ); ?></textarea>
						<p class="description"><?php esc_html_e( 'Shown when no Q&A matches. Your email and contact link are appended automatically.', 'ournethelps-mortgage-qa-assistant' ); ?></p>
					</td>
				</tr>
				<tr>
					<th><?php esc_html_e( 'Urgency Text', 'ournethelps-mortgage-qa-assistant' ); ?></th>
					<td>
						<input type="text" name="onhmqa_urgency" value="<?php echo esc_attr( $urgency ); ?>" class="regular-text" placeholder="e.g. Have mortgage questions?" />
						<p class="description"><?php esc_html_e( 'Persistent pill above the button. Leave blank to hide.', 'ournethelps-mortgage-qa-assistant' ); ?></p>
					</td>
				</tr>
				<tr>
					<th><?php esc_html_e( 'Contact Page URL', 'ournethelps-mortgage-qa-assistant' ); ?></th>
					<td><input type="url" name="onhmqa_contact_url" value="<?php echo esc_attr( $contact_url ); ?>" class="regular-text" placeholder="https://yoursite.com/contact/" /></td>
				</tr>
				<tr>
					<th><?php esc_html_e( 'Exclude From Pages', 'ournethelps-mortgage-qa-assistant' ); ?></th>
					<td>
						<textarea name="onhmqa_exclude_pages" rows="3" class="large-text" placeholder="/apply/&#10;/privacy-policy/"><?php echo esc_textarea( $exclude ); ?></textarea>
						<p class="description"><?php esc_html_e( 'One URL path per line. Exact match only.', 'ournethelps-mortgage-qa-assistant' ); ?></p>
					</td>
				</tr>
				<tr>
					<th><?php esc_html_e( 'OurNetHelps Branding', 'ournethelps-mortgage-qa-assistant' ); ?></th>
					<td>
						<label><input type="checkbox" name="onhmqa_show_branding" value="1" <?php checked( get_option( 'onhmqa_show_branding', '0' ), '1' ); ?> /> <?php esc_html_e( 'Show "Powered by OurNetHelps" credit in widget footer', 'ournethelps-mortgage-qa-assistant' ); ?></label>
						<p class="description"><?php esc_html_e( 'Optional. Off by default. Enable this if you enjoy the plugin and want to credit OurNetHelps.', 'ournethelps-mortgage-qa-assistant' ); ?></p>
					</td>
				</tr>
			</table>

			<?php elseif ( 'profile' === $active_tab ) : ?>
			<!-- ── BROKER PROFILE TAB ──────────────────────────────────────── -->
			<table class="form-table onhmqa-table">
				<tr>
					<th><?php esc_html_e( 'Your Name', 'ournethelps-mortgage-qa-assistant' ); ?></th>
					<td>
						<input type="text" name="onhmqa_agent_name" value="<?php echo esc_attr( $agent_name ); ?>" class="regular-text" placeholder="Jane Smith" />
						<p class="description"><?php esc_html_e( 'Displayed in the chat header.', 'ournethelps-mortgage-qa-assistant' ); ?></p>
					</td>
				</tr>
				<tr>
					<th><?php esc_html_e( 'Title / Role', 'ournethelps-mortgage-qa-assistant' ); ?></th>
					<td><input type="text" name="onhmqa_agent_title" value="<?php echo esc_attr( $agent_title ); ?>" class="regular-text" placeholder="Mortgage Broker" /></td>
				</tr>
				<tr>
					<th><?php esc_html_e( 'NMLS License Number', 'ournethelps-mortgage-qa-assistant' ); ?></th>
					<td>
						<input type="text" name="onhmqa_agent_license" value="<?php echo esc_attr( $agent_license ); ?>" class="regular-text" placeholder="123456" />
						<p class="description"><?php esc_html_e( 'Enter just the number (e.g. 123456) — "NMLS #" is added automatically in the chat header.', 'ournethelps-mortgage-qa-assistant' ); ?></p>
					</td>
				</tr>
				<tr>
					<th><?php esc_html_e( 'Phone Number', 'ournethelps-mortgage-qa-assistant' ); ?></th>
					<td>
						<input type="text" name="onhmqa_agent_phone" value="<?php echo esc_attr( $agent_phone ); ?>" class="regular-text" placeholder="(555) 123-4567" />
						<p class="description"><?php esc_html_e( 'Shown as a clickable tel: link in the chat header.', 'ournethelps-mortgage-qa-assistant' ); ?></p>
					</td>
				</tr>
				<tr>
					<th><?php esc_html_e( 'Email Address', 'ournethelps-mortgage-qa-assistant' ); ?></th>
					<td>
						<input type="email" name="onhmqa_agent_email" value="<?php echo esc_attr( $agent_email ); ?>" class="regular-text" placeholder="you@yourdomain.com" />
						<p class="description"><?php esc_html_e( 'Shown as a mailto link in fallback answers.', 'ournethelps-mortgage-qa-assistant' ); ?></p>
					</td>
				</tr>
				<tr>
					<th><?php esc_html_e( 'Your Photo', 'ournethelps-mortgage-qa-assistant' ); ?></th>
					<td>
						<?php if ( $photo_url ) : ?>
							<img src="<?php echo esc_url( $photo_url ); ?>" class="onhmqa-photo-preview" alt="" />
						<?php endif; ?>
						<input type="hidden" name="onhmqa_agent_photo_url" id="onhmqa-photo-url" value="<?php echo esc_attr( $photo_url ); ?>" />
						<br>
						<button type="button" class="button" id="onhmqa-upload-photo"><?php esc_html_e( 'Upload / Choose Photo', 'ournethelps-mortgage-qa-assistant' ); ?></button>
						<button type="button" class="button" id="onhmqa-remove-photo" style="<?php echo $photo_url ? '' : 'display:none'; ?>"><?php esc_html_e( 'Remove Photo', 'ournethelps-mortgage-qa-assistant' ); ?></button>
						<p class="description"><?php esc_html_e( 'Circular avatar in the chat header. Recommended: 80x80px.', 'ournethelps-mortgage-qa-assistant' ); ?></p>
					</td>
				</tr>
			</table>

			<?php elseif ( 'qa' === $active_tab ) : ?>
			<!-- ── Q&A EDITOR TAB ──────────────────────────────────────────── -->
			<p><?php esc_html_e( 'Add your Q&A pairs. Visitors tap chips or type questions and get instant answers. No limit on pairs.', 'ournethelps-mortgage-qa-assistant' ); ?></p>
			<p class="description" style="color:#059669;font-weight:600"><?php esc_html_e( '✓ Default mortgage Q&A is built-in and always active. Your custom pairs below are searched first and shown as chips.', 'ournethelps-mortgage-qa-assistant' ); ?></p>
			<input type="hidden" name="onhmqa_qa_json" id="onhmqa-qa-json" value="<?php echo esc_attr( wp_json_encode( $qa_pairs ) ); ?>" />
			<div id="onhmqa-qa-list">
			<?php foreach ( $qa_pairs as $i => $pair ) : ?>
				<div class="onhmqa-qa-row" data-idx="<?php echo esc_attr( $i ); ?>">
					<div class="onhmqa-qa-fields">
						<div>
							<label><?php esc_html_e( 'Question / Chip Label', 'ournethelps-mortgage-qa-assistant' ); ?></label>
							<input type="text" class="large-text onhmqa-q" placeholder="e.g. What are today's rates?" value="<?php echo esc_attr( $pair['question'] ?? '' ); ?>" />
						</div>
						<div>
							<label><?php esc_html_e( 'Keywords (comma-separated, optional)', 'ournethelps-mortgage-qa-assistant' ); ?></label>
							<input type="text" class="large-text onhmqa-k" placeholder="rates, interest rate, today rate" value="<?php echo esc_attr( $pair['keywords'] ?? '' ); ?>" />
						</div>
						<div>
							<label><?php esc_html_e( 'Answer', 'ournethelps-mortgage-qa-assistant' ); ?></label>
							<textarea class="large-text onhmqa-a" rows="2"><?php echo esc_textarea( $pair['answer'] ?? '' ); ?></textarea>
						</div>
					</div>
					<button type="button" class="button onhmqa-remove-qa"><?php esc_html_e( 'Remove', 'ournethelps-mortgage-qa-assistant' ); ?></button>
				</div>
			<?php endforeach; ?>
			</div>
			<button type="button" class="button button-secondary" id="onhmqa-add-qa" style="margin-top:8px"><?php esc_html_e( '+ Add Q&amp;A Pair', 'ournethelps-mortgage-qa-assistant' ); ?></button>

			<?php elseif ( 'info' === $active_tab ) : ?>
			<!-- ── PLUGIN INFO TAB ─────────────────────────────────────────── -->
			<table class="form-table onhmqa-table">
				<tr><th><?php esc_html_e( 'Version', 'ournethelps-mortgage-qa-assistant' ); ?></th><td><?php echo esc_html( ONHMQA_VERSION ); ?></td></tr>
				<tr><th><?php esc_html_e( 'Widget Enabled', 'ournethelps-mortgage-qa-assistant' ); ?></th><td><?php echo get_option('onhmqa_enabled','1')==='1' ? '<span style="color:#059669;font-weight:600">' . esc_html__('Yes','ournethelps-mortgage-qa-assistant') . '</span>' : '<span style="color:#dc2626;font-weight:600">' . esc_html__('No','ournethelps-mortgage-qa-assistant') . '</span>'; ?></td></tr>
				<tr><th><?php esc_html_e( 'Plugin Page', 'ournethelps-mortgage-qa-assistant' ); ?></th><td><a href="https://ournethelps.com/mortgage-qa-assistant/" target="_blank" rel="noopener">ournethelps.com/mortgage-qa-assistant/</a></td></tr>
				<tr><th><?php esc_html_e( 'Support', 'ournethelps-mortgage-qa-assistant' ); ?></th><td><a href="mailto:sanjeev@ournethelps.com">sanjeev@ournethelps.com</a></td></tr>
			</table>
			<?php endif; ?>

			<?php if ( 'info' !== $active_tab ) : ?>
			<p class="submit">
				<input type="submit" class="button button-primary" value="<?php esc_attr_e( 'Save Settings', 'ournethelps-mortgage-qa-assistant' ); ?>" />
			</p>
			<?php endif; ?>
		</form>
	</div>
	<?php
}
