<?php
/**
 * Rowshost Admin Controller, Menu Endpoints & Settings UI (v3.0)
 *
 * - Adds native "Rowshost Endpoints" drag-and-drop meta-box to Appearance -> Menus
 * - Green dismissible WordPress confirmation banners (`notice-success`) on every action
 * - Partial tail-masking (`••••••••••` on last 10 chars) for saved Dynadot API & Webhook keys
 */

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

class Rowshost_Admin {

	private static $instance = null;

	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	private function __construct() {
		add_action( 'admin_menu', array( $this, 'register_menus' ) );
		add_action( 'admin_init', array( $this, 'handle_form_submissions' ) );
		add_action( 'admin_notices', array( $this, 'render_admin_notices' ) );

		// Native WordPress Appearance -> Menus Meta-Box ("Rowshost Endpoints")
		add_action( 'admin_head-nav-menus.php', array( $this, 'register_nav_menu_metabox' ) );

		// WooCommerce Product Data Tab for Hosting Plans
		add_filter( 'woocommerce_product_data_tabs', array( $this, 'add_wc_product_tab' ) );
		add_action( 'woocommerce_product_data_panels', array( $this, 'render_wc_product_panel' ) );
		add_action( 'woocommerce_process_product_meta', array( $this, 'save_wc_product_meta' ) );
	}

	/* =========================================================================
	 * NATIVE WORDPRESS APPEARANCE -> MENUS ENDPOINTS META-BOX
	 * ========================================================================= */

	public function register_nav_menu_metabox() {
		add_meta_box(
			'rowshost_nav_endpoints',
			__( 'Rowshost Endpoints', 'rowshost' ),
			array( $this, 'render_nav_menu_metabox' ),
			'nav-menus',
			'side',
			'default'
		);
	}

	public function render_nav_menu_metabox() {
		global $_nav_menu_placeholder, $nav_menu_selected_id;
		$_nav_menu_placeholder = 0 > $_nav_menu_placeholder ? $_nav_menu_placeholder - 1 : -1;

		$endpoints = array(
			'dashboard'       => array( 'label' => 'Client Dashboard', 'url' => Rowshost_Plugin::get_portal_url() ),
			'hosting'         => array( 'label' => 'Hosting Plans', 'url' => Rowshost_Plugin::get_portal_url( 'hosting' ) ),
			'domains'         => array( 'label' => 'Domains & DNS', 'url' => Rowshost_Plugin::get_portal_url( 'domains' ) ),
			'register-domain' => array( 'label' => 'New Domain', 'url' => Rowshost_Plugin::get_portal_url( 'register-domain' ) ),
			'transfer-domain' => array( 'label' => 'Transfer Domain', 'url' => Rowshost_Plugin::get_portal_url( 'transfer-domain' ) ),
			'billing'         => array( 'label' => 'Subscriptions & Invoices', 'url' => Rowshost_Plugin::get_portal_url( 'billing' ) ),
			'edit-account'    => array( 'label' => 'Account & Billing', 'url' => Rowshost_Plugin::get_portal_url( 'edit-account' ) ),
			'login'           => array( 'label' => 'Client Login / Dashboard', 'url' => Rowshost_Plugin::get_portal_url() . '#rowshost-login' ),
			'logout'          => array( 'label' => 'Log Out', 'url' => home_url( '/#rowshost-logout' ) ),
		);
		?>
		<div id="posttype-rowshost-endpoints" class="posttypediv">
			<div id="tabs-panel-rowshost-endpoints" class="tabs-panel tabs-panel-active">
				<ul id="rowshost-endpoints-checklist" class="categorychecklist form-no-clear">
					<?php foreach ( $endpoints as $slug => $ep ) :
						$_nav_menu_placeholder--;
						?>
						<li>
							<label class="menu-item-title">
								<input type="checkbox" class="menu-item-checkbox" name="menu-item[<?php echo esc_attr( $_nav_menu_placeholder ); ?>][menu-item-object-id]" value="<?php echo esc_attr( $_nav_menu_placeholder ); ?>">
								<?php echo esc_html( $ep['label'] ); ?>
							</label>
							<input type="hidden" class="menu-item-type" name="menu-item[<?php echo esc_attr( $_nav_menu_placeholder ); ?>][menu-item-type]" value="custom">
							<input type="hidden" class="menu-item-title" name="menu-item[<?php echo esc_attr( $_nav_menu_placeholder ); ?>][menu-item-title]" value="<?php echo esc_attr( $ep['label'] ); ?>">
							<input type="hidden" class="menu-item-url" name="menu-item[<?php echo esc_attr( $_nav_menu_placeholder ); ?>][menu-item-url]" value="<?php echo esc_url( $ep['url'] ); ?>">
							<input type="hidden" class="menu-item-classes" name="menu-item[<?php echo esc_attr( $_nav_menu_placeholder ); ?>][menu-item-classes]" value="rowshost-endpoint-<?php echo esc_attr( $slug ); ?>">
						</li>
					<?php endforeach; ?>
				</ul>
			</div>
			<p class="button-controls wp-clearfix">
				<span class="list-controls">
					<label class="select-all">
						<input type="checkbox" class="select-all" onclick="var c=this.checked;document.querySelectorAll('#rowshost-endpoints-checklist input[type=checkbox]').forEach(function(el){el.checked=c;});">
						<?php esc_html_e( 'Select All', 'rowshost' ); ?>
					</label>
				</span>
				<span class="add-to-menu">
					<input type="submit" <?php wp_nav_menu_disabled_check( $nav_menu_selected_id ); ?> class="button submit-add-to-menu right" value="<?php esc_attr_e( 'Add to Menu', 'rowshost' ); ?>" name="add-post-type-menu-item" id="submit-posttype-rowshost-endpoints">
					<span class="spinner"></span>
				</span>
			</p>
		</div>
		<?php
	}

