<?php
/**
 * Base class for admin pages
 *
 * All admin pages extend this class. Provides common functionality:
 * - Menu registration
 * - Page rendering
 * - Form handling
 * - Error/success messaging
 *
 * @package BW_Schema
 * @since 3.0.0-babel
 */

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

abstract class BW_Schema_Page {

	/**
	 * Page slug (for URL, menu item)
	 *
	 * @var string
	 */
	protected $slug;

	/**
	 * Page title
	 *
	 * @var string
	 */
	protected $title;

	/**
	 * Page icon (dashicons class)
	 *
	 * @var string
	 */
	protected $icon = 'dashicons-admin-generic';

	/**
	 * Page capability required
	 *
	 * @var string
	 */
	protected $capability = 'manage_options';

	/**
	 * Parent menu slug (null for top-level)
	 *
	 * @var string|null
	 */
	protected $parent_slug = 'bw-schema';

	/**
	 * Messages to display (errors, success)
	 *
	 * @var array
	 */
	protected $messages = array();

	/**
	 * Constructor
	 */
	public function __construct() {
		$this->init();
	}

	/**
	 * Initialize the page
	 *
	 * Override in subclasses to set up properties.
	 *
	 * @return void
	 */
	protected function init() {
		// Override in subclass
	}

	/**
	 * Register the page in WordPress
	 *
	 * Called by BW_Schema_Admin to register this page.
	 *
	 * @return void
	 */
	public function register() {
		if ( empty( $this->slug ) ) {
			return;
		}

		if ( $this->parent_slug ) {
			// Submenu page
			add_submenu_page(
				$this->parent_slug,
				$this->title,
				$this->title,
				$this->capability,
				$this->slug,
				array( $this, 'render_page' )
			);
		} else {
			// Top-level page
			add_menu_page(
				$this->title,
				$this->title,
				$this->capability,
				$this->slug,
				array( $this, 'render_page' ),
				$this->icon
			);
		}
	}

	/**
	 * Render the page
	 *
	 * Main entry point called by WordPress.
	 * Handles form submission, then renders the page.
	 *
	 * @return void
	 */
	public function render_page() {
		// Check capability
		if ( ! current_user_can( $this->capability ) ) {
			wp_die( esc_html__( 'You do not have permission to access this page.', 'bw-schema' ) );
		}

		// Handle form submission
		if ( ! empty( $_POST ) ) {
			$this->handle_save();
		}

		// Render page wrapper
		echo '<div class="wrap bw-schema-page bw-schema-page-' . esc_attr( $this->slug ) . '">';

		// Page title
		echo '<h1>' . esc_html( $this->title ) . '</h1>';

		// Display messages
		$this->display_messages();

		// Render page content with error handling
		try {
			$this->render();
		} catch ( Throwable $e ) {
			// Log the error for debugging
			error_log( 'BW Schema Page Error (' . $this->slug . '): ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine() );
			error_log( 'Stack trace: ' . $e->getTraceAsString() );

			echo '<div class="notice notice-error"><p>';
			echo esc_html__( 'Unable to render page content. Some services may not be available.', 'bw-schema' );
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
				echo '<br><code>' . esc_html( $e->getMessage() . ' (' . $e->getFile() . ':' . $e->getLine() . ')' ) . '</code>';
			}
			echo '</p></div>';
		}

		echo '</div>';
	}

	/**
	 * Render page content
	 *
	 * Override in subclass to render the page.
	 *
	 * @return void
	 */
	abstract protected function render();

	/**
	 * Handle form submission
	 *
	 * Override in subclass to process form data.
	 * Call add_message() to queue messages.
	 *
	 * @return void
	 */
	protected function handle_save() {
		// Override in subclass
	}

	/**
	 * Add a message to display
	 *
	 * Messages are displayed at the top of the page.
	 *
	 * @param string $message Message text
	 * @param string $type Message type ('success', 'error', 'warning', 'info')
	 * @return void
	 */
	protected function add_message( $message, $type = 'success' ) {
		$this->messages[] = array(
			'text' => $message,
			'type' => $type,
		);
	}

	/**
	 * Add an error message
	 *
	 * @param string $message Error message
	 * @return void
	 */
	protected function add_error( $message ) {
		$this->add_message( $message, 'error' );
	}

	/**
	 * Display queued messages
	 *
	 * @return void
	 */
	private function display_messages() {
		if ( empty( $this->messages ) ) {
			return;
		}

		foreach ( $this->messages as $message ) {
			echo '<div class="notice notice-' . esc_attr( $message['type'] ) . '">';
			echo '<p>' . esc_html( $message['text'] ) . '</p>';
			echo '</div>';
		}
	}

	/**
	 * Render a section heading
	 *
	 * @param string $heading Heading text
	 * @return void
	 */
	protected function render_heading( $heading ) {
		echo '<h2>' . esc_html( $heading ) . '</h2>';
	}

	/**
	 * Render a description paragraph
	 *
	 * @param string $description Description text
	 * @return void
	 */
	protected function render_description( $description ) {
		echo '<p class="description">' . esc_html( $description ) . '</p>';
	}

	/**
	 * Render a card/box section
	 *
	 * @param string $title Card title
	 * @param string $content Card content (HTML)
	 * @param string $class Additional CSS classes
	 * @return void
	 */
	protected function render_card( $title, $content, $class = '' ) {
		echo '<div class="bw-schema-card ' . esc_attr( $class ) . '">';
		if ( $title ) {
			echo '<h3>' . esc_html( $title ) . '</h3>';
		}
		echo $content; // phpcs:ignore WordPress.Security.EscapeOutput
		echo '</div>';
	}

	/**
	 * Render a form with form builder
	 *
	 * @param string $form_name Form name/slug
	 * @param array  $fields Field definitions
	 * @param array  $data Current form data
	 * @return void
	 */
	protected function render_form( $form_name, $fields, $data = array() ) {
		$form = BW_Schema_Form_Builder::build_form( $form_name, $fields, $data );
		echo $form->render(); // phpcs:ignore WordPress.Security.EscapeOutput
	}

	/**
	 * Get current page slug
	 *
	 * @return string
	 */
	public function get_slug() {
		return $this->slug;
	}

	/**
	 * Get current page title
	 *
	 * @return string
	 */
	public function get_title() {
		return $this->title;
	}
}
