<?php
/**
 * Admin menu registration.
 *
 * @package GoValid_QR
 */

defined( 'ABSPATH' ) || exit;

class GoValid_Admin {

	/**
	 * Register admin hooks.
	 */
	public function register(): void {
		add_action( 'admin_menu', array( $this, 'add_menu_pages' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
		add_filter( 'plugin_action_links_' . GOVALID_QR_PLUGIN_BASENAME, array( $this, 'add_settings_link' ) );
	}

	/**
	 * Add admin menu pages.
	 */
	public function add_menu_pages(): void {
		add_menu_page(
			__( 'GoValid QR', 'govalid-qr' ),
			__( 'GoValid QR', 'govalid-qr' ),
			'edit_posts',
			'govalid-qr-generator',
			array( $this, 'render_generator_page' ),
			GOVALID_QR_PLUGIN_URL . 'assets/images/govalid-icon.svg?v2=' . GOVALID_QR_VERSION,
			80
		);

		// 1. QR Generator (top item — matches parent slug).
		add_submenu_page(
			'govalid-qr-generator',
			__( 'QR Generator', 'govalid-qr' ),
			__( 'QR Generator', 'govalid-qr' ),
			'edit_posts',
			'govalid-qr-generator',
			array( $this, 'render_generator_page' )
		);

		// 2. Humanize Links.
		add_submenu_page(
			'govalid-qr-generator',
			__( 'Humanize Links', 'govalid-qr' ),
			__( 'Humanize Links', 'govalid-qr' ),
			'edit_posts',
			'govalid-qr-links',
			array( $this, 'render_links_page' )
		);

		// 3. Forms.
		add_submenu_page(
			'govalid-qr-generator',
			__( 'Forms', 'govalid-qr' ),
			__( 'Forms', 'govalid-qr' ),
			'edit_posts',
			'govalid-qr-forms',
			array( $this, 'render_forms_page' )
		);

		// 4. List QR.
		add_submenu_page(
			'govalid-qr-generator',
			__( 'List QR', 'govalid-qr' ),
			__( 'List QR', 'govalid-qr' ),
			'edit_posts',
			'govalid-qr-list',
			array( $this, 'render_list_page' )
		);

		// 5. Analytics.
		add_submenu_page(
			'govalid-qr-generator',
			__( 'Analytics', 'govalid-qr' ),
			__( 'Analytics', 'govalid-qr' ),
			'edit_posts',
			'govalid-qr-analytics',
			array( $this, 'render_analytics_page' )
		);

		// 6. Settings (last).
		add_submenu_page(
			'govalid-qr-generator',
			__( 'Settings', 'govalid-qr' ),
			__( 'Settings', 'govalid-qr' ),
			'manage_options',
			'govalid-qr',
			array( $this, 'render_settings_page' )
		);

		// Hidden page: Form Builder.
		add_submenu_page(
			null,
			__( 'Form Builder', 'govalid-qr' ),
			'',
			'edit_posts',
			'govalid-qr-form-builder',
			array( $this, 'render_form_builder_page' )
		);

		// Hidden page: Form Submissions.
		add_submenu_page(
			null,
			__( 'Form Submissions', 'govalid-qr' ),
			'',
			'edit_posts',
			'govalid-qr-form-submissions',
			array( $this, 'render_form_submissions_page' )
		);

		// Hidden page for OAuth callback.
		add_submenu_page(
			null,
			__( 'OAuth Callback', 'govalid-qr' ),
			'',
			'manage_options',
			'govalid-qr-oauth-callback',
			array( $this, 'render_oauth_callback' )
		);
	}

	/**
	 * Render settings page.
	 */
	public function render_settings_page(): void {
		include GOVALID_QR_PLUGIN_DIR . 'admin/partials/settings-page.php';
	}

	/**
	 * Render generator page.
	 */
	public function render_generator_page(): void {
		include GOVALID_QR_PLUGIN_DIR . 'admin/partials/generator-page.php';
	}

	/**
	 * Render List QR page.
	 */
	public function render_list_page(): void {
		include GOVALID_QR_PLUGIN_DIR . 'admin/partials/list-page.php';
	}

	/**
	 * Render Analytics page.
	 */
	public function render_analytics_page(): void {
		include GOVALID_QR_PLUGIN_DIR . 'admin/partials/analytics-page.php';
	}

	/**
	 * Render Humanize Links page.
	 */
	public function render_links_page(): void {
		include GOVALID_QR_PLUGIN_DIR . 'admin/partials/links-page.php';
	}

	/**
	 * Render Forms list page.
	 */
	public function render_forms_page(): void {
		// Ensure tables exist (handles upgrades without re-activation).
		GoValid_QR_Activator::maybe_create_tables();
		include GOVALID_QR_PLUGIN_DIR . 'admin/partials/forms-page.php';
	}

	/**
	 * Render Form Builder page.
	 */
	public function render_form_builder_page(): void {
		include GOVALID_QR_PLUGIN_DIR . 'admin/partials/form-builder-page.php';
	}

	/**
	 * Render Form Submissions page.
	 */
	public function render_form_submissions_page(): void {
		include GOVALID_QR_PLUGIN_DIR . 'admin/partials/form-submissions-page.php';
	}

	/**
	 * Handle OAuth callback rendering.
	 */
	public function render_oauth_callback(): void {
		$settings = new GoValid_Admin_Settings();
		$settings->handle_oauth_callback();
	}

	/**
	 * Enqueue admin assets.
	 *
	 * @param string $hook Current admin page hook.
	 */
	public function enqueue_assets( string $hook ): void {
		// Only load on our plugin pages.
		if ( strpos( $hook, 'govalid-qr' ) === false ) {
			return;
		}

		wp_enqueue_style(
			'govalid-admin',
			GOVALID_QR_PLUGIN_URL . 'admin/css/govalid-admin.css',
			array(),
			GOVALID_QR_VERSION
		);

		wp_enqueue_script(
			'govalid-admin',
			GOVALID_QR_PLUGIN_URL . 'admin/js/govalid-admin.js',
			array( 'jquery' ),
			GOVALID_QR_VERSION,
			true
		);

		wp_localize_script( 'govalid-admin', 'govalidQR', array(
			'ajaxUrl'      => admin_url( 'admin-ajax.php' ),
			'restUrl'      => rest_url( 'govalid-qr/v1/' ),
			'baseUrl'      => GoValid_QR::get_base_url(),
			'nonce'        => wp_create_nonce( 'wp_rest' ),
			'isConnected'  => GoValid_QR::is_connected(),
			'settingsUrl'  => admin_url( 'admin.php?page=govalid-qr' ),
			'promoAds'     => $this->get_promo_ads(),
			'i18n'    => array(
				'confirm_disconnect'  => __( 'Are you sure you want to disconnect from GoValid?', 'govalid-qr' ),
				'generating'          => __( 'Generating QR code...', 'govalid-qr' ),
				'error'               => __( 'An error occurred. Please try again.', 'govalid-qr' ),
				'copied'              => __( 'Copied to clipboard!', 'govalid-qr' ),
				'smart_qr_desc'       => __( 'Compact QR code with 96-bit security. Perfect for tiny labels and product tags. Smallest QR code size.', 'govalid-qr' ),
				'secure_qr_desc'      => __( '256-bit encryption protects your data from unauthorized changes and tampering. Balanced QR code size.', 'govalid-qr' ),
				'enterprise_qr_desc'  => __( '256-bit encryption with digital signatures and non-repudiation guarantee. Tamper-proof verification with legally binding proof of origin. Large QR code size.', 'govalid-qr' ),
				'suggesting'          => __( 'Generating suggestions...', 'govalid-qr' ),
				'creating_link'       => __( 'Creating link...', 'govalid-qr' ),
				'checking_slug'       => __( 'Checking...', 'govalid-qr' ),
				'slug_available'      => __( 'Available!', 'govalid-qr' ),
				'slug_taken'          => __( 'Already taken.', 'govalid-qr' ),
				'slug_reserved'       => __( 'Reserved.', 'govalid-qr' ),
				'confirm_delete_link' => __( 'Are you sure you want to delete this link?', 'govalid-qr' ),
				'link_deleted'        => __( 'Link deleted.', 'govalid-qr' ),
				'link_created'        => __( 'Link created!', 'govalid-qr' ),
				'no_links'            => __( 'No humanize links yet. Create one above!', 'govalid-qr' ),
				'loading_links'       => __( 'Loading links...', 'govalid-qr' ),
				'active'              => __( 'Active', 'govalid-qr' ),
				'inactive'            => __( 'Inactive', 'govalid-qr' ),
				'select_suggestion'   => __( 'Select a suggestion below, edit the slug if needed, then create.', 'govalid-qr' ),
				'pin_enter_6'         => __( 'Please enter all 6 digits.', 'govalid-qr' ),
				'pin_invalid'         => __( 'Invalid PIN.', 'govalid-qr' ),
				'pin_required'        => __( 'Please verify your signing PIN first.', 'govalid-qr' ),
				'verify_pin'          => __( 'Verify PIN', 'govalid-qr' ),
				'verifying'           => __( 'Verifying...', 'govalid-qr' ),
				'loading_qr'          => __( 'Loading QR codes...', 'govalid-qr' ),
				'no_qr'               => __( 'No QR codes generated from WordPress yet.', 'govalid-qr' ),
				'copy'                => __( 'Copy', 'govalid-qr' ),
				'verify'              => __( 'Verify', 'govalid-qr' ),
				'scans_label'         => __( 'scans', 'govalid-qr' ),
				'view_detail'         => __( 'View', 'govalid-qr' ),
				'delete'              => __( 'Delete', 'govalid-qr' ),
				'confirm_delete_qr'   => __( 'Are you sure you want to delete this QR code?', 'govalid-qr' ),
				'qr_deleted'          => __( 'QR code deleted.', 'govalid-qr' ),
				'confirm_bulk_delete_qr' => __( 'Delete {count} selected QR code(s)?', 'govalid-qr' ),
				'bulk_deleted'        => __( 'Selected QR codes deleted.', 'govalid-qr' ),
				'delete_selected'     => __( 'Delete Selected', 'govalid-qr' ),
				'deleting'            => __( 'Deleting...', 'govalid-qr' ),
				'download'            => __( 'Download', 'govalid-qr' ),
				'export_excel'        => __( 'Export Excel', 'govalid-qr' ),
				'exporting'           => __( 'Exporting...', 'govalid-qr' ),
			),
			'i18nLabel' => array(
				'label_layout'       => __( 'Label Layout', 'govalid-qr' ),
				'export_pdf'         => __( 'PDF', 'govalid-qr' ),
				'export_png'         => __( 'PNG', 'govalid-qr' ),
				'export_jpg'         => __( 'JPG', 'govalid-qr' ),
				'print'              => __( 'Print', 'govalid-qr' ),
				'close'              => __( 'Close', 'govalid-qr' ),
				'selected_qr_codes'  => __( 'Selected QR Codes', 'govalid-qr' ),
				'add_more'           => __( 'Add More', 'govalid-qr' ),
				'paper_settings'     => __( 'Paper Settings', 'govalid-qr' ),
				'label_settings'     => __( 'Label Settings', 'govalid-qr' ),
				'frame_settings'     => __( 'Frame Settings', 'govalid-qr' ),
				'paper_size'         => __( 'Paper Size', 'govalid-qr' ),
				'orientation'        => __( 'Orientation', 'govalid-qr' ),
				'portrait'           => __( 'Portrait', 'govalid-qr' ),
				'landscape'          => __( 'Landscape', 'govalid-qr' ),
				'columns'            => __( 'Columns', 'govalid-qr' ),
				'rows'               => __( 'Rows', 'govalid-qr' ),
				'margins'            => __( 'Margins (mm)', 'govalid-qr' ),
				'spacing'            => __( 'Spacing (mm)', 'govalid-qr' ),
				'qr_size'            => __( 'QR Size (mm)', 'govalid-qr' ),
				'qr_position'        => __( 'QR Position', 'govalid-qr' ),
				'show_label'         => __( 'Show Label', 'govalid-qr' ),
				'label_content'      => __( 'Label Content', 'govalid-qr' ),
				'name'               => __( 'Name', 'govalid-qr' ),
				'id'                 => __( 'ID', 'govalid-qr' ),
				'both'               => __( 'Both', 'govalid-qr' ),
				'position'           => __( 'Position', 'govalid-qr' ),
				'font'               => __( 'Font', 'govalid-qr' ),
				'size'               => __( 'Size', 'govalid-qr' ),
				'color'              => __( 'Color', 'govalid-qr' ),
				'background'         => __( 'Background', 'govalid-qr' ),
				'frame_style'        => __( 'Frame Style', 'govalid-qr' ),
				'frame_color'        => __( 'Frame Color', 'govalid-qr' ),
				'fill_color'         => __( 'Fill Color', 'govalid-qr' ),
				'stroke_width'       => __( 'Stroke Width', 'govalid-qr' ),
				'none'               => __( 'None', 'govalid-qr' ),
				'basic'              => __( 'Basic', 'govalid-qr' ),
				'rounded'            => __( 'Rounded', 'govalid-qr' ),
				'double'             => __( 'Double', 'govalid-qr' ),
				'dashed'             => __( 'Dashed', 'govalid-qr' ),
				'dotted'             => __( 'Dotted', 'govalid-qr' ),
				'shadow'             => __( 'Shadow', 'govalid-qr' ),
				'zoom_in'            => __( 'Zoom In', 'govalid-qr' ),
				'zoom_out'           => __( 'Zoom Out', 'govalid-qr' ),
				'reset_zoom'         => __( 'Reset Zoom', 'govalid-qr' ),
				'page_of'            => __( 'Page {current} of {total}', 'govalid-qr' ),
				'exporting'          => __( 'Exporting...', 'govalid-qr' ),
				'preparing_print'    => __( 'Preparing print...', 'govalid-qr' ),
				'add_qr_codes'       => __( 'Add QR Codes', 'govalid-qr' ),
				'search_qr'          => __( 'Search QR codes...', 'govalid-qr' ),
				'add_selected'       => __( 'Add Selected', 'govalid-qr' ),
				'cancel'             => __( 'Cancel', 'govalid-qr' ),
				'no_qr_available'    => __( 'No QR codes available.', 'govalid-qr' ),
				'top'                => __( 'Top', 'govalid-qr' ),
				'bottom'             => __( 'Bottom', 'govalid-qr' ),
				'left'               => __( 'Left', 'govalid-qr' ),
				'right'              => __( 'Right', 'govalid-qr' ),
				'center'             => __( 'Center', 'govalid-qr' ),
				'custom'             => __( 'Custom', 'govalid-qr' ),
				'width_mm'           => __( 'Width (mm)', 'govalid-qr' ),
				'height_mm'          => __( 'Height (mm)', 'govalid-qr' ),
				'layout_presets'     => __( 'Layout Presets', 'govalid-qr' ),
				'select_preset'      => __( '— Select Preset —', 'govalid-qr' ),
				'save_current'       => __( 'Save Current', 'govalid-qr' ),
				'delete_preset'      => __( 'Delete', 'govalid-qr' ),
				'last_used'          => __( 'Last Used', 'govalid-qr' ),
				'default_settings'   => __( 'Default Settings', 'govalid-qr' ),
				'preset_name_prompt' => __( 'Enter a name for this preset:', 'govalid-qr' ),
				'preset_saved'       => __( 'Preset saved!', 'govalid-qr' ),
				'preset_deleted'     => __( 'Preset deleted.', 'govalid-qr' ),
				'confirm_delete'     => __( 'Delete this preset?', 'govalid-qr' ),
				'templates'          => __( 'Templates', 'govalid-qr' ),
				'saved_presets'      => __( 'My Presets', 'govalid-qr' ),
			),
		) );

		// Generator page — load Leaflet for timeline map.
		if ( strpos( $hook, 'govalid-qr-generator' ) !== false ) {
			wp_enqueue_style(
				'leaflet-css',
				GOVALID_QR_PLUGIN_URL . 'admin/vendor/leaflet.css',
				array(),
				'1.9.4'
			);

			wp_enqueue_script(
				'leaflet-js',
				GOVALID_QR_PLUGIN_URL . 'admin/vendor/leaflet.js',
				array(),
				'1.9.4',
				true
			);
		}

		// Links page — load QR code styling for live QR designer.
		if ( strpos( $hook, 'govalid-qr-links' ) !== false ) {
			wp_enqueue_media();

			wp_enqueue_script(
				'qr-code-styling',
				GOVALID_QR_PLUGIN_URL . 'admin/vendor/qr-code-styling.min.js',
				array(),
				'1.6.0',
				true
			);
		}

		// List page — load label layout assets.
		if ( strpos( $hook, 'govalid-qr-list' ) !== false ) {
			wp_enqueue_script(
				'html2canvas',
				GOVALID_QR_PLUGIN_URL . 'admin/vendor/html2canvas.min.js',
				array(),
				'1.4.1',
				true
			);

			wp_enqueue_script(
				'jspdf',
				GOVALID_QR_PLUGIN_URL . 'admin/vendor/jspdf.umd.min.js',
				array(),
				'2.5.2',
				true
			);

			wp_enqueue_script(
				'sortablejs',
				GOVALID_QR_PLUGIN_URL . 'admin/vendor/sortable.min.js',
				array(),
				'1.15.6',
				true
			);

			wp_enqueue_script(
				'sheetjs',
				GOVALID_QR_PLUGIN_URL . 'admin/vendor/xlsx.mini.min.js',
				array(),
				'0.20.3',
				true
			);

			wp_enqueue_style(
				'govalid-label-layout',
				GOVALID_QR_PLUGIN_URL . 'admin/css/govalid-label-layout.css',
				array( 'govalid-admin' ),
				GOVALID_QR_VERSION
			);

			wp_enqueue_script(
				'govalid-label-layout',
				GOVALID_QR_PLUGIN_URL . 'admin/js/govalid-label-layout.js',
				array( 'jquery', 'html2canvas', 'jspdf', 'sortablejs', 'govalid-admin' ),
				GOVALID_QR_VERSION,
				true
			);
		}

		// Forms pages — load form builder / forms admin assets.
		if ( strpos( $hook, 'govalid-qr-form-builder' ) !== false ) {
			wp_enqueue_media();

			wp_enqueue_script(
				'sortablejs',
				GOVALID_QR_PLUGIN_URL . 'admin/vendor/sortable.min.js',
				array(),
				'1.15.6',
				true
			);

			wp_enqueue_style(
				'govalid-form-builder',
				GOVALID_QR_PLUGIN_URL . 'admin/css/govalid-form-builder.css',
				array( 'govalid-admin' ),
				GOVALID_QR_VERSION
			);

			wp_enqueue_script(
				'govalid-form-builder',
				GOVALID_QR_PLUGIN_URL . 'admin/js/govalid-form-builder.js',
				array( 'jquery', 'sortablejs', 'govalid-admin' ),
				GOVALID_QR_VERSION,
				true
			);
		}

		if ( strpos( $hook, 'govalid-qr-forms' ) !== false || strpos( $hook, 'govalid-qr-form-submissions' ) !== false ) {
			wp_enqueue_script(
				'govalid-forms-admin',
				GOVALID_QR_PLUGIN_URL . 'admin/js/govalid-forms-admin.js',
				array( 'jquery', 'govalid-admin' ),
				GOVALID_QR_VERSION,
				true
			);
		}

		// Submissions page — load Chart.js for statistics.
		if ( strpos( $hook, 'govalid-qr-form-submissions' ) !== false ) {
			wp_enqueue_script(
				'chart-js',
				GOVALID_QR_PLUGIN_URL . 'admin/vendor/chart.umd.min.js',
				array(),
				'4.4.4',
				true
			);
		}

		// Analytics page — load Leaflet, Chart.js, and analytics script.
		if ( strpos( $hook, 'govalid-qr-analytics' ) !== false ) {
			wp_enqueue_style(
				'leaflet-css',
				GOVALID_QR_PLUGIN_URL . 'admin/vendor/leaflet.css',
				array(),
				'1.9.4'
			);

			wp_enqueue_script(
				'leaflet-js',
				GOVALID_QR_PLUGIN_URL . 'admin/vendor/leaflet.js',
				array(),
				'1.9.4',
				true
			);

			wp_enqueue_script(
				'chart-js',
				GOVALID_QR_PLUGIN_URL . 'admin/vendor/chart.umd.min.js',
				array(),
				'4.4.4',
				true
			);

			wp_enqueue_script(
				'leaflet-markercluster',
				GOVALID_QR_PLUGIN_URL . 'admin/vendor/leaflet.markercluster.js',
				array( 'leaflet-js' ),
				'1.4.1',
				true
			);

			wp_enqueue_script(
				'govalid-analytics',
				GOVALID_QR_PLUGIN_URL . 'admin/js/govalid-analytics.js',
				array( 'jquery', 'leaflet-js', 'leaflet-markercluster', 'chart-js', 'govalid-admin' ),
				GOVALID_QR_VERSION,
				true
			);
		}
	}

	/**
	 * Add settings link to plugin list.
	 *
	 * @param array $links Existing links.
	 * @return array
	 */
	public function add_settings_link( array $links ): array {
		$settings_link = sprintf(
			'<a href="%s">%s</a>',
			esc_url( admin_url( 'admin.php?page=govalid-qr' ) ),
			esc_html__( 'Settings', 'govalid-qr' )
		);
		array_unshift( $links, $settings_link );
		return $links;
	}

	/**
	 * Fetch promotional ads from GoValid API (cached for 30 min).
	 *
	 * @return array
	 */
	private function get_promo_ads(): array {
		$cache_key = 'govalid_promo_ads';
		$cached    = get_transient( $cache_key );

		if ( false !== $cached ) {
			return $cached;
		}

		$base_url = GoValid_QR::get_base_url();
		$url      = $base_url . '/api/v1/plugin/ads/?slot=wp_plugin_sidebar&limit=5';

		$response = wp_remote_get( $url, array(
			'timeout'    => 5,
			'user-agent' => 'GoValid-QR-WordPress/' . GOVALID_QR_VERSION,
			'headers'    => array( 'Accept' => 'application/json' ),
		) );

		if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
			// Cache empty result for 5 min so we don't hammer the API on errors.
			set_transient( $cache_key, array(), 5 * MINUTE_IN_SECONDS );
			return array();
		}

		$body = json_decode( wp_remote_retrieve_body( $response ), true );
		$ads  = isset( $body['ads'] ) && is_array( $body['ads'] ) ? $body['ads'] : array();

		set_transient( $cache_key, $ads, 30 * MINUTE_IN_SECONDS );

		return $ads;
	}
}