	private function mask_secret_tail( $plain, $mask_len = 10 ) {
		$plain = (string) $plain;
		if ( '' === $plain ) {
			return '';
		}
		$len = strlen( $plain );
		if ( $len <= $mask_len ) {
			return str_repeat( '•', $len );
		}
		return substr( $plain, 0, $len - $mask_len ) . str_repeat( '•', $mask_len );
	}

	public function render_admin_notices() {
		$page = sanitize_key( $_GET['page'] ?? '' );
		if ( 0 !== strpos( $page, 'rowshost' ) ) {
			return;
		}
		$messages = array(
			'updated'  => 'Settings saved successfully.',
			'synced'   => 'WHM server packages and cPanel accounts synced.',
			'linked'   => 'cPanel account linked to customer.',
			'emailed'  => 'Hosting welcome email sent.',
			'assigned' => 'Domain owner updated.',
			'saved'    => 'Subscription saved successfully.',
		);
		foreach ( $messages as $param => $text ) {
			if ( ! empty( $_GET[ $param ] ) ) {
				echo '<div class="notice notice-success is-dismissible"><p><strong>Rowshost:</strong> ' . esc_html( $text ) . '</p></div>';
				break;
			}
		}
	}

	public function register_menus() {
		add_menu_page(
			__( 'Rowshost', 'rowshost' ),
			__( 'Rowshost', 'rowshost' ),
			'manage_options',
			'rowshost',
			array( $this, 'render_dashboard_page' ),
			'dashicons-cloud',
			56
		);

		add_submenu_page( 'rowshost', 'Dashboard', 'Dashboard', 'manage_options', 'rowshost', array( $this, 'render_dashboard_page' ) );
		add_submenu_page( 'rowshost', 'WHM Servers', 'WHM Servers', 'manage_options', 'rowshost-servers', array( $this, 'render_servers_page' ) );
		add_submenu_page( 'rowshost', 'cPanel Accounts', 'cPanel Accounts', 'manage_options', 'rowshost-hosting', array( $this, 'render_hosting_page' ) );
		add_submenu_page( 'rowshost', 'Domains & Dynadot', 'Domains & Dynadot', 'manage_options', 'rowshost-domains', array( $this, 'render_domains_page' ) );
		add_submenu_page( 'rowshost', 'Subscriptions', 'Subscriptions', 'manage_options', 'rowshost-subscriptions', array( $this, 'render_subscriptions_page' ) );
		add_submenu_page( 'rowshost', 'Settings', 'Settings', 'manage_options', 'rowshost-settings', array( $this, 'render_settings_page' ) );
	}

