<?php
/**
 * Floating feedback / suggestion widget for TSM admin pages.
 *
 * Renders a small button bottom-right on every TSM admin page; clicking
 * opens a panel with subject (auto-set), reply-to email, and message.
 * Submits via admin-ajax to wp_mail() the developer.
 *
 * @package TradeSchoolManager
 */

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

class TSM_Feedback {

	const RECIPIENT = 'cburleigh@cjswebservice.com';
	const AJAX      = 'tsm_send_feedback';

	public static function init() {
		add_action( 'admin_enqueue_scripts',           array( __CLASS__, 'enqueue_assets' ) );
		add_action( 'admin_footer',                    array( __CLASS__, 'render' ) );
		add_action( 'wp_ajax_' . self::AJAX,           array( __CLASS__, 'handle_ajax' ) );
	}

	private static function on_tsm_page() {
		if ( ! is_admin() ) { return false; }
		$page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( '' === $page ) { return false; }
		return ( 0 === strpos( $page, 'tsm-' ) || 0 === strpos( $page, 'tsmp-' ) );
	}

	public static function enqueue_assets() {
		if ( ! self::on_tsm_page() ) { return; }
		if ( ! current_user_can( 'manage_tradeschool' ) && ! current_user_can( 'manage_options' ) ) { return; }

		$css = <<<'CSS'
#tsm-fb-root { position:fixed; right:20px; bottom:20px; z-index:99998; font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif; }
#tsm-fb-btn { display:inline-flex; align-items:center; gap:6px; padding:10px 16px; background:#1f6feb; color:#fff; border:0; border-radius:999px; box-shadow:0 6px 16px rgba(15,23,42,.25); cursor:pointer; font-weight:600; font-size:13px; }
#tsm-fb-btn:hover { background:#1858c4; }
#tsm-fb-btn .dashicons { font-size:18px; width:18px; height:18px; }
#tsm-fb-panel { position:absolute; right:0; bottom:54px; width:340px; background:#fff; border:1px solid #e2e8f0; border-radius:12px; box-shadow:0 16px 36px rgba(15,23,42,.18); overflow:hidden; }
.tsm-fb-head { display:flex; justify-content:space-between; align-items:center; padding:12px 14px; background:#f8fafc; border-bottom:1px solid #e2e8f0; }
.tsm-fb-head strong { font-size:14px; color:#0f172a; }
.tsm-fb-x { background:none; border:0; font-size:22px; line-height:1; cursor:pointer; color:#64748b; }
#tsm-fb-form { padding:14px; display:flex; flex-direction:column; gap:10px; }
#tsm-fb-form label { display:flex; flex-direction:column; gap:4px; font-size:12px; font-weight:600; color:#334155; }
#tsm-fb-form input, #tsm-fb-form select, #tsm-fb-form textarea { width:100%; padding:8px 10px; border:1px solid #cbd5e1; border-radius:6px; font-size:13px; font-weight:400; }
#tsm-fb-form textarea { resize:vertical; min-height:90px; }
.tsm-fb-foot { display:flex; justify-content:space-between; align-items:center; gap:8px; }
.tsm-fb-status { font-size:12px; color:#475569; }
.tsm-fb-status.ok { color:#15803d; }
.tsm-fb-status.err { color:#dc2626; }
CSS;
		wp_register_style( 'tsm-feedback', false, array(), defined( 'TSM_VERSION' ) ? TSM_VERSION : '1' );
		wp_enqueue_style( 'tsm-feedback' );
		wp_add_inline_style( 'tsm-feedback', $css );

		$js = <<<'JS'
(function(){
	var root = document.getElementById('tsm-fb-root');
	if (!root) return;
	var btn   = document.getElementById('tsm-fb-btn');
	var panel = document.getElementById('tsm-fb-panel');
	var form  = document.getElementById('tsm-fb-form');
	var stat  = form.querySelector('.tsm-fb-status');
	var closeBtn = panel.querySelector('.tsm-fb-x');
	btn.addEventListener('click', function(){ panel.hidden = !panel.hidden; if(!panel.hidden) form.querySelector('textarea').focus(); });
	closeBtn.addEventListener('click', function(){ panel.hidden = true; });
	form.addEventListener('submit', function(e){
		e.preventDefault();
		stat.className = 'tsm-fb-status'; stat.textContent = 'Sending...';
		var fd = new FormData(form);
		fd.append('action', root.dataset.action);
		fd.append('_nonce', root.dataset.nonce);
		fetch(root.dataset.ajax, { method:'POST', credentials:'same-origin', body:fd })
			.then(function(r){ return r.json(); })
			.then(function(j){
				if (j && j.success) {
					stat.className = 'tsm-fb-status ok';
					stat.textContent = 'Thanks - sent!';
					form.querySelector('textarea').value = '';
					setTimeout(function(){ panel.hidden = true; stat.textContent = ''; }, 1800);
				} else {
					stat.className = 'tsm-fb-status err';
					stat.textContent = (j && j.data) ? j.data : 'Failed to send.';
				}
			})
			.catch(function(){ stat.className='tsm-fb-status err'; stat.textContent='Network error.'; });
	});
})();
JS;
		wp_register_script( 'tsm-feedback', false, array(), defined( 'TSM_VERSION' ) ? TSM_VERSION : '1', true );
		wp_enqueue_script( 'tsm-feedback' );
		wp_add_inline_script( 'tsm-feedback', $js );
	}

	public static function render() {
		if ( ! self::on_tsm_page() ) { return; }
		if ( ! current_user_can( 'manage_tradeschool' ) && ! current_user_can( 'manage_options' ) ) { return; }
		$user  = wp_get_current_user();
		$email = $user ? $user->user_email : '';
		$nonce = wp_create_nonce( self::AJAX );
		?>
		<div id="tsm-fb-root" data-nonce="<?php echo esc_attr( $nonce ); ?>" data-action="<?php echo esc_attr( self::AJAX ); ?>" data-ajax="<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>">
			<button type="button" id="tsm-fb-btn" aria-label="<?php esc_attr_e( 'Send feedback', 'tradeschool-manager' ); ?>">
				<span class="dashicons dashicons-format-chat"></span>
				<span><?php esc_html_e( 'Feedback', 'tradeschool-manager' ); ?></span>
			</button>
			<div id="tsm-fb-panel" hidden>
				<div class="tsm-fb-head">
					<strong><?php esc_html_e( 'Feedback or Suggestion', 'tradeschool-manager' ); ?></strong>
					<button type="button" class="tsm-fb-x" aria-label="Close">&times;</button>
				</div>
				<form id="tsm-fb-form">
					<label><?php esc_html_e( 'Type', 'tradeschool-manager' ); ?>
						<select name="kind">
							<option value="Feedback"><?php esc_html_e( 'Feedback', 'tradeschool-manager' ); ?></option>
							<option value="Suggestion"><?php esc_html_e( 'Suggestion', 'tradeschool-manager' ); ?></option>
							<option value="Bug Report"><?php esc_html_e( 'Bug report', 'tradeschool-manager' ); ?></option>
						</select>
					</label>
					<label><?php esc_html_e( 'Your email', 'tradeschool-manager' ); ?>
						<input type="email" name="reply_to" required value="<?php echo esc_attr( $email ); ?>">
					</label>
					<label><?php esc_html_e( 'Message', 'tradeschool-manager' ); ?>
						<textarea name="message" rows="5" required maxlength="4000" placeholder="<?php esc_attr_e( "What's on your mind?", 'tradeschool-manager' ); ?>"></textarea>
					</label>
					<div class="tsm-fb-foot">
						<span class="tsm-fb-status" aria-live="polite"></span>
						<button type="submit" class="button button-primary"><?php esc_html_e( 'Send', 'tradeschool-manager' ); ?></button>
					</div>
				</form>
			</div>
		</div>
		<?php
	}

	public static function handle_ajax() {
		check_ajax_referer( self::AJAX, '_nonce' );
		if ( ! current_user_can( 'manage_tradeschool' ) && ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( __( 'Not allowed.', 'tradeschool-manager' ), 403 );
		}
		$kind     = sanitize_text_field( wp_unslash( $_POST['kind'] ?? 'Feedback' ) );
		$reply_to = sanitize_email( wp_unslash( $_POST['reply_to'] ?? '' ) );
		$message  = sanitize_textarea_field( wp_unslash( $_POST['message'] ?? '' ) );

		if ( ! is_email( $reply_to ) ) { wp_send_json_error( __( 'Please enter a valid email.', 'tradeschool-manager' ) ); }
		if ( strlen( trim( $message ) ) < 5 ) { wp_send_json_error( __( 'Please write a message.', 'tradeschool-manager' ) ); }
		if ( strlen( $message ) > 4000 ) { wp_send_json_error( __( 'Message too long.', 'tradeschool-manager' ) ); }

		$user = wp_get_current_user();
		$site = wp_parse_url( home_url(), PHP_URL_HOST );

		$subject = 'TSM ' . $kind;
		$body    = "TSM " . $kind . " from " . ( $user ? $user->display_name : 'unknown' ) . "\n";
		$body   .= "Site: " . home_url() . "\n";
		$body   .= "User email: " . ( $user ? $user->user_email : '' ) . "\n";
		$body   .= "Reply-To: " . $reply_to . "\n";
		$body   .= "TSM version: " . ( defined( 'TSM_VERSION' ) ? TSM_VERSION : '?' ) . "\n";
		$body   .= "WP: " . get_bloginfo( 'version' ) . " | PHP: " . PHP_VERSION . "\n";
		$body   .= str_repeat( '-', 40 ) . "\n\n";
		$body   .= $message . "\n";

		$headers = array(
			'Content-Type: text/plain; charset=UTF-8',
			'Reply-To: ' . $reply_to,
			'From: TSM Feedback <wordpress@' . ( $site ?: 'localhost' ) . '>',
		);

		$ok = wp_mail( self::RECIPIENT, $subject, $body, $headers );
		if ( $ok ) {
			wp_send_json_success( array( 'message' => 'sent' ) );
		}
		wp_send_json_error( __( 'Mail delivery failed on this server.', 'tradeschool-manager' ) );
	}
}

TSM_Feedback::init();
