<?php
/**
 * Aura Builder settings — construction mode and global options.
 *
 * @package AuraBuilder
 */

declare(strict_types=1);

namespace AuraBuilder\Admin;

use AuraBuilder\Frontend\BrandCredit;
use AuraBuilder\Frontend\ConstructionMode;
use AuraBuilder\Licensing\License;

final class SettingsPage {

	public function hooks(): void {
		add_action( 'admin_menu', array( $this, 'menu' ) );
		add_action( 'admin_init', array( $this, 'register' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'assets' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'menu_icon_css' ) );
		add_action( 'admin_bar_menu', array( $this, 'admin_bar' ), 90 );
		add_action( 'admin_notices', array( $this, 'notice' ) );
	}

	/**
	 * Color picker on settings screen.
	 *
	 * @param string $hook Hook suffix.
	 */
	public function assets( string $hook ): void {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$page = isset( $_GET['page'] ) ? (string) $_GET['page'] : '';
		if ( $page !== 'aura-builder-settings' ) {
			return;
		}
		wp_enqueue_style( 'wp-color-picker' );
		wp_enqueue_script( 'wp-color-picker' );
		wp_add_inline_script(
			'wp-color-picker',
			"jQuery(function($){ $('.ab-color-field').wpColorPicker({ change: function(){ abCreditPreview(); }, clear: function(){ setTimeout(abCreditPreview, 10); } }); function abCreditPreview(){ var t=$('#ab-credit-text-color').val()||'#4f46e5'; var b=$('#ab-credit-bg-color').val()||'#ffffff'; var el=document.getElementById('ab-credit-preview'); if(!el) return; el.style.background=b; el.style.color=t; var a=el.querySelector('a'); if(a) a.style.color=t; } abCreditPreview(); });"
		);
	}

	public function menu(): void {
		// Settings is ONLY a submenu under the main "Páginas" hub (see PagesList).
		// Do NOT register the top-level menu here — that forced manage_options on the
		// parent slug and caused "Sem permissão para acessar esta página" for many users.
		add_submenu_page(
			'aura-builder-pages',
			__( 'Settings', 'auranet-page-theme-builder' ),
			__( 'Configurações', 'auranet-page-theme-builder' ),
			'manage_options',
			'aura-builder-settings',
			array( $this, 'render' )
		);
	}

	public function register(): void {
		register_setting(
			'aptb_settings',
			ConstructionMode::OPTION,
			array(
				'type'              => 'string',
				'sanitize_callback' => static function ( $v ) {
					return $v === '1' || $v === 1 || $v === true || $v === 'on' ? '1' : '0';
				},
				'default'           => '0',
			)
		);
		register_setting(
			'aptb_settings',
			ConstructionMode::OPTION_TITLE,
			array(
				'type'              => 'string',
				'sanitize_callback' => 'sanitize_text_field',
				'default'           => 'Estamos em construção',
			)
		);
		register_setting(
			'aptb_settings',
			ConstructionMode::OPTION_MESSAGE,
			array(
				'type'              => 'string',
				'sanitize_callback' => 'sanitize_textarea_field',
				'default'           => '',
			)
		);
		// Opt-in credit only used when AURA_BUILDER_WPORG_MODE is true.
		register_setting(
			'aptb_settings',
			BrandCredit::OPTION_OPT_IN,
			array(
				'type'              => 'string',
				'sanitize_callback' => static function ( $v ) {
					return $v === '1' || $v === 1 || $v === true || $v === 'on' ? '1' : '0';
				},
				'default'           => '0',
			)
		);
		register_setting(
			'aptb_settings',
			BrandCredit::OPTION_TEXT_COLOR,
			array(
				'type'              => 'string',
				'sanitize_callback' => static function ( $v ) {
					$c = BrandCredit::sanitize_color( $v, BrandCredit::DEFAULT_TEXT_COLOR );
					// Sync into Globais do site so editor + front stay aligned.
					$bg = BrandCredit::sanitize_color(
						isset( $_POST[ BrandCredit::OPTION_BG_COLOR ] ) // phpcs:ignore WordPress.Security.NonceVerification.Missing
							? wp_unslash( (string) $_POST[ BrandCredit::OPTION_BG_COLOR ] ) // phpcs:ignore
							: BrandCredit::bg_color(),
						BrandCredit::DEFAULT_BG_COLOR
					);
					BrandCredit::save_colors( $c, $bg );
					return $c;
				},
				'default'           => BrandCredit::DEFAULT_TEXT_COLOR,
			)
		);
		register_setting(
			'aptb_settings',
			BrandCredit::OPTION_BG_COLOR,
			array(
				'type'              => 'string',
				'sanitize_callback' => static function ( $v ) {
					return BrandCredit::sanitize_color( $v, BrandCredit::DEFAULT_BG_COLOR );
				},
				'default'           => BrandCredit::DEFAULT_BG_COLOR,
			)
		);
	}

