<?php
/**
 * File Path: includes/admin/tabs/class-mbs-tab-general.php
 *
 * General Tab (Parent Orchestrator)
 *
 * Thin parent that coordinates the child panels for this tab.
 * All business logic lives in the child classes:
 *
 *   MBS_Tab_General_Save     — save_settings(), nonce/cap check, PRG redirect
 *   MBS_Tab_General_Currency — currency, timezone field group render
 *   MBS_Tab_General_Display  — ISBN, series, author, coming soon toggles render
 *
 * @package    My_Book_Showroom
 * @subpackage Includes/Admin/Tabs
 * @since      1.0.0
 */

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

class MBS_Tab_General {

	/** @var MBS_Tab_General_Save */
	private MBS_Tab_General_Save $saver;

	public function __construct() {
		$this->saver = new MBS_Tab_General_Save();

		add_action( 'admin_init', array( $this, 'save_settings' ) );
	}

	/**
	 * Handle General tab form saves submitted via admin_init.
	 */
	public function save_settings(): void {
		if ( ! isset( $_POST['mbs_general_nonce'] ) ) {
			return;
		}

		check_admin_referer( 'mbs_general_save', 'mbs_general_nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$this->saver->save();
	}

	/**
	 * Enqueue General tab assets when this tab is active.
	 *
	 * @param string $current_tab The active tab slug.
	 */
	public function enqueue( string $current_tab ): void {
		if ( 'general' !== $current_tab ) {
			return;
		}

		wp_enqueue_script(
			'mbs-admin-general-currency',
			plugins_url( 'assets/js/adminjs/admin-general-currency.js', MBS_DIR . 'bookshowroom.php' ),
			array( 'jquery' ),
			MBS_VERSION,
			true
		);

		wp_localize_script(
			'mbs-admin-general-currency',
			'MBS_GeneralCurrency',
			array(
				'wpTimezone' => MBS_Timezone_Helper::get_wp_iana_timezone(),
			)
		);

		// Auto-fill disclosure textarea with placeholder text when checkbox is first enabled.
		wp_add_inline_script(
			'mbs-admin-general-currency',
			'(function(){ \'use strict\'; document.addEventListener(\'DOMContentLoaded\',function(){ var cb=document.querySelector(\'[name="mbs_general_disclosure_enabled"]\'); var ta=document.getElementById(\'mbs_general_disclosure_text\'); if(!cb||!ta)return; cb.addEventListener(\'change\',function(){ if(this.checked&&ta.value.trim()===\'\') ta.value=ta.getAttribute(\'placeholder\')||\'\'; }); }); })();'
		);

		wp_enqueue_style(
			'mbs-admin-settings-general',
			plugins_url( 'assets/css/mbs-admin-settings-general.css', MBS_DIR . 'bookshowroom.php' ),
			array( 'mbs-admin-settings' ),
			MBS_VERSION
		);
	}

	/**
	 * Render the General Settings tab.
	 *
	 * Delegates to MBS_Tab_General_Render::render().
	 * Kept as a thin instance method so class-mbs-settings.php can call
	 * $tab->render() without modification (R-19 delegate pattern).
	 *
	 * @return void
	 */
	public function render(): void {
		MBS_Tab_General_Render::render();
	}
}