	public function handle_form_submissions() {
		if ( ! current_user_can( 'manage_options' ) || empty( $_POST['rowshost_action'] ) ) {
			return;
		}

		$action = sanitize_key( $_POST['rowshost_action'] );
		check_admin_referer( 'rowshost_admin_' . $action );

		global $wpdb;

		if ( 'save_server' === $action ) {
			$server_id = absint( $_POST['server_id'] ?? 0 );
			$raw_token = trim( wp_unslash( $_POST['whm_api_token'] ?? '' ) );

			$data = array(
				'name'         => sanitize_text_field( wp_unslash( $_POST['name'] ?? '' ) ),
				'hostname'     => sanitize_text_field( wp_unslash( $_POST['hostname'] ?? '' ) ),
				'ip_address'   => sanitize_text_field( wp_unslash( $_POST['ip_address'] ?? '' ) ),
				'whm_username' => sanitize_text_field( wp_unslash( $_POST['whm_username'] ?? '' ) ),
				'ns1'          => sanitize_text_field( wp_unslash( $_POST['ns1'] ?? '' ) ),
				'ns2'          => sanitize_text_field( wp_unslash( $_POST['ns2'] ?? '' ) ),
				'ns3'          => sanitize_text_field( wp_unslash( $_POST['ns3'] ?? '' ) ),
				'ns4'          => sanitize_text_field( wp_unslash( $_POST['ns4'] ?? '' ) ),
			);

			if ( '' !== $raw_token ) {
				$data['whm_api_token'] = Rowshost_Crypto::encrypt( $raw_token );
			}

			$table = Rowshost_DB::table( 'servers' );
			if ( $server_id ) {
				$wpdb->update( $table, $data, array( 'id' => $server_id ) );
			} else {
				$wpdb->insert( $table, $data );
				$server_id = (int) $wpdb->insert_id;
			}

			if ( $server_id ) {
				Rowshost_WHM::sync_packages( $server_id );
				Rowshost_WHM::sync_accounts( $server_id );
			}

			wp_safe_redirect( add_query_arg( array( 'page' => 'rowshost-servers', 'updated' => 1 ), admin_url( 'admin.php' ) ) );
			exit;
		}

		if ( 'sync_server' === $action ) {
			$server_id = absint( $_POST['server_id'] ?? 0 );
			if ( $server_id ) {
				Rowshost_WHM::sync_packages( $server_id );
				Rowshost_WHM::sync_accounts( $server_id );
			}
			wp_safe_redirect( add_query_arg( array( 'page' => 'rowshost-servers', 'synced' => 1 ), admin_url( 'admin.php' ) ) );
			exit;
		}

		if ( 'link_cpanel' === $action ) {
			$server_id       = absint( $_POST['server_id'] ?? 0 );
			$cpanel_username = sanitize_user( wp_unslash( $_POST['cpanel_username'] ?? '' ), true );
			$user_id         = absint( $_POST['user_id'] ?? 0 );
			$send_welcome    = ! empty( $_POST['send_welcome'] );

			$cached = $wpdb->get_row(
				$wpdb->prepare(
					'SELECT * FROM ' . Rowshost_DB::table( 'cpanel_cache' ) . ' WHERE server_id = %d AND cpanel_username = %s',
					$server_id,
					$cpanel_username
				)
			);

			if ( $cached && $user_id ) {
				$wpdb->insert(
					Rowshost_DB::table( 'hosting_accounts' ),
					array(
						'user_id'         => $user_id,
						'server_id'       => $server_id,
						'domain'          => $cached->domain,
						'cpanel_username' => $cached->cpanel_username,
						'whm_package'     => $cached->whm_package,
						'status'          => $cached->status,
					)
				);
				$hosting_id = (int) $wpdb->insert_id;

				if ( $send_welcome && $hosting_id ) {
					Rowshost_Emails::send_hosting_welcome( $hosting_id );
				}
			}

			wp_safe_redirect( add_query_arg( array( 'page' => 'rowshost-hosting', 'linked' => 1 ), admin_url( 'admin.php' ) ) );
			exit;
		}

		if ( 'resend_welcome' === $action ) {
			$hosting_id = absint( $_POST['hosting_id'] ?? 0 );
			if ( $hosting_id ) {
				Rowshost_Emails::send_hosting_welcome( $hosting_id );
			}
			wp_safe_redirect( add_query_arg( array( 'page' => 'rowshost-hosting', 'emailed' => 1 ), admin_url( 'admin.php' ) ) );
			exit;
		}

		if ( 'save_dynadot' === $action ) {
			update_option( 'rowshost_dynadot_mode', sanitize_key( $_POST['dynadot_mode'] ?? 'live' ) );

			$api_key    = trim( wp_unslash( $_POST['dynadot_api_key'] ?? '' ) );
			$api_secret = trim( wp_unslash( $_POST['dynadot_api_secret'] ?? '' ) );
			$wh_key     = trim( wp_unslash( $_POST['dynadot_webhook_key'] ?? '' ) );
			$wh_secret  = trim( wp_unslash( $_POST['dynadot_webhook_secret'] ?? '' ) );

			if ( '' !== $api_key && false === strpos( $api_key, '•••' ) ) {
				update_option( 'rowshost_dynadot_api_key', Rowshost_Crypto::encrypt( $api_key ) );
			}
			if ( '' !== $api_secret && false === strpos( $api_secret, '•••' ) ) {
				update_option( 'rowshost_dynadot_api_secret', Rowshost_Crypto::encrypt( $api_secret ) );
			}
			if ( '' !== $wh_key && false === strpos( $wh_key, '•••' ) ) {
				update_option( 'rowshost_dynadot_webhook_key', Rowshost_Crypto::encrypt( $wh_key ) );
			}
			if ( '' !== $wh_secret && false === strpos( $wh_secret, '•••' ) ) {
				update_option( 'rowshost_dynadot_webhook_secret', Rowshost_Crypto::encrypt( $wh_secret ) );
			}

			update_option( 'rowshost_dynadot_default_tlds', sanitize_text_field( wp_unslash( $_POST['default_tlds'] ?? 'com,net,org,io,ai,co,xyz,locker' ) ) );
			update_option( 'rowshost_dynadot_ns1', sanitize_text_field( wp_unslash( $_POST['ns1'] ?? '' ) ) );
			update_option( 'rowshost_dynadot_ns2', sanitize_text_field( wp_unslash( $_POST['ns2'] ?? '' ) ) );
			update_option( 'rowshost_dynadot_ns3', sanitize_text_field( wp_unslash( $_POST['ns3'] ?? '' ) ) );
			update_option( 'rowshost_dynadot_ns4', sanitize_text_field( wp_unslash( $_POST['ns4'] ?? '' ) ) );
			update_option( 'rowshost_dynadot_default_privacy', sanitize_key( $_POST['default_privacy'] ?? 'full' ) );
			update_option( 'rowshost_dynadot_transfer_lock', ! empty( $_POST['transfer_lock'] ) ? '1' : '0' );
			update_option( 'rowshost_dynadot_reg_markup', (float) ( $_POST['reg_markup'] ?? 3.00 ) );
			update_option( 'rowshost_dynadot_transfer_markup', (float) ( $_POST['transfer_markup'] ?? 0.00 ) );

			if ( ! empty( $_POST['sync_now'] ) ) {
				Rowshost_Dynadot::sync_domains();
			}

			wp_safe_redirect( add_query_arg( array( 'page' => 'rowshost-domains', 'updated' => 1 ), admin_url( 'admin.php' ) ) );
			exit;
		}

		if ( 'assign_domain_owner' === $action ) {
			$domain_id = absint( $_POST['domain_id'] ?? 0 );
			$user_id   = absint( $_POST['user_id'] ?? 0 );
			if ( $domain_id ) {
				$wpdb->update( Rowshost_DB::table( 'domains' ), array( 'user_id' => $user_id ), array( 'id' => $domain_id ) );
			}
			wp_safe_redirect( add_query_arg( array( 'page' => 'rowshost-domains', 'assigned' => 1 ), admin_url( 'admin.php' ) ) );
			exit;
		}

		if ( 'save_subscription' === $action ) {
			$sub_id       = absint( $_POST['sub_id'] ?? 0 );
			$user_id      = absint( $_POST['user_id'] ?? 0 );
			$service_type = sanitize_key( $_POST['service_type'] ?? 'hosting' );
			$service_id   = absint( $_POST['service_id'] ?? 0 );
			$plan_label   = sanitize_text_field( wp_unslash( $_POST['plan_label'] ?? '' ) );
			$amount       = (float) ( $_POST['amount'] ?? 0 );
			$interval     = max( 1, absint( $_POST['billing_interval'] ?? 1 ) );
			$period       = sanitize_key( $_POST['billing_period'] ?? 'month' );
			$start_date   = sanitize_text_field( wp_unslash( $_POST['start_date'] ?? gmdate( 'Y-m-d' ) ) ) . ' 00:00:00';
			$next_due     = sanitize_text_field( wp_unslash( $_POST['next_payment_date'] ?? gmdate( 'Y-m-d' ) ) ) . ' 00:00:00';
			$status       = sanitize_key( $_POST['status'] ?? 'active' );
			$auto_charge  = ! empty( $_POST['auto_charge'] ) ? 1 : 0;

			$table = Rowshost_DB::table( 'subscriptions' );
			if ( $sub_id ) {
				$wpdb->update(
					$table,
					array(
						'plan_label'        => $plan_label,
						'amount'            => $amount,
						'billing_interval'  => $interval,
						'billing_period'    => $period,
						'start_date'        => $start_date,
						'next_payment_date' => $next_due,
						'status'            => $status,
						'auto_charge'       => $auto_charge,
					),
					array( 'id' => $sub_id )
				);
			} elseif ( $user_id ) {
				$new_id = Rowshost_Billing::create_subscription(
					array(
						'user_id'           => $user_id,
						'service_type'      => $service_type,
						'service_id'        => $service_id,
						'plan_label'        => $plan_label,
						'amount'            => $amount,
						'billing_interval'  => $interval,
						'billing_period'    => $period,
						'start_date'        => $start_date,
						'next_payment_date' => $next_due,
						'status'            => $status,
						'auto_charge'       => $auto_charge,
					)
				);

				if ( $new_id && $service_id ) {
					$svc_table = 'domain' === $service_type ? Rowshost_DB::table( 'domains' ) : Rowshost_DB::table( 'hosting_accounts' );
					$wpdb->update( $svc_table, array( 'subscription_id' => $new_id ), array( 'id' => $service_id ) );
				}
			}

			wp_safe_redirect( add_query_arg( array( 'page' => 'rowshost-subscriptions', 'saved' => 1 ), admin_url( 'admin.php' ) ) );
			exit;
		}

		if ( 'save_settings' === $action ) {
			update_option( 'rowshost_portal_mode', sanitize_key( $_POST['portal_mode'] ?? 'shortcode' ) );
			update_option( 'rowshost_portal_page_id', absint( $_POST['portal_page_id'] ?? 0 ) );
			update_option( 'rowshost_grace_period_days', max( 1, absint( $_POST['grace_period_days'] ?? 5 ) ) );
			flush_rewrite_rules();

			wp_safe_redirect( add_query_arg( array( 'page' => 'rowshost-settings', 'updated' => 1 ), admin_url( 'admin.php' ) ) );
			exit;
		}
	}

