<?php
/**
 * Form renderer — builds the password form output.
 *
 * @package PrivexPasswordProtect
 */

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

/**
 * Class PPMSTR_Form_Renderer
 */
class PPMSTR_Form_Renderer {

	/**
	 * Render a password form and return the HTML.
	 *
	 * @param array $args Form arguments.
	 * @return string HTML output.
	 */
	public function render( $args = array() ) {
		$settings = get_option( 'ppmstr_settings', array() );

		$defaults = array(
			'post_id'     => 0,
			'type'        => 'post',
			'error'       => false,
			'headline'    => isset( $settings['form_headline'] ) ? $settings['form_headline'] : __( 'This Content is Protected', 'privex-password-protect' ),
			'description' => isset( $settings['form_description'] ) ? $settings['form_description'] : '',
			'button_text' => isset( $settings['form_button_text'] ) ? $settings['form_button_text'] : __( 'Unlock', 'privex-password-protect' ),
			'placeholder' => isset( $settings['form_placeholder'] ) ? $settings['form_placeholder'] : __( 'Enter password…', 'privex-password-protect' ),
			'error_msg'   => isset( $settings['form_error_message'] ) ? $settings['form_error_message'] : '',
			'template'    => isset( $settings['active_template'] ) ? $settings['active_template'] : 'default',
		);

		$args     = wp_parse_args( $args, $defaults );
		$type     = $args['type'];
		$post_id  = absint( $args['post_id'] );
		$nonce    = '';

		switch ( $type ) {
			case 'site':
				$nonce = wp_create_nonce( 'ppmstr_password_site' );
				break;
			case 'category':
				$term_id = isset( $args['term_id'] ) ? absint( $args['term_id'] ) : 0;
				$nonce   = wp_create_nonce( 'ppmstr_password_cat_' . $term_id );
				break;
			case 'post_type':
				$post_type = isset( $args['post_type'] ) ? sanitize_key( $args['post_type'] ) : get_post_type( $post_id );
				$nonce     = wp_create_nonce( 'ppmstr_password_pt_' . $post_type );
				break;
			case 'child':
				$parent_id = isset( $args['parent_id'] ) ? absint( $args['parent_id'] ) : wp_get_post_parent_id( $post_id );
				if ( ! $parent_id ) {
					$parent_id = $post_id;
				}
				$nonce = wp_create_nonce( 'ppmstr_password_' . $parent_id );
				break;
			case 'shortcode':
				$instance_id = isset( $args['instance_id'] ) ? sanitize_key( $args['instance_id'] ) : '';
				$nonce       = wp_create_nonce( 'ppmstr_password_sc_' . $instance_id );
				break;
			default:
				// Regular post.
				$nonce = wp_create_nonce( 'ppmstr_password_' . $post_id );
				break;
		}
		// Inject CAPTCHA if enabled.
		if ( ! class_exists( 'PPMSTR_Security_Handler' ) ) {
			require_once PPMSTR_PLUGIN_DIR . 'includes/security/class-ppmstr-security-handler.php';
		}
		$args['captcha_html'] = PPMSTR_Security_Handler::get_captcha_html();

		// Phase 7: Countdown timer injection for Scheduled Unlock.
		if ( ! empty( $args['post_id'] ) ) {
			$sched_start = get_post_meta( $args['post_id'], '_ppmstr_schedule_start', true );
			if ( ! empty( $sched_start ) ) {
				$t = strtotime( $sched_start );
				if ( $t > current_time( 'timestamp' ) ) {
					$tz_offset     = get_option( 'gmt_offset' ) * HOUR_IN_SECONDS;
					$utc_timestamp = $t - $tz_offset; // Normalize to UTC timestamp for robust JS parsing.
					$args['description'] .= '<div class="ppmstr-countdown" data-unlock="' . esc_attr( $utc_timestamp ) . '" style="margin-top:12px;padding:12px;background:rgba(0,0,0,0.05);border-radius:6px;font-weight:600;font-size:14px;color:inherit;text-align:center;">' . esc_html__( 'Content auto-unlocks in: ', 'privex-password-protect' ) . '<span class="ppmstr-cd-val">--:--:--</span></div>';
				}
			}
		}

		// Check if this is a builder template (custom or preset).
		$template_slug = sanitize_key( $args['template'] );
		if ( ! class_exists( 'PPMSTR_Template_Builder' ) ) {
			require_once PPMSTR_PLUGIN_DIR . 'admin/class-ppmstr-template-builder.php';
		}
		if ( PPMSTR_Template_Builder::is_builder_template( $template_slug ) ) {
			return $this->render_custom_template( $template_slug, $args, $nonce );
		}

		$tpl_file = $this->locate_template( sanitize_file_name( $args['template'] ) );

		ob_start();
		include $tpl_file;
		$html = ob_get_clean();

		if ( ! empty( $args['captcha_html'] ) ) {
			$html = str_replace( '<button type="submit"', $args['captcha_html'] . '<button type="submit"', $html );
		}

		return $html;
	}

	/**
	 * Render a custom builder template from stored JSON config.
	 *
	 * @param string $template_id Custom template ID.
	 * @param array  $args        Form args.
	 * @param string $nonce       Nonce value.
	 * @return string HTML output.
	 */
	private function render_custom_template( $template_id, $args, $nonce ) {
		// Load builder class if not available.
		if ( ! class_exists( 'PPMSTR_Template_Builder' ) ) {
			require_once PPMSTR_PLUGIN_DIR . 'admin/class-ppmstr-template-builder.php';
		}

		$builder_tpl = PPMSTR_Template_Builder::get_template( $template_id );
		if ( ! $builder_tpl ) {
			// Fall back to default template.
			$tpl_file = $this->locate_template( 'default' );
			ob_start();
			include $tpl_file;
			return ob_get_clean();
		}

		return PPMSTR_Template_Builder::render( $builder_tpl, $args, $nonce );
	}

	/**
	 * Locate a template file with theme override support.
	 *
	 * @param string $slug Template slug.
	 * @return string Absolute path to the template file.
	 */
	private function locate_template( $slug ) {
		// Theme override.
		$theme = get_stylesheet_directory() . '/privex-password-protect/' . $slug . '/template.php';
		if ( file_exists( $theme ) ) {
			return $theme;
		}

		$plugin = PPMSTR_PLUGIN_DIR . 'templates/' . $slug . '/template.php';
		if ( file_exists( $plugin ) ) {
			return $plugin;
		}

		return PPMSTR_PLUGIN_DIR . 'templates/default/template.php';
	}
}