	/**
	 * Activate / deactivate license (credit removal).
	 */
	public function handle_license_post(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		// phpcs:ignore WordPress.Security.NonceVerification.Missing
		if ( empty( $_POST['ab_license_action'] ) ) {
			return;
		}
		check_admin_referer( 'aptb_license' );
		$action = sanitize_key( (string) wp_unslash( $_POST['ab_license_action'] ) );
		$flag   = 'err';
		$msg    = '';
		if ( $action === 'activate' ) {
			$key = isset( $_POST['ab_license_key'] ) ? (string) wp_unslash( $_POST['ab_license_key'] ) : '';
			$res = License::activate( $key );
			if ( is_wp_error( $res ) ) {
				$flag = 'err';
				$msg  = $res->get_error_message();
			} else {
				$flag = 'ok';
				$msg  = __( 'Licença ativada. O crédito “Powered by Auranet Builder” foi removido deste site.', 'auranet-page-theme-builder' );
			}
		} elseif ( $action === 'deactivate' ) {
			License::deactivate();
			$flag = 'off';
			$msg  = __( 'Licença desativada. O crédito voltará a aparecer no rodapé público.', 'auranet-page-theme-builder' );
		}
		set_transient(
			'aptb_license_flash',
			array(
				'flag' => $flag,
				'msg'  => $msg,
			),
			60
		);
		wp_safe_redirect( admin_url( 'admin.php?page=aura-builder-settings#ab-license' ) );
		exit;
	}

	public function menu_icon_css(): void {
		if ( ! defined( 'AURA_BUILDER_LOGO_64_URL' ) ) {
			return;
		}
		// Top-level slug is now aura-builder-pages (PagesList hub).
		$css = '#adminmenu #toplevel_page_aura-builder-pages .wp-menu-image img{'
			. 'width:20px;height:20px;padding:6px 0 0;object-fit:contain;}'
			. '#adminmenu #toplevel_page_aura-builder-pages.wp-has-current-submenu .wp-menu-image img,'
			. '#adminmenu #toplevel_page_aura-builder-pages.current .wp-menu-image img{opacity:1;}';
		wp_register_style( 'aptb-admin-menu', false, array(), AURA_BUILDER_VERSION );
		wp_enqueue_style( 'aptb-admin-menu' );
		wp_add_inline_style( 'aptb-admin-menu', wp_strip_all_tags( $css ) );
	}

	public function render(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Sem permissão.', 'auranet-page-theme-builder' ) );
		}

