<?php
/**
 * Costudio_Admin_Menu — admin menu registration + page callbacks.
 *
 * Owns the top-level "Contentosapp Studio" menu, all submenus (Dashboard, Studio,
 * Settings, License, Setup Wizard, hidden Detail), the wizard redirect
 * guard, and the thin page-<slug> callbacks that include the matching
 * view file.
 *
 * Extracted from Costudio_Admin as part of Task 2 (PR 2 — Menu split).
 *
 * @package Contentosapp_Studio
 * @since   3.2.0
 */

defined( 'ABSPATH' ) || exit;

class Costudio_Admin_Menu {

	/** @var self|null */
	private static ?self $instance = null;

	private function __construct() {}

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

	/**
	 * Wire menu + wizard-guard hooks.
	 */
	public function register_hooks(): void {
		add_action( 'admin_menu', array( $this, 'register_menus' ) );
		add_action( 'admin_init', array( $this, 'maybe_redirect_to_wizard' ) );
	}

	/**
	 * Register standalone menus.
	 */
	public function register_menus(): void {
		$settings = costudio_settings();
		$api_key  = $settings ? $settings->get( 'ai_api_key' ) : '';
		$badge    = empty( $api_key ) ? ' <span class="update-plugins count-1"><span class="plugin-count">1</span></span>' : '';

		add_menu_page(
			__( 'Contentosapp Studio', 'contentosapp-studio' ) . $badge,
			__( 'Contentosapp Studio', 'contentosapp-studio' ),
			'manage_options',
			'costudio',
			array( $this, 'page_dashboard' ),
			'dashicons-layout',
			30
		);

		add_submenu_page(
			'costudio',
			__( 'Dashboard', 'contentosapp-studio' ),
			__( 'Dashboard', 'contentosapp-studio' ),
			'manage_options',
			'costudio',
			array( $this, 'page_dashboard' )
		);

		add_submenu_page(
			'costudio',
			__( 'Studio', 'contentosapp-studio' ),
			__( 'Studio', 'contentosapp-studio' ),
			'manage_options',
			'costudio-studio',
			array( $this, 'page_studio' )
		);

		add_submenu_page(
			'costudio',
			__( 'Settings', 'contentosapp-studio' ),
			__( 'Settings', 'contentosapp-studio' ),
			'manage_options',
			'costudio-settings',
			array( $this, 'page_settings_standalone' )
		);

		add_submenu_page(
			'costudio',
			__( 'License', 'contentosapp-studio' ),
			__( 'License', 'contentosapp-studio' ),
			'manage_options',
			'costudio-license',
			array( $this, 'page_license' )
		);

		// Setup Wizard — parent must stay registered (do NOT remove_submenu_page: WP denies admin.php?page= access).
		add_submenu_page(
			'costudio',
			__( 'Setup Wizard', 'contentosapp-studio' ),
			__( 'Setup Wizard', 'contentosapp-studio' ),
			'manage_options',
			'costudio-setup',
			array( $this, 'page_wizard' )
		);

		// Production detail — same; visibility hidden via CSS in enqueue_assets().
		add_submenu_page(
			'costudio',
			__( 'Production Detail', 'contentosapp-studio' ),
			__( 'Production Detail', 'contentosapp-studio' ),
			'manage_options',
			'costudio-detalhe',
			array( $this, 'page_detalhe' )
		);
	}

	/**
	 * Redirect to setup wizard if API key is missing and user is accessing Contentosapp Studio pages.
	 */
	public function maybe_redirect_to_wizard(): void {
		if ( ! is_admin() || ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
			return;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin routing parameter.
		$page = sanitize_key( wp_unslash( $_GET['page'] ?? '' ) );
		if ( 0 !== strpos( $page, 'costudio' ) ) {
			return;
		}

		// Exceptions: allow setup wizard, license, and settings page even without API key.
		if ( in_array( $page, array( 'costudio-setup', 'costudio-license', 'costudio-settings' ), true ) ) {
			return;
		}

		// Check if AI is configured: either a BYOK key or ContentOS Auto mode is enough.
		$settings = costudio_settings();
		$api_key  = $settings ? $settings->get( 'ai_api_key' ) : '';
		$ai_mode  = $settings ? $settings->get( 'ai_mode', '' ) : '';

		$is_configured = ! empty( $api_key ) || $ai_mode === 'contentos';

		if ( ! $is_configured ) {
			wp_safe_redirect( admin_url( 'admin.php?page=costudio-setup' ) );
			exit;
		}
	}

	// ── Page callbacks ────────────────────────────────────────────────────

	public function page_wizard(): void {
		include COSTUDIO_DIR . 'admin/views/page-wizard.php';
	}

	public function page_studio(): void {
		// Capability is already enforced by the menu registration; re-check here
		// so the request-derived navigation params are read once, in an
		// authorized place, rather than inside the included view templates.
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have permission to access this page.', 'contentosapp-studio' ) );
		}

		// Read-only navigation hints from the query string (no state change).
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only admin navigation params on a manage_options-gated screen; sanitized inline, never used to mutate state.
		$studio_active_tab = isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : '';
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only admin navigation param (preselects a planning row); absint-sanitized, never used to mutate state.
		$studio_plan_id = isset( $_GET['plan_id'] ) ? absint( wp_unslash( $_GET['plan_id'] ) ) : 0;

		include COSTUDIO_DIR . 'admin/views/page-studio.php';
	}

	public function page_license(): void {
		include COSTUDIO_DIR . 'admin/views/page-upgrade.php';
	}

	public function page_detalhe(): void {
		// Capability is already enforced by the menu registration; re-check here
		// so the request-derived navigation param is read once, in an
		// authorized place, rather than inside the included view template.
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have permission to access this page.', 'contentosapp-studio' ) );
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only admin navigation param; absint-sanitized, never used to mutate state.
		$production_id = isset( $_GET['id'] ) ? absint( wp_unslash( $_GET['id'] ) ) : 0;

		echo '<div class="wrap fos-standalone-wrap">';
		include COSTUDIO_DIR . 'admin/views/page-detalhe.php';
		echo '</div>';
	}

	/**
	 * Settings page — standalone (own menu entry with wrapper + header).
	 */
	public function page_settings_standalone(): void {
		echo '<div class="wrap fos-standalone-wrap">';

		$costudio_header_title    = __( 'Settings', 'contentosapp-studio' );
		$costudio_header_subtitle = __( 'Configure AI providers, sites, and the seven production agents', 'contentosapp-studio' );
		$costudio_header_icon     = '⚙️';
		include COSTUDIO_DIR . 'admin/partials/partial-page-header.php';

		include COSTUDIO_DIR . 'admin/views/page-settings.php';

		// 🎙️ Brand Voice Modal
		if ( class_exists( 'Costudio_Brand_Voice' ) ) {
			include COSTUDIO_DIR . 'admin/views/partials/modal-brand-voice.php';
		}

		echo '</div>';
	}

	public function page_dashboard(): void {
		include COSTUDIO_DIR . 'admin/views/page-dashboard.php';
	}
}
