<?php
/**
 * Plugin Name: Sidebar Maker
 * Plugin URI:  https://bowdenworks.com
 * Description: Create custom sidebars with shortcode support for seamless integration with themes like Kadence.
 * Version:     1.1.0
 * Author:      Bowden Works
 * Author URI:  https://bowdenworks.com
 * Text Domain: bw-sidebar-maker
 * License:     GPL-2.0+
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! class_exists( 'BW_Sidebar_Maker' ) ) {

	class BW_Sidebar_Maker {

		/**
		 * Option name to store sidebar data.
		 *
		 * @var string
		 */
		private $bw_option_name = 'bw_custom_sidebars';

		/**
		 * Constructor.
		 */
		public function __construct() {
			// Register sidebars on front end and admin.
			add_action( 'widgets_init', array( $this, 'bw_register_sidebars' ) );

			// Add admin menu.
			add_action( 'admin_menu', array( $this, 'bw_add_admin_menu' ) );

			// Handle form processing.
			add_action( 'admin_init', array( $this, 'bw_process_settings' ) );

			// Register Shortcode for Page Builders/Kadence Elements.
			add_shortcode( 'bw_sidebar', array( $this, 'bw_render_shortcode' ) );
		}

		/**
		 * Register the stored sidebars with WordPress.
		 * Using generic HTML5 wrappers for maximum theme compatibility.
		 */
		public function bw_register_sidebars() {
			$bw_sidebars = get_option( $this->bw_option_name, array() );

			if ( ! empty( $bw_sidebars ) && is_array( $bw_sidebars ) ) {
				foreach ( $bw_sidebars as $sidebar ) {
					register_sidebar( array(
						'name'          => esc_html( $sidebar['name'] ),
						'id'            => esc_attr( $sidebar['id'] ),
						'description'   => esc_html__( 'Custom sidebar created via Sidebar Maker.', 'bw-sidebar-maker' ),
						'before_widget' => '<div id="%1$s" class="widget %2$s bw-widget-container">',
						'after_widget'  => '</div>',
						'before_title'  => '<h2 class="widget-title bw-widget-title">',
						'after_title'   => '</h2>',
					) );
				}
			}
		}

		/**
		 * Shortcode Handler: [bw_sidebar slug="your-slug"]
		 */
		public function bw_render_shortcode( $atts ) {
			$atts = shortcode_atts(
				array(
					'slug' => '',
				),
				$atts,
				'bw_sidebar'
			);

			if ( empty( $atts['slug'] ) ) {
				return '';
			}

			if ( is_active_sidebar( $atts['slug'] ) ) {
				ob_start();
				echo '<div class="bw-sidebar-shortcode-wrapper">';
				dynamic_sidebar( $atts['slug'] );
				echo '</div>';
				return ob_get_clean();
			}

			return '';
		}

		/**
		 * Add the settings page under "Appearance".
		 */
		public function bw_add_admin_menu() {
			add_theme_page(
				__( 'Sidebar Maker', 'bw-sidebar-maker' ),
				__( 'Sidebar Maker', 'bw-sidebar-maker' ),
				'manage_options',
				'bw-sidebar-maker',
				array( $this, 'bw_render_admin_page' )
			);
		}

		/**
		 * Process Add/Delete actions.
		 */
		public function bw_process_settings() {
			if ( ! isset( $_POST['bw_action'] ) || ! current_user_can( 'manage_options' ) ) {
				return;
			}

			$bw_sidebars = get_option( $this->bw_option_name, array() );

			// Action: Add New Sidebar
			if ( 'bw_add_sidebar' === $_POST['bw_action'] ) {
				check_admin_referer( 'bw_add_sidebar_nonce', 'bw_nonce' );

				$bw_name = sanitize_text_field( $_POST['bw_sidebar_name'] );
				
				if ( ! empty( $_POST['bw_sidebar_slug'] ) ) {
					$bw_slug = sanitize_title( $_POST['bw_sidebar_slug'] );
				} else {
					$bw_slug = sanitize_title( $bw_name );
				}

				if ( empty( $bw_name ) || empty( $bw_slug ) ) {
					add_settings_error( 'bw_messages', 'bw_error', __( 'Sidebar Name and Slug are required.', 'bw-sidebar-maker' ), 'error' );
					return;
				}

				foreach ( $bw_sidebars as $sidebar ) {
					if ( $sidebar['id'] === $bw_slug ) {
						add_settings_error( 'bw_messages', 'bw_error', __( 'A sidebar with this Slug already exists.', 'bw-sidebar-maker' ), 'error' );
						return;
					}
				}

				$bw_sidebars[] = array(
					'name' => $bw_name,
					'id'   => $bw_slug,
				);

				update_option( $this->bw_option_name, $bw_sidebars );
				add_settings_error( 'bw_messages', 'bw_success', __( 'Sidebar created successfully.', 'bw-sidebar-maker' ), 'updated' );
			}

			// Action: Delete Sidebar
			if ( 'bw_delete_sidebar' === $_POST['bw_action'] ) {
				check_admin_referer( 'bw_delete_sidebar_nonce', 'bw_nonce' );

				$bw_target_id = sanitize_text_field( $_POST['bw_sidebar_id'] );

				foreach ( $bw_sidebars as $key => $sidebar ) {
					if ( $sidebar['id'] === $bw_target_id ) {
						unset( $bw_sidebars[ $key ] );
					}
				}

				update_option( $this->bw_option_name, array_values( $bw_sidebars ) );
				add_settings_error( 'bw_messages', 'bw_success', __( 'Sidebar deleted.', 'bw-sidebar-maker' ), 'updated' );
			}
		}

		/**
		 * Render the Admin Interface.
		 */
		public function bw_render_admin_page() {
			$bw_sidebars = get_option( $this->bw_option_name, array() );
			?>
			<div class="wrap">
				<h1><?php esc_html_e( 'Sidebar Maker', 'bw-sidebar-maker' ); ?></h1>
				
				<?php settings_errors( 'bw_messages' ); ?>

				<div style="display: flex; gap: 20px; flex-wrap: wrap;">
					
					<div style="flex: 1; min-width: 300px; background: #fff; padding: 20px; border: 1px solid #ccd0d4; box-shadow: 0 1px 1px rgba(0,0,0,.04);">
						<h2><?php esc_html_e( 'Add New Sidebar', 'bw-sidebar-maker' ); ?></h2>
						<form method="post" action="">
							<?php wp_nonce_field( 'bw_add_sidebar_nonce', 'bw_nonce' ); ?>
							<input type="hidden" name="bw_action" value="bw_add_sidebar">
							
							<p>
								<label for="bw_sidebar_name"><strong><?php esc_html_e( 'Sidebar Name', 'bw-sidebar-maker' ); ?></strong></label><br>
								<input type="text" name="bw_sidebar_name" id="bw_sidebar_name" class="regular-text" required placeholder="e.g. Header Promo">
							</p>
							
							<p>
								<label for="bw_sidebar_slug"><strong><?php esc_html_e( 'Sidebar Slug (ID)', 'bw-sidebar-maker' ); ?></strong></label><br>
								<input type="text" name="bw_sidebar_slug" id="bw_sidebar_slug" class="regular-text" placeholder="e.g. header-promo">
								<p class="description"><?php esc_html_e( 'Unique ID. Leave empty to auto-generate.', 'bw-sidebar-maker' ); ?></p>
							</p>

							<p>
								<input type="submit" class="button button-primary" value="<?php esc_attr_e( 'Create Sidebar', 'bw-sidebar-maker' ); ?>">
							</p>
						</form>
					</div>

					<div style="flex: 2; min-width: 300px;">
						<table class="wp-list-table widefat fixed striped">
							<thead>
								<tr>
									<th><?php esc_html_e( 'Name', 'bw-sidebar-maker' ); ?></th>
									<th><?php esc_html_e( 'Slug', 'bw-sidebar-maker' ); ?></th>
									<th><?php esc_html_e( 'Shortcode (For Kadence/Pages)', 'bw-sidebar-maker' ); ?></th>
									<th style="width: 80px;"><?php esc_html_e( 'Actions', 'bw-sidebar-maker' ); ?></th>
								</tr>
							</thead>
							<tbody>
								<?php if ( empty( $bw_sidebars ) ) : ?>
									<tr>
										<td colspan="4"><?php esc_html_e( 'No custom sidebars found.', 'bw-sidebar-maker' ); ?></td>
									</tr>
								<?php else : ?>
									<?php foreach ( $bw_sidebars as $sidebar ) : ?>
										<tr>
											<td><strong><?php echo esc_html( $sidebar['name'] ); ?></strong></td>
											<td><code><?php echo esc_html( $sidebar['id'] ); ?></code></td>
											<td>
												<code style="user-select: all; cursor: pointer;">[bw_sidebar slug="<?php echo esc_html( $sidebar['id'] ); ?>"]</code>
											</td>
											<td>
												<form method="post" action="" onsubmit="return confirm('<?php esc_attr_e( 'Delete this sidebar?', 'bw-sidebar-maker' ); ?>');">
													<?php wp_nonce_field( 'bw_delete_sidebar_nonce', 'bw_nonce' ); ?>
													<input type="hidden" name="bw_action" value="bw_delete_sidebar">
													<input type="hidden" name="bw_sidebar_id" value="<?php echo esc_attr( $sidebar['id'] ); ?>">
													<button type="submit" class="button button-link-delete" style="color: #a00;">
														<?php esc_html_e( 'Delete', 'bw-sidebar-maker' ); ?>
													</button>
												</form>
											</td>
										</tr>
									<?php endforeach; ?>
								<?php endif; ?>
							</tbody>
						</table>
					</div>

				</div>
			</div>
			<?php
		}
	}

	new BW_Sidebar_Maker();
}