		$enabled = ConstructionMode::is_enabled();
		$title   = (string) get_option( ConstructionMode::OPTION_TITLE, 'Estamos em construção' );
		$message = (string) get_option(
			ConstructionMode::OPTION_MESSAGE,
			'Estamos desenvolvendo um novo design para o site. Em breve você poderá conferir uma experiência renovada, mais moderna e pensada para você.'
		);
		$home        = home_url( '/' );
		$logo        = defined( 'AURA_BUILDER_LOGO_64_URL' ) ? AURA_BUILDER_LOGO_64_URL : '';
		$opt_in      = (string) get_option( BrandCredit::OPTION_OPT_IN, '0' ) === '1';
		$credit_text = BrandCredit::text_color();
		$credit_bg   = BrandCredit::bg_color();
		?>
		<div class="wrap" style="max-width:720px">
			<h1 style="display:flex;align-items:center;gap:10px">
				<?php if ( $logo ) : ?>
					<img src="<?php echo esc_url( $logo ); ?>" alt="" width="32" height="32" style="width:32px;height:32px;object-fit:contain;border-radius:8px"/>
				<?php else : ?>
					<span class="dashicons dashicons-layout" style="font-size:28px;width:28px;height:28px"></span>
				<?php endif; ?>
				<?php esc_html_e( 'Auranet Page and Theme Builder', 'auranet-page-theme-builder' ); ?>
			</h1>
			<p style="color:#646970;font-size:14px;max-width:56ch">
				<?php esc_html_e( 'Global settings. All features are free and fully functional.', 'auranet-page-theme-builder' ); ?>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=aura-builder-policy' ) ); ?>"><?php esc_html_e( 'Usage policy', 'auranet-page-theme-builder' ); ?></a>
			</p>

			<?php if ( $enabled ) : ?>
				<div class="notice notice-warning inline" style="margin:16px 0">
					<p>
						<strong><?php esc_html_e( 'Modo construção ativo.', 'auranet-page-theme-builder' ); ?></strong>
						<?php esc_html_e( 'Visitantes não logados veem a página de “em construção”.', 'auranet-page-theme-builder' ); ?>
						<a href="<?php echo esc_url( $home ); ?>" target="_blank" rel="noopener"><?php esc_html_e( 'Abrir site', 'auranet-page-theme-builder' ); ?></a>
					</p>
				</div>
			<?php endif; ?>

			<form method="post" action="options.php" style="background:#fff;border:1px solid #c3c4c7;border-radius:8px;padding:24px 28px;margin-top:12px;box-shadow:0 1px 1px rgba(0,0,0,.04)">
				<?php settings_fields( 'aptb_settings' ); ?>

				<h2 style="margin-top:0;font-size:16px" id="ab-credit-style"><?php esc_html_e( 'Optional footer credit', 'auranet-page-theme-builder' ); ?></h2>
				<p style="color:#646970;margin-top:0">
					<?php esc_html_e( 'Optional. Off by default. You can show a free “Powered by Auranet Builder” link and style its colors. No feature is locked.', 'auranet-page-theme-builder' ); ?>
				</p>
				<table class="form-table" role="presentation">
					<tr>
						<th scope="row"><?php esc_html_e( 'Public footer', 'auranet-page-theme-builder' ); ?></th>
						<td>
							<label style="display:inline-flex;align-items:center;gap:10px;font-size:14px">
								<input type="checkbox" name="<?php echo esc_attr( BrandCredit::OPTION_OPT_IN ); ?>" value="1" <?php checked( $opt_in ); ?> />
								<span><?php esc_html_e( 'Show “Powered by Auranet Builder” in the footer', 'auranet-page-theme-builder' ); ?></span>
							</label>
						</td>
					</tr>
					<tr>
						<th scope="row"><label for="ab-credit-text-color"><?php esc_html_e( 'Text color', 'auranet-page-theme-builder' ); ?></label></th>
						<td>
							<input type="text" class="ab-color-field" id="ab-credit-text-color"
								name="<?php echo esc_attr( BrandCredit::OPTION_TEXT_COLOR ); ?>"
								value="<?php echo esc_attr( $credit_text ); ?>"
								data-default-color="<?php echo esc_attr( BrandCredit::DEFAULT_TEXT_COLOR ); ?>"/>
						</td>
					</tr>
					<tr>
						<th scope="row"><label for="ab-credit-bg-color"><?php esc_html_e( 'Background color', 'auranet-page-theme-builder' ); ?></label></th>
						<td>
							<input type="text" class="ab-color-field" id="ab-credit-bg-color"
								name="<?php echo esc_attr( BrandCredit::OPTION_BG_COLOR ); ?>"
								value="<?php echo esc_attr( $credit_bg ); ?>"
								data-default-color="<?php echo esc_attr( BrandCredit::DEFAULT_BG_COLOR ); ?>"/>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Preview', 'auranet-page-theme-builder' ); ?></th>
						<td>
							<div id="ab-credit-preview" style="display:block;text-align:center;padding:12px 16px;font-size:12px;font-weight:600;border:1px solid #dcdcde;border-radius:6px;background:<?php echo esc_attr( $credit_bg ); ?>;color:<?php echo esc_attr( $credit_text ); ?>;">
								<a href="<?php echo esc_url( License::PLUGIN_URL ); ?>" target="_blank" rel="noopener noreferrer" style="color:<?php echo esc_attr( $credit_text ); ?>;text-decoration:none;font-weight:600;">
									<?php echo esc_html( __( 'Powered by Auranet Builder', 'auranet-page-theme-builder' ) ); ?>
								</a>
							</div>
							<p class="description">
								<a href="<?php echo esc_url( License::PLUGIN_URL ); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Support Auranet (optional)', 'auranet-page-theme-builder' ); ?></a>
							</p>
						</td>
					</tr>
				</table>
				<hr style="border:none;border-top:1px solid #dcdcde;margin:20px 0"/>

