<?php
/**
 * Block Registration
 *
 * Registers Gutenberg blocks.
 *
 * @package DonorCore\Frontend
 */

namespace DonorCore\Frontend;

defined( 'ABSPATH' ) || exit;

/**
 * Block Registration Class
 */
class Block_Registration {

	/**
	 * Initialize hooks.
	 */
	public function init() {
		// Add custom block category.
		add_filter( 'block_categories_all', array( $this, 'add_block_category' ), 10, 2 );
		
		// Register blocks immediately instead of hooking to init (we're already in init)
		$this->register_blocks();
	}

	/**
	 * Add DonorCore block category.
	 *
	 * @param array $categories Block categories.
	 * @param object $post Current post.
	 * @return array
	 */
	public function add_block_category( $categories, $post ) {
		// Insert DonorCore category at position 1 (2nd in list)
		$donorcore_category = array(
			'slug'  => 'donorcore-donations',
			'title' => __( 'DonorCore', 'donorcore-donations' ),
			'icon'  => 'heart',
		);
		
		// Insert at position 1 (after first category)
		array_splice( $categories, 1, 0, array( $donorcore_category ) );
		
		return $categories;
	}

	/**
	 * Register blocks.
	 */
	public function register_blocks() {
		// Register donation form block script
		wp_register_script(
			'donor-core-donation-form-block',
			DONOR_CORE_PLUGIN_URL . 'assets/js/donation-form-block.js',
			array( 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-i18n' ),
			DONOR_CORE_VERSION,
			true
		);
		wp_set_script_translations( 'donor-core-donation-form-block', 'donorcore-donations', DONOR_CORE_PLUGIN_DIR . 'languages' );

		// Register frontend interaction script
		wp_register_script(
			'donor-core-donation-form-frontend',
			DONOR_CORE_PLUGIN_URL . 'includes/js/donation-form.js',
			array(),
			DONOR_CORE_VERSION,
			true
		);

		// Register EDITOR-ONLY styles for donation form block (compiled by webpack)
		wp_register_style(
			'donor-core-donation-form-editor-style',
			DONOR_CORE_PLUGIN_URL . 'assets/css/donation-form-block.css',
			array(),
			DONOR_CORE_VERSION
		);

		// Register FRONTEND-ONLY styles for donation form block
		wp_register_style(
			'donor-core-donation-form-frontend-style',
			DONOR_CORE_PLUGIN_URL . 'includes/css/frontend-blocks.css',
			array(),
			DONOR_CORE_VERSION
		);
		
		// Localize WooCommerce currency settings and default suggested amounts for all blocks
		$global_suggested = get_option( 'donorcore_suggested_amounts', '50,100,250,500' );
		$default_suggested = array_map( 'floatval', array_filter( array_map( 'trim', explode( ',', $global_suggested ) ) ) );
		if ( empty( $default_suggested ) ) {
			$default_suggested = array( 50, 100, 250, 500 );
		}

		wp_localize_script(
			'donor-core-donation-form-block',
			'donorCoreSettings',
			array(
				'currency'                => get_woocommerce_currency(),
				'currencySymbol'          => get_woocommerce_currency_symbol(),
				'locale'                  => get_locale(),
				'defaultSuggestedAmounts' => array_values( $default_suggested ),
			)
		);

		// Register donation form block
		register_block_type( 'donor-core/donation-form', array(
			'editor_script'   => 'donor-core-donation-form-block',
			'editor_style'    => 'donor-core-donation-form-editor-style',
			'script'          => 'donor-core-donation-form-frontend',
			'style'           => 'donor-core-donation-form-frontend-style',
			'render_callback' => array( $this, 'render_donation_form' ),
			'category'        => 'donorcore-donations',
			'attributes'      => array(
				'campaignId' => array(
					'type'    => 'string',
					'default' => '',
				),
			),
		) );

		// Register progress bar block script
		wp_register_script(
			'donor-core-progress-bar-block',
			DONOR_CORE_PLUGIN_URL . 'assets/js/progress-bar-block.js',
			array( 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-i18n' ),
			DONOR_CORE_VERSION,
			true
		);
		wp_set_script_translations( 'donor-core-progress-bar-block', 'donorcore-donations', DONOR_CORE_PLUGIN_DIR . 'languages' );

		// Register EDITOR-ONLY styles for progress bar block (compiled by webpack)
		wp_register_style(
			'donor-core-progress-bar-editor-style',
			DONOR_CORE_PLUGIN_URL . 'assets/css/progress-bar-block.css',
			array(),
			DONOR_CORE_VERSION
		);

		// Register FRONTEND-ONLY styles for progress bar block
		wp_register_style(
			'donor-core-progress-bar-frontend-style',
			DONOR_CORE_PLUGIN_URL . 'includes/css/frontend-blocks.css',
			array(),
			DONOR_CORE_VERSION
		);
		
		// Localize currency for progress bar block too
		wp_localize_script(
			'donor-core-progress-bar-block',
			'donorCoreSettings',
			array(
				'currency' => get_woocommerce_currency(),
				'currencySymbol' => get_woocommerce_currency_symbol(),
				'locale' => get_locale(),
			)
		);

		// Register progress bar block
		register_block_type( 'donor-core/progress-bar', array(
			'editor_script'   => 'donor-core-progress-bar-block',
			'editor_style'    => 'donor-core-progress-bar-editor-style',
			'style'           => 'donor-core-progress-bar-frontend-style',
			'render_callback' => array( $this, 'render_progress_bar' ),
			'category'        => 'donorcore-donations',
			'attributes'      => array(
				'campaignId' => array(
					'type'    => 'string',
					'default' => '',
				),
				'showAmount' => array(
					'type'    => 'boolean',
					'default' => true,
				),
				'showPercentage' => array(
					'type'    => 'boolean',
					'default' => true,
				),
			),
		) );
	}

	/**
	 * Render donation form block.
	 *
	 * @param array $attributes Block attributes.
	 * @return string
	 */
	public function render_donation_form( $attributes ) {
		$campaign_id = isset( $attributes['campaignId'] ) ? intval( $attributes['campaignId'] ) : 0;

		if ( ! $campaign_id ) {
			return '<p>' . esc_html__( 'Please configure campaign ID.', 'donorcore-donations' ) . '</p>';
		}

		$campaign = get_post( $campaign_id );
		if ( ! $campaign || 'donorcore_campaign' !== $campaign->post_type ) {
			return '<p>' . esc_html__( 'Campaign not found.', 'donorcore-donations' ) . '</p>';
		}

		$product_id = get_post_meta( $campaign_id, '_donorcore_campaign_product_id', true );
		if ( ! $product_id ) {
			return '<p>' . esc_html__( 'Product not linked to campaign.', 'donorcore-donations' ) . '</p>';
		}

		// Get suggested amounts with fallback to global settings.
		$suggested = get_post_meta( $campaign_id, '_donorcore_campaign_suggested_amounts', true );
		$amounts   = is_string( $suggested ) && ! empty( $suggested ) ? json_decode( $suggested, true ) : null;
		if ( is_array( $amounts ) ) {
			$amounts = array_filter( array_map( 'floatval', $amounts ) );
		}
		if ( empty( $amounts ) || ! is_array( $amounts ) ) {
			$global_suggested = get_option( 'donorcore_suggested_amounts', '50,100,250,500' );
			$amounts          = array_map( 'floatval', array_filter( array_map( 'trim', explode( ',', $global_suggested ) ) ) );
			if ( empty( $amounts ) ) {
				$amounts = array( 50, 100, 250, 500 );
			}
		}
		$amounts = array_values( $amounts );

		// Check if campaign has ended
		$end_date = get_post_meta( $campaign_id, '_donorcore_campaign_end_date', true );
		$is_ended = false;
		if ( $end_date ) {
			$end_timestamp = strtotime( $end_date );
			$is_ended = ( time() > $end_timestamp );
		}

		// If campaign has ended, show only progress bar and message
		if ( $is_ended ) {
			ob_start();
			?>
			<div class="dc-campaign-ended-wrapper">
				<div class="dc-ended-notice">
					<span class="dc-ended-icon">🏁</span>
					<h3><?php esc_html_e( 'This Campaign Has Ended', 'donorcore-donations' ); ?></h3>
					<p><?php 
						printf( 
							/* translators: %s: end date */
							esc_html__( 'This campaign ended on %s. Thank you to all our supporters!', 'donorcore-donations' ), 
							esc_html( gmdate( 'F j, Y', strtotime( $end_date ) ) ) 
						); 
					?></p>
				</div>
			</div>


			<?php
			return ob_get_clean();
		}

		ob_start();
		?>
		<div class="dc-donation-form-wrapper">
		<h3 class="dc-campaign-title"><?php echo esc_html( $campaign->post_title ); ?></h3>
			<form class="dc-donation-form" method="post" action="<?php echo esc_url( wc_get_cart_url() ); ?>">
				<?php wp_nonce_field( 'donorcore_add_to_cart_' . $product_id, 'donorcore_add_to_cart_nonce' ); ?>
				<div class="dc-amount-selector">
					<div class="dc-section-label"><?php esc_html_e( 'Select Amount', 'donorcore-donations' ); ?></div>
					<div class="dc-amount-buttons">
						<?php foreach ( $amounts as $amount ) : ?>
							<button type="button" class="dc-amount-btn" data-amount="<?php echo esc_attr( $amount ); ?>">
								<?php echo wp_kses_post( wc_price( $amount ) ); ?>
							</button>
						<?php endforeach; ?>
					</div>
					<div class="dc-custom-amount-input">
						<div class="dc-section-label"><?php esc_html_e( 'Custom Amount', 'donorcore-donations' ); ?></div>
						<input type="number" name="donorcore_donation_amount" class="dc-amount-field" step="0.01" min="1" value="<?php echo esc_attr( $amounts[0] ); ?>" required />
					</div>
				</div>

				<input type="hidden" name="add-to-cart" value="<?php echo esc_attr( $product_id ); ?>" />
				<button type="submit" class="dc-donate-btn"><?php esc_html_e( 'Donate Now', 'donorcore-donations' ); ?></button>
			</form>
		</div>

	<?php
		$js = "
        document.addEventListener('DOMContentLoaded', function() {
            // Select all donation wrappers
            const wrappers = document.querySelectorAll('.dc-donation-form-wrapper');

			const freqLabels = document.querySelectorAll('.dc-frequency-selector label');
            
            wrappers.forEach(wrapper => {
                const buttons = wrapper.querySelectorAll('.dc-amount-btn');
                const input = wrapper.querySelector('.dc-amount-field');
                
                // Set initial active state (first button)
                if(buttons.length > 0) {
                    buttons[0].classList.add('active');
                }

                buttons.forEach(btn => {
                    btn.addEventListener('click', function() {
                        // Remove active class from all buttons in THIS wrapper only
                        buttons.forEach(b => b.classList.remove('active'));
                        
                        // Add active class to clicked button
                        this.classList.add('active');
                        
                        // Update the input field in THIS wrapper
                        if(input) {
                            input.value = this.dataset.amount;
                            // Trigger change event just in case other scripts listen for it
                            input.dispatchEvent(new Event('change')); 
                        }
                    });
                });
            });

			freqLabels.forEach(label => {
				label.addEventListener('click', function() {
					// Remove active class from siblings
					freqLabels.forEach(l => l.removeAttribute('data-active'));
					// Add active state to clicked
					this.setAttribute('data-active', 'true');
				});
				
				// Set initial active state based on checked input
				if (label.querySelector('input').checked) {
					label.setAttribute('data-active', 'true');
				}
			});
        });
		";
		wp_add_inline_script( 'donor-core-donation-form-frontend', $js );
		?>
		<?php
		return ob_get_clean();
	}

	/**
	 * Render progress bar block.
	 *
	 * @param array $attributes Block attributes.
	 * @return string
	 */
	public function render_progress_bar( $attributes ) {
		$campaign_id     = isset( $attributes['campaignId'] ) ? intval( $attributes['campaignId'] ) : 0;
		$show_amount     = isset( $attributes['showAmount'] ) ? $attributes['showAmount'] : true;
		$show_percentage = isset( $attributes['showPercentage'] ) ? $attributes['showPercentage'] : true;

		if ( ! $campaign_id ) {
			return '<p>' . esc_html__( 'Please configure campaign ID.', 'donorcore-donations' ) . '</p>';
		}

		$campaign = get_post( $campaign_id );
		if ( ! $campaign || 'donorcore_campaign' !== $campaign->post_type ) {
			return '<p>' . esc_html__( 'Campaign not found.', 'donorcore-donations' ) . '</p>';
		}

		$goal       = get_post_meta( $campaign_id, '_donorcore_campaign_goal', true );
		$donation_repo = new \DonorCore\Database\Donation_Log_Repository();
		$raised     = $donation_repo->get_campaign_total( $campaign_id );
		$percentage = $goal > 0 ? min( 100, round( ( $raised / $goal ) * 100, 1 ) ) : 0;

		ob_start();
		?>
		<div class="dc-progress-bar-wrapper">
			<h3><?php echo esc_html( $campaign->post_title ); ?></h3>
			<div class="dc-progress-bar">
				<div class="dc-progress-fill" style="width: <?php echo esc_attr( $percentage ); ?>%">
					<?php if ( $show_percentage ) : ?>
						<span class="dc-progress-text"><?php echo esc_html( $percentage ); ?>%</span>
					<?php endif; ?>
				</div>
			</div>
			<?php if ( $show_amount ) : ?>
			<div class="dc-progress-amounts">
				<span class="dc-raised-wrapper">
					<strong class="dc-amount"><?php echo wp_kses_post( wc_price( $raised ) ); ?></strong> <?php esc_html_e( 'raised', 'donorcore-donations' ); ?>
				</span>
				<span class="dc-goal-wrapper">
					<?php esc_html_e( 'of', 'donorcore-donations' ); ?> <strong class="dc-amount"><?php echo wp_kses_post( wc_price( $goal ) ); ?></strong>
				</span>
			</div>
			<?php endif; ?>
		</div>


		<?php
		return ob_get_clean();
	}


}