	public function add_wc_product_tab( $tabs ) {
		$tabs['rowshost_hosting'] = array(
			'label'    => __( 'Rowshost Hosting', 'rowshost' ),
			'target'   => 'rowshost_hosting_product_data',
			'class'    => array(),
			'priority' => 25,
		);
		return $tabs;
	}

	public function render_wc_product_panel() {
		global $post, $wpdb;
		$servers     = $wpdb->get_results( 'SELECT * FROM ' . Rowshost_DB::table( 'servers' ) . ' ORDER BY name ASC' );
		$is_hosting  = get_post_meta( $post->ID, '_rowshost_is_hosting', true );
		$server_id   = absint( get_post_meta( $post->ID, '_rowshost_server_id', true ) );
		$whm_package = get_post_meta( $post->ID, '_rowshost_whm_package', true );
		$interval    = get_post_meta( $post->ID, '_rowshost_billing_interval', true ) ?: '1';
		$period      = get_post_meta( $post->ID, '_rowshost_billing_period', true ) ?: 'month';
		?>
		<div id="rowshost_hosting_product_data" class="panel woocommerce_options_panel">
			<div class="options_group">
				<?php
				woocommerce_wp_checkbox(
					array(
						'id'          => '_rowshost_is_hosting',
						'label'       => __( 'Enable Hosting Provisioning', 'rowshost' ),
						'description' => __( 'Automatically provision a cPanel account when this product is purchased.', 'rowshost' ),
						'value'       => $is_hosting,
					)
				);

				$server_opts = array( '0' => __( '— Select WHM Server —', 'rowshost' ) );
				$pkg_opts    = array( '' => __( '— Select WHM Package —', 'rowshost' ) );

				foreach ( $servers as $srv ) {
					$server_opts[ $srv->id ] = $srv->name . ' (' . $srv->hostname . ')';
					$cached_pkgs             = json_decode( $srv->packages_cache ?: '[]', true );
					if ( is_array( $cached_pkgs ) ) {
						foreach ( $cached_pkgs as $p ) {
							$pkg_opts[ $p['name'] ] = $p['name'] . ' [' . $srv->name . ']';
						}
					}
				}

				woocommerce_wp_select(
					array(
						'id'      => '_rowshost_server_id',
						'label'   => __( 'WHM Server', 'rowshost' ),
						'options' => $server_opts,
						'value'   => $server_id,
					)
				);

				woocommerce_wp_select(
					array(
						'id'      => '_rowshost_whm_package',
						'label'   => __( 'WHM Package', 'rowshost' ),
						'options' => $pkg_opts,
						'value'   => $whm_package,
					)
				);

				woocommerce_wp_text_input(
					array(
						'id'                => '_rowshost_billing_interval',
						'label'             => __( 'Billing Interval', 'rowshost' ),
						'type'              => 'number',
						'custom_attributes' => array( 'min' => 1, 'step' => 1 ),
						'value'             => $interval,
					)
				);

				woocommerce_wp_select(
					array(
						'id'      => '_rowshost_billing_period',
						'label'   => __( 'Billing Period', 'rowshost' ),
						'options' => array(
							'month' => __( 'Month(s)', 'rowshost' ),
							'year'  => __( 'Year(s)', 'rowshost' ),
						),
						'value'   => $period,
					)
				);
				?>
			</div>
		</div>
		<?php
	}