				<h2 style="margin-top:0;font-size:16px"><?php esc_html_e( 'Página “Estamos em construção”', 'auranet-page-theme-builder' ); ?></h2>
				<p style="color:#646970;margin-top:0">
					<?php esc_html_e( 'Quando ativada, todo o site exibe essa página para quem não está logado. Equipe logada continua editando normalmente.', 'auranet-page-theme-builder' ); ?>
				</p>

				<table class="form-table" role="presentation">
					<tr>
						<th scope="row"><?php esc_html_e( 'Status', 'auranet-page-theme-builder' ); ?></th>
						<td>
							<label style="display:inline-flex;align-items:center;gap:10px;font-size:14px">
								<input type="checkbox" name="<?php echo esc_attr( ConstructionMode::OPTION ); ?>" value="1" <?php checked( $enabled ); ?> />
								<span><strong><?php esc_html_e( 'Ativar página de construção', 'auranet-page-theme-builder' ); ?></strong></span>
							</label>
						</td>
					</tr>
					<tr>
						<th scope="row"><label for="ab-cc-title"><?php esc_html_e( 'Título', 'auranet-page-theme-builder' ); ?></label></th>
						<td>
							<input type="text" class="regular-text" id="ab-cc-title"
								name="<?php echo esc_attr( ConstructionMode::OPTION_TITLE ); ?>"
								value="<?php echo esc_attr( $title ); ?>"
								placeholder="Estamos em construção"/>
						</td>
					</tr>
					<tr>
						<th scope="row"><label for="ab-cc-msg"><?php esc_html_e( 'Mensagem', 'auranet-page-theme-builder' ); ?></label></th>
						<td>
							<textarea class="large-text" rows="4" id="ab-cc-msg"
								name="<?php echo esc_attr( ConstructionMode::OPTION_MESSAGE ); ?>"
								placeholder="Estamos desenvolvendo um novo design…"><?php echo esc_textarea( $message ); ?></textarea>
						</td>
					</tr>
				</table>

				<?php submit_button( __( 'Salvar configurações', 'auranet-page-theme-builder' ) ); ?>
			</form>

			<div style="margin-top:24px;padding:18px 20px;background:#f6f7f7;border-radius:8px;border:1px solid #dcdcde">
				<h3 style="margin:0 0 8px;font-size:14px"><?php esc_html_e( 'Como funciona o gratuito', 'auranet-page-theme-builder' ); ?></h3>
				<ul style="margin:0;padding-left:1.2em;color:#50575e;line-height:1.6">
					<li><?php esc_html_e( 'Todas as funções do editor e Theme Builder: grátis.', 'auranet-page-theme-builder' ); ?></li>
					<li><?php esc_html_e( 'Crédito “Powered by Auranet Builder” no rodapé: obrigatório no plano gratuito.', 'auranet-page-theme-builder' ); ?></li>
					<li><?php echo esc_html( sprintf( __( 'Remover o crédito: R$ %s por domínio.', 'auranet-page-theme-builder' ), License::PRICE_BRL ) ); ?></li>
					<li><a href="<?php echo esc_url( admin_url( 'admin.php?page=aura-builder-policy' ) ); ?>"><?php esc_html_e( 'Política de uso completa', 'auranet-page-theme-builder' ); ?></a></li>
				</ul>
			</div>