	public function save_wc_product_meta( $post_id ) {
		update_post_meta( $post_id, '_rowshost_is_hosting', isset( $_POST['_rowshost_is_hosting'] ) ? 'yes' : 'no' );
		update_post_meta( $post_id, '_rowshost_server_id', absint( $_POST['_rowshost_server_id'] ?? 0 ) );
		update_post_meta( $post_id, '_rowshost_whm_package', sanitize_text_field( wp_unslash( $_POST['_rowshost_whm_package'] ?? '' ) ) );
		update_post_meta( $post_id, '_rowshost_billing_interval', max( 1, absint( $_POST['_rowshost_billing_interval'] ?? 1 ) ) );
		update_post_meta( $post_id, '_rowshost_billing_period', sanitize_key( $_POST['_rowshost_billing_period'] ?? 'month' ) );
	}

	public function render_dashboard_page() {
		global $wpdb;
		$hosting_count = (int) $wpdb->get_var( 'SELECT COUNT(*) FROM ' . Rowshost_DB::table( 'hosting_accounts' ) . " WHERE status = 'active'" );
		$domain_count  = (int) $wpdb->get_var( 'SELECT COUNT(*) FROM ' . Rowshost_DB::table( 'domains' ) . " WHERE status = 'active'" );
		$sub_count     = (int) $wpdb->get_var( 'SELECT COUNT(*) FROM ' . Rowshost_DB::table( 'subscriptions' ) . " WHERE status = 'active'" );
		$mrr           = (float) $wpdb->get_var( 'SELECT SUM(amount) FROM ' . Rowshost_DB::table( 'subscriptions' ) . " WHERE status = 'active' AND billing_period = 'month'" );
		?>
		<div class="wrap">
			<h1>Rowshost Overview <span style="font-size:13px;font-weight:500;color:#64748b;">v<?php echo esc_html( ROWSHOST_VERSION ); ?></span></h1>
			<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-top:20px;">
				<div class="card" style="padding:20px;margin:0;"><h3>Active Hosting</h3><p style="font-size:28px;font-weight:700;margin:8px 0 0;"><?php echo $hosting_count; ?></p></div>
				<div class="card" style="padding:20px;margin:0;"><h3>Active Domains</h3><p style="font-size:28px;font-weight:700;margin:8px 0 0;"><?php echo $domain_count; ?></p></div>
				<div class="card" style="padding:20px;margin:0;"><h3>Active Subscriptions</h3><p style="font-size:28px;font-weight:700;margin:8px 0 0;"><?php echo $sub_count; ?></p></div>
				<div class="card" style="padding:20px;margin:0;"><h3>Monthly Recurring</h3><p style="font-size:28px;font-weight:700;margin:8px 0 0;">$<?php echo number_format( $mrr, 2 ); ?></p></div>
			</div>
		</div>
		<?php
	}

	public function render_servers_page() {
		global $wpdb;
		$servers = $wpdb->get_results( 'SELECT * FROM ' . Rowshost_DB::table( 'servers' ) . ' ORDER BY id DESC' );
		?>
		<div class="wrap">
			<h1>WHM Servers</h1>
			<form method="post" class="card" style="max-width:760px;padding:20px;margin-bottom:24px;">
				<?php wp_nonce_field( 'rowshost_admin_save_server' ); ?>
				<input type="hidden" name="rowshost_action" value="save_server">
				<h2>Connect WHM Server</h2>
				<table class="form-table">
					<tr><th>Server Label</th><td><input type="text" name="name" class="regular-text" placeholder="Rowshost WHM" required></td></tr>
					<tr><th>WHM Hostname</th><td><input type="text" name="hostname" class="regular-text" placeholder="whm.rowshost.com" required></td></tr>
					<tr><th>Shared Server IP</th><td><input type="text" name="ip_address" class="regular-text" placeholder="207.7.81.241"></td></tr>
					<tr><th>WHM Username</th><td><input type="text" name="whm_username" class="regular-text" placeholder="rowshost" required></td></tr>
					<tr><th>WHM API Token</th><td><input type="password" name="whm_api_token" class="regular-text" required></td></tr>
					<tr><th>Nameservers</th><td>
						<input type="text" name="ns1" placeholder="ns1.rowshost.com" style="margin-bottom:6px;"><br>
						<input type="text" name="ns2" placeholder="ns2.rowshost.com">
					</td></tr>
				</table>
				<?php submit_button( 'Save & Sync Server' ); ?>
			</form>

			<h2>Connected Servers</h2>
			<table class="widefat striped">
				<thead><tr><th>Name</th><th>Hostname</th><th>Synced Packages</th><th>Last Synced</th><th>Action</th></tr></thead>
				<tbody>
				<?php foreach ( $servers as $srv ) :
					$pkgs = json_decode( $srv->packages_cache ?: '[]', true );
					?>
					<tr>
						<td><strong><?php echo esc_html( $srv->name ); ?></strong></td>
						<td><?php echo esc_html( $srv->hostname ); ?></td>
						<td><?php echo is_array( $pkgs ) ? count( $pkgs ) . ' packages' : '0'; ?></td>
						<td><?php echo esc_html( $srv->last_synced ?: 'Never' ); ?></td>
						<td>
							<form method="post" style="display:inline;">
								<?php wp_nonce_field( 'rowshost_admin_sync_server' ); ?>
								<input type="hidden" name="rowshost_action" value="sync_server">
								<input type="hidden" name="server_id" value="<?php echo absint( $srv->id ); ?>">
								<button type="submit" class="button">Sync Packages &amp; Accounts</button>
							</form>
						</td>
					</tr>
				<?php endforeach; ?>
				</tbody>
			</table>
		</div>
		<?php
	}