			<div style="margin-top:20px;padding:18px 20px;background:#fff;border-radius:8px;border:1px solid #c3c4c7">
				<h3 style="margin:0 0 8px;font-size:14px"><?php esc_html_e( 'Atalhos', 'auranet-page-theme-builder' ); ?></h3>
				<p style="margin:0;line-height:1.7">
					<a class="button button-primary" href="<?php echo esc_url( admin_url( 'admin.php?page=aura-builder-pages' ) ); ?>"><?php esc_html_e( 'Páginas do Builder', 'auranet-page-theme-builder' ); ?></a>
					<span style="display:inline-block;width:8px"></span>
					<a class="button" href="<?php echo esc_url( admin_url( 'edit.php?post_type=page' ) ); ?>"><?php esc_html_e( 'Páginas WP', 'auranet-page-theme-builder' ); ?></a>
				</p>
			</div>
		</div>
		<?php
	}

	/**
	 * Soft reminder when free + credit on (admin only).
	 */
	public function license_notice(): void {
		if ( ! current_user_can( 'manage_options' ) || License::is_licensed() ) {
			return;
		}
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$page = isset( $_GET['page'] ) ? (string) $_GET['page'] : '';
		if ( $page === 'aura-builder-settings' || $page === 'aura-builder-policy' ) {
			return;
		}
		if ( strpos( $page, 'auranet-page-theme-builder' ) !== 0 ) {
			return;
		}
		echo '<div class="notice notice-info is-dismissible"><p>';
		echo '<strong>Aura Builder:</strong> ';
		echo esc_html__( 'Uso gratuito com o crédito “Powered by Auranet Builder” no rodapé.', 'auranet-page-theme-builder' );
		echo ' ';
		echo '<a href="' . esc_url( admin_url( 'admin.php?page=aura-builder-settings#ab-license' ) ) . '">';
		echo esc_html( sprintf( __( 'Remover por R$ %s', 'auranet-page-theme-builder' ), License::PRICE_BRL ) );
		echo '</a>';
		echo ' · <a href="' . esc_url( admin_url( 'admin.php?page=aura-builder-policy' ) ) . '">';
		echo esc_html__( 'Política de uso', 'auranet-page-theme-builder' );
		echo '</a></p></div>';
	}

	/**
	 * @param \WP_Admin_Bar $bar Bar.
	 */
	public function admin_bar( $bar ): void {
		if ( ! is_admin_bar_showing() || ! current_user_can( 'manage_options' ) ) {
			return;
		}
		if ( ! ConstructionMode::is_enabled() ) {
			return;
		}
		$bar->add_node(
			array(
				'id'    => 'aura-builder-construction',
				'title' => '⚠ Construção ON',
				'href'  => admin_url( 'admin.php?page=aura-builder-settings' ),
				'meta'  => array(
					'title' => 'Visitantes veem a página de construção. Clique para gerenciar.',
				),
			)
		);
	}

	public function notice(): void {
		if ( ! ConstructionMode::is_enabled() || ! current_user_can( 'manage_options' ) ) {
			return;
		}
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$page = isset( $_GET['page'] ) ? (string) $_GET['page'] : '';
		if ( $page === 'aura-builder-settings' ) {
			return;
		}
		echo '<div class="notice notice-warning is-dismissible"><p>';
		echo '<strong>Aura Builder:</strong> modo construção está <strong>ativo</strong>. ';
		echo 'Visitantes não logados não veem o site. ';
		echo '<a href="' . esc_url( admin_url( 'admin.php?page=aura-builder-settings' ) ) . '">Gerenciar</a>';
		echo '</p></div>';
	}
}