	public function render_hosting_page() {
		global $wpdb;
		$accounts = $wpdb->get_results( 'SELECT * FROM ' . Rowshost_DB::table( 'hosting_accounts' ) . ' ORDER BY id DESC' );
		$cached   = $wpdb->get_results( 'SELECT * FROM ' . Rowshost_DB::table( 'cpanel_cache' ) . ' ORDER BY cpanel_username ASC' );
		$users    = get_users( array( 'fields' => array( 'ID', 'user_login', 'user_email' ) ) );
		?>
		<div class="wrap">
			<h1>Hosting &amp; cPanel Accounts</h1>

			<form method="post" class="card" style="max-width:760px;padding:20px;margin-bottom:24px;">
				<?php wp_nonce_field( 'rowshost_admin_link_cpanel' ); ?>
				<input type="hidden" name="rowshost_action" value="link_cpanel">
				<h2>Link Existing cPanel Account to Customer</h2>
				<p class="description">Assign an already-active cPanel account to a WordPress customer without duplicating the account or creating dummy $0 subscriptions.</p>
				<table class="form-table">
					<tr>
						<th>Synced cPanel Account</th>
						<td>
							<select name="cpanel_username" id="rh-cpanel-select" required onchange="document.getElementById('rh-cpanel-server').value = this.options[this.selectedIndex].dataset.server;">
								<option value="">— Select cPanel Account —</option>
								<?php foreach ( $cached as $c ) : ?>
									<option value="<?php echo esc_attr( $c->cpanel_username ); ?>" data-server="<?php echo absint( $c->server_id ); ?>">
										<?php echo esc_html( $c->cpanel_username . ' — ' . $c->domain . ' (' . $c->whm_package . ')' ); ?>
									</option>
								<?php endforeach; ?>
							</select>
							<input type="hidden" name="server_id" id="rh-cpanel-server" value="0">
						</td>
					</tr>
					<tr>
						<th>Customer (WordPress User)</th>
						<td>
							<select name="user_id" required>
								<option value="">— Select Customer —</option>
								<?php foreach ( $users as $u ) : ?>
									<option value="<?php echo absint( $u->ID ); ?>"><?php echo esc_html( $u->user_login . ' (' . $u->user_email . ')' ); ?></option>
								<?php endforeach; ?>
							</select>
						</td>
					</tr>
					<tr>
						<th>Welcome Email</th>
						<td><label><input type="checkbox" name="send_welcome" value="1"> Send hosting welcome &amp; portal login email now</label></td>
					</tr>
				</table>
				<?php submit_button( 'Assign cPanel Account' ); ?>
			</form>

			<h2>Assigned Customer Hosting Accounts</h2>
			<table class="widefat striped">
				<thead><tr><th>Domain</th><th>cPanel User</th><th>Customer</th><th>Package</th><th>Status</th><th>Actions</th></tr></thead>
				<tbody>
				<?php foreach ( $accounts as $acc ) :
					$u = get_userdata( $acc->user_id );
					?>
					<tr>
						<td><strong><?php echo esc_html( $acc->domain ); ?></strong></td>
						<td><code><?php echo esc_html( $acc->cpanel_username ); ?></code></td>
						<td><?php echo $u ? esc_html( $u->user_email ) : 'Unassigned'; ?></td>
						<td><?php echo esc_html( $acc->whm_package ); ?></td>
						<td><?php echo esc_html( ucfirst( $acc->status ) ); ?></td>
						<td>
							<form method="post" style="display:inline;">
								<?php wp_nonce_field( 'rowshost_admin_resend_welcome' ); ?>
								<input type="hidden" name="rowshost_action" value="resend_welcome">
								<input type="hidden" name="hosting_id" value="<?php echo absint( $acc->id ); ?>">
								<button type="submit" class="button button-small">Send Welcome Email</button>
							</form>
						</td>
					</tr>
				<?php endforeach; ?>
				</tbody>
			</table>
		</div>
		<?php
	}

	public function render_domains_page() {
		global $wpdb;
		$domains           = $wpdb->get_results( 'SELECT * FROM ' . Rowshost_DB::table( 'domains' ) . ' ORDER BY domain_name ASC' );
		$users             = get_users( array( 'fields' => array( 'ID', 'user_login', 'user_email' ) ) );
		$masked_api_key    = $this->mask_secret_tail( Rowshost_Crypto::decrypt( get_option( 'rowshost_dynadot_api_key', '' ) ) );
		$masked_api_secret = $this->mask_secret_tail( Rowshost_Crypto::decrypt( get_option( 'rowshost_dynadot_api_secret', '' ) ) );
		$masked_wh_key     = $this->mask_secret_tail( Rowshost_Crypto::decrypt( get_option( 'rowshost_dynadot_webhook_key', '' ) ) );
		$masked_wh_secret  = $this->mask_secret_tail( Rowshost_Crypto::decrypt( get_option( 'rowshost_dynadot_webhook_secret', '' ) ) );
		$webhook_url       = rest_url( 'rowshost/v1/dynadot-webhook' );
		$handoff_url       = add_query_arg(
			array(
				'rowshost_action' => 'add_domain',
				'type'            => 'register',
				'years'           => '1',
				'domain'          => '',
			),
			home_url( '/' )
		);
		?>
		<div class="wrap">
			<h1>Domains &amp; Dynadot Settings</h1>
			<form method="post" class="card" style="max-width:820px;padding:20px;margin-bottom:24px;">
				<?php wp_nonce_field( 'rowshost_admin_save_dynadot' ); ?>
				<input type="hidden" name="rowshost_action" value="save_dynadot">
				<h2>1. Dynadot API Credentials &amp; Retail Pricing</h2>
				<table class="form-table">
					<tr>
						<th>Environment</th>
						<td>
							<select name="dynadot_mode">
								<option value="live" <?php selected( get_option( 'rowshost_dynadot_mode', 'live' ), 'live' ); ?>>Live / Production</option>
								<option value="sandbox" <?php selected( get_option( 'rowshost_dynadot_mode' ), 'sandbox' ); ?>>Sandbox</option>
							</select>
						</td>
					</tr>
					<tr><th>Dynadot API Key</th><td><input type="text" name="dynadot_api_key" class="regular-text" value="<?php echo esc_attr( $masked_api_key ); ?>" onfocus="if(this.value.indexOf('•••')!==-1)this.value='';"> <span class="description">Click to replace key.</span></td></tr>
					<tr><th>Dynadot Secret Key</th><td><input type="text" name="dynadot_api_secret" class="regular-text" value="<?php echo esc_attr( $masked_api_secret ); ?>" onfocus="if(this.value.indexOf('•••')!==-1)this.value='';"></td></tr>
					<tr><th>Default Search TLDs</th><td><input type="text" name="default_tlds" class="regular-text" value="<?php echo esc_attr( get_option( 'rowshost_dynadot_default_tlds', 'com,net,org,io,ai,co,xyz,locker' ) ); ?>"></td></tr>
					<tr><th>Registration Markup ($ USD)</th><td><input type="number" step="0.01" name="reg_markup" value="<?php echo esc_attr( get_option( 'rowshost_dynadot_reg_markup', '3.00' ) ); ?>"></td></tr>
					<tr><th>Transfer Markup ($ USD)</th><td><input type="number" step="0.01" name="transfer_markup" value="<?php echo esc_attr( get_option( 'rowshost_dynadot_transfer_markup', '0.00' ) ); ?>"></td></tr>
					<tr><th>Default Nameservers</th><td>
						<input type="text" name="ns1" value="<?php echo esc_attr( get_option( 'rowshost_dynadot_ns1', 'ns1.rowshost.com' ) ); ?>" style="margin-bottom:6px;"><br>
						<input type="text" name="ns2" value="<?php echo esc_attr( get_option( 'rowshost_dynadot_ns2', 'ns2.rowshost.com' ) ); ?>">
					</td></tr>
					<tr><th>Dynadot Webhook URL</th><td><code><?php echo esc_html( $webhook_url ); ?></code></td></tr>
					<tr><th>Webhook Production Key</th><td><input type="text" name="dynadot_webhook_key" class="regular-text" value="<?php echo esc_attr( $masked_wh_key ); ?>" onfocus="if(this.value.indexOf('•••')!==-1)this.value='';"></td></tr>
					<tr><th>Webhook Secret Key</th><td><input type="text" name="dynadot_webhook_secret" class="regular-text" value="<?php echo esc_attr( $masked_wh_secret ); ?>" onfocus="if(this.value.indexOf('•••')!==-1)this.value='';"></td></tr>
					<tr><th>External Search Handoff URL</th><td><code><?php echo esc_html( $handoff_url ); ?></code></td></tr>
					<tr><th>Sync Domains</th><td><label><input type="checkbox" name="sync_now" value="1"> Sync all domains from Dynadot when saving</label></td></tr>
				</table>
				<?php submit_button( 'Save Dynadot Settings' ); ?>
			</form>

			<h2>Synced &amp; Registered Domains (<?php echo count( $domains ); ?>)</h2>
			<table class="widefat striped">
				<thead><tr><th>Domain</th><th>Status</th><th>Expiration</th><th>Nameservers</th><th>Assigned Customer</th></tr></thead>
				<tbody>
				<?php foreach ( $domains as $d ) :
					$ns = json_decode( $d->nameservers ?: '[]', true );
					?>
					<tr>
						<td><strong><?php echo esc_html( $d->domain_name ); ?></strong></td>
						<td><?php echo esc_html( ucfirst( $d->status ) ); ?></td>
						<td><?php echo esc_html( $d->expiration_date ? gmdate( 'Y-m-d', strtotime( $d->expiration_date ) ) : '—' ); ?></td>
						<td><?php echo esc_html( is_array( $ns ) && ! empty( $ns ) ? implode( ', ', $ns ) : 'Default' ); ?></td>
						<td>
							<form method="post" style="display:flex;gap:6px;">
								<?php wp_nonce_field( 'rowshost_admin_assign_domain_owner' ); ?>
								<input type="hidden" name="rowshost_action" value="assign_domain_owner">
								<input type="hidden" name="domain_id" value="<?php echo absint( $d->id ); ?>">
								<select name="user_id">
									<option value="0">— Unassigned (House Domain) —</option>
									<?php foreach ( $users as $u ) : ?>
										<option value="<?php echo absint( $u->ID ); ?>" <?php selected( (int) $d->user_id, (int) $u->ID ); ?>><?php echo esc_html( $u->user_login ); ?></option>
									<?php endforeach; ?>
								</select>
								<button type="submit" class="button button-small">Save</button>
							</form>
						</td>
					</tr>
				<?php endforeach; ?>
				</tbody>
			</table>
		</div>
		<?php
	}

	public function render_subscriptions_page() {
		global $wpdb;
		$subs  = $wpdb->get_results( 'SELECT * FROM ' . Rowshost_DB::table( 'subscriptions' ) . ' ORDER BY next_payment_date ASC' );
		$users = get_users( array( 'fields' => array( 'ID', 'user_login', 'user_email' ) ) );
		?>
		<div class="wrap">
			<h1>Subscriptions &amp; Billing Due Dates</h1>
			<form method="post" class="card" style="max-width:780px;padding:20px;margin-bottom:24px;">
				<?php wp_nonce_field( 'rowshost_admin_save_subscription' ); ?>
				<input type="hidden" name="rowshost_action" value="save_subscription">
				<h2>Create Recurring Subscription (Custom Start &amp; Due Date)</h2>
				<table class="form-table">
					<tr>
						<th>Customer</th>
						<td>
							<select name="user_id" required>
								<option value="">— Select Customer —</option>
								<?php foreach ( $users as $u ) : ?>
									<option value="<?php echo absint( $u->ID ); ?>"><?php echo esc_html( $u->user_login . ' (' . $u->user_email . ')' ); ?></option>
								<?php endforeach; ?>
							</select>
						</td>
					</tr>
					<tr><th>Plan / Service Label</th><td><input type="text" name="plan_label" class="regular-text" placeholder="Rowshost Pro Hosting - norristowing.com" required></td></tr>
					<tr><th>Amount ($ USD)</th><td><input type="number" step="0.01" name="amount" value="15.00" required></td></tr>
					<tr>
						<th>Billing Cycle</th>
						<td>
							Every <input type="number" name="billing_interval" value="1" min="1" style="width:65px;">
							<select name="billing_period">
								<option value="month">Month(s)</option>
								<option value="year">Year(s)</option>
							</select>
						</td>
					</tr>
					<tr><th>Subscription Start Date</th><td><input type="date" name="start_date" value="<?php echo esc_attr( gmdate( 'Y-m-d' ) ); ?>" required></td></tr>
					<tr><th>Next Payment Due Date</th><td><input type="date" name="next_payment_date" value="<?php echo esc_attr( gmdate( 'Y-m-01', strtotime( '+1 month' ) ) ); ?>" required></td></tr>
					<tr><th>Auto-Charge Saved Token</th><td><label><input type="checkbox" name="auto_charge" value="1" checked> Automatically charge saved WooCommerce payment method when due</label></td></tr>
				</table>
				<?php submit_button( 'Create Subscription' ); ?>
			</form>

			<h2>Active &amp; Scheduled Subscriptions</h2>
			<table class="widefat striped">
				<thead><tr><th>Customer</th><th>Service</th><th>Amount</th><th>Start Date</th><th>Next Due Date</th><th>Status</th></tr></thead>
				<tbody>
				<?php foreach ( $subs as $s ) :
					$u = get_userdata( $s->user_id );
					?>
					<tr>
						<td><?php echo $u ? esc_html( $u->user_email ) : 'User #' . absint( $s->user_id ); ?></td>
						<td><strong><?php echo esc_html( $s->plan_label ); ?></strong></td>
						<td>$<?php echo esc_html( number_format( (float) $s->amount, 2 ) . ' / ' . $s->billing_period ); ?></td>
						<td><?php echo esc_html( gmdate( 'Y-m-d', strtotime( $s->start_date ) ) ); ?></td>
						<td><strong><?php echo esc_html( gmdate( 'Y-m-d', strtotime( $s->next_payment_date ) ) ); ?></strong></td>
						<td><?php echo esc_html( ucfirst( $s->status ) ); ?></td>
					</tr>
				<?php endforeach; ?>
				</tbody>
			</table>
		</div>
		<?php
	}

	public function render_settings_page() {
		?>
		<div class="wrap">
			<h1>Rowshost General &amp; Portal Settings</h1>
			<form method="post" class="card" style="max-width:760px;padding:20px;">
				<?php wp_nonce_field( 'rowshost_admin_save_settings' ); ?>
				<input type="hidden" name="rowshost_action" value="save_settings">
				<table class="form-table">
					<tr>
						<th>Client Portal Mode</th>
						<td>
							<select name="portal_mode">
								<option value="shortcode" <?php selected( get_option( 'rowshost_portal_mode', 'shortcode' ), 'shortcode' ); ?>>Custom Elementor Portal Page (Recommended)</option>
								<option value="my_account" <?php selected( get_option( 'rowshost_portal_mode', 'shortcode' ), 'my_account' ); ?>>WooCommerce My Account Endpoints</option>
							</select>
							<p class="description">Select your main Client Portal page below so all <strong>Rowshost Endpoints</strong> in <em>Appearance &rarr; Menus</em> and login redirects point there cleanly.</p>
						</td>
					</tr>
					<tr>
						<th>Main Client Portal Page</th>
						<td>
							<?php
							wp_dropdown_pages(
								array(
									'name'              => 'portal_page_id',
									'selected'          => absint( get_option( 'rowshost_portal_page_id', 0 ) ),
									'show_option_none'  => '— Select Page —',
									'option_none_value' => 0,
								)
							);
							?>
						</td>
					</tr>
					<tr>
						<th>Overdue Grace Period (Days)</th>
						<td><input type="number" name="grace_period_days" min="1" max="30" value="<?php echo esc_attr( get_option( 'rowshost_grace_period_days', 5 ) ); ?>"></td>
					</tr>
				</table>
				<?php submit_button( 'Save Settings' ); ?>
			</form>
		</div>
		<?php
	}
}