<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; }
use Sifency\Classes\Sifency_Addons_Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;
use Sifency\Traits\Sifency_Addons_Button_Style_Controls;
use Sifency\Traits\Sifency_Addons_Help_Controls;
class Sifency_Addons_Widget_Protected_Content extends Sifency_Addons_Widget_Base {
	use Sifency_Addons_Button_Style_Controls;
	use Sifency_Addons_Help_Controls;

	public function __construct( $data = array(), $args = null ) {
		parent::__construct( $data, $args );
		$this->wg_config = array(
			'name'           => 'sifency-protected-content',
			'title'          => 'Sifency Protected Content',
			'icon'           => 'eicon-lock-user',
			'category'       => array( 'sifency-creative-widgets' ),
			'script_depends' => array( 'sifency-protected-content-script' ),
			'style_depends'  => array( 'sifency-moon-style' ),
		);
	}
	protected function register_controls() {
		$this->start_controls_section( 'section_content', array( 'label' => 'Protect Text or Full Elementor Template' ) );

		$this->add_control(
			'content_source',
			array(
				'label'   => 'Content Type',
				'type'    => Controls_Manager::SELECT,
				'default' => 'text',
				'options' => array(
					'text'     => 'Custom Text',
					'template' => 'Elementor Template',
				),
			)
		);

		$this->add_control(
			'protected_text',
			array(
				'label'     => 'Protected Text Content',
				'type'      => Controls_Manager::WYSIWYG,
				'default'   => 'This is secret protected content!',
				'condition' => array( 'content_source' => 'text' ),
			)
		);

		$this->add_control(
			'template_id',
			array(
				'label'     => 'Select Template',
				'type'      => Controls_Manager::SELECT2,
				'options'   => function_exists( 'sifency_addons_get_elementor_templates' ) ? sifency_addons_get_elementor_templates() : array(),
				'condition' => array( 'content_source' => 'template' ),
			)
		);
		$this->end_controls_section();
		$this->start_controls_section( 'section_protection', array( 'label' => 'User Role, Single or Multi Password Mode' ) );

		$this->add_control(
			'protection_mode',
			array(
				'label'   => 'Select Protection Mode',
				'type'    => Controls_Manager::SELECT,
				'default' => 'single',
				'options' => array(
					'role'   => 'User Role Based',
					'single' => 'Single Password',
					'multi'  => 'Multiple Passwords',
				),
			)
		);

		$this->add_control(
			'allowed_roles',
			array(
				'label'       => 'Allowed User Roles',
				'type'        => Controls_Manager::SELECT2,
				'multiple'    => true,
				'options'     => $this->get_user_roles(),
				'condition'   => array( 'protection_mode' => 'role' ),
				'description' => 'Select which logged-in roles can see this content.',
			)
		);

		$this->add_control(
			'single_password',
			array(
				'label'     => 'Enter Password',
				'type'      => Controls_Manager::TEXT,
				'default'   => 'secret123',
				'condition' => array( 'protection_mode' => 'single' ),
			)
		);

		$this->add_control(
			'multi_password',
			array(
				'label'       => 'Enter Passwords (One per line)',
				'type'        => Controls_Manager::TEXTAREA,
				'condition'   => array( 'protection_mode' => 'multi' ),
				'description' => 'Users can unlock the content using ANY of these passwords.',
			)
		);
		$this->end_controls_section();
		$this->start_controls_section(
			'section_cookie',
			array(
				'label'     => 'Store Value in Cookie',
				'condition' => array( 'protection_mode' => array( 'single', 'multi' ) ),
			)
		);

		$this->add_control(
			'save_cookie',
			array(
				'label'   => 'Remember Unlock State',
				'type'    => Controls_Manager::SWITCHER,
				'default' => 'yes',
			)
		);

		$this->add_control(
			'cookie_days',
			array(
				'label'     => 'Cookie Expiry (Days)',
				'type'      => Controls_Manager::NUMBER,
				'default'   => 7,
				'condition' => array( 'save_cookie' => 'yes' ),
			)
		);
		$this->end_controls_section();
		$this->start_controls_section( 'section_before_content', array( 'label' => 'Add Custom Content Before Unlocking Protected Content' ) );

		$this->add_control(
			'before_content_text',
			array(
				'label'   => 'Heading / Description',
				'type'    => Controls_Manager::WYSIWYG,
				'default' => '<h3>Restricted Access</h3><p>Please enter the password to view this content.</p>',
			)
		);
		$this->end_controls_section();
		$this->start_controls_section(
			'section_form_text',
			array(
				'label'     => 'Edit Form Text',
				'condition' => array( 'protection_mode' => array( 'single', 'multi' ) ),
			)
		);

		$this->add_control(
			'input_placeholder',
			array(
				'label'   => 'Input Placeholder',
				'type'    => Controls_Manager::TEXT,
				'default' => 'Enter Password...',
			)
		);

		$this->add_control(
			'button_text',
			array(
				'label'   => 'Submit Button Text',
				'type'    => Controls_Manager::TEXT,
				'default' => 'Unlock',
			)
		);
		$this->end_controls_section();
		$this->start_controls_section( 'section_error', array( 'label' => 'Custom Error Message' ) );

		$this->add_control(
			'error_message',
			array(
				'label'   => 'Error Message Text',
				'type'    => Controls_Manager::TEXT,
				'default' => 'Incorrect password. Please try again.',
			)
		);
		$this->end_controls_section();
		$this->start_controls_section(
			'style_general_section',
			array(
				'label' => 'Customize Everything',
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_control(
			'form_alignment',
			array(
				'label'     => 'Alignment',
				'type'      => Controls_Manager::CHOOSE,
				'options'   => array(
					'left'   => array(
						'title' => 'Left',
						'icon'  => 'eicon-text-align-left',
					),
					'center' => array(
						'title' => 'Center',
						'icon'  => 'eicon-text-align-center',
					),
					'right'  => array(
						'title' => 'Right',
						'icon'  => 'eicon-text-align-right',
					),
				),
				'default'   => 'center',
				'selectors' => array( '{{WRAPPER}} .sifency-protected-lock-screen' => 'text-align: {{VALUE}}; align-items: {{VALUE}};' ),
			)
		);

		$this->add_control(
			'error_color',
			array(
				'label'     => 'Error Message Color',
				'type'      => Controls_Manager::COLOR,
				'default'   => '#e74c3c',
				'selectors' => array( '{{WRAPPER}} .sf-error-msg' => 'color: {{VALUE}};' ),
			)
		);

		$this->end_controls_section();
		$this->add_Sifency_Addons_Button_Style_Controls(
			array(
				'target_children' => true,
				'selector'        => '.sf-unlock-btn',
			)
		);
	}
	private function get_user_roles() {
		global $wp_roles;
		$roles = array();
		if ( isset( $wp_roles ) ) {
			foreach ( $wp_roles->roles as $key => $value ) {
				$roles[ $key ] = $value['name'];
			}
		}
		return $roles;
	}

	protected function render_dom( array $context ) {
		$settings = $this->get_settings_for_display();

		$raw_content = '';
		if ( $settings['content_source'] === 'text' ) {
			$raw_content = wpautop( $settings['protected_text'] );
		} elseif ( $settings['content_source'] === 'template' && ! empty( $settings['template_id'] ) ) {
			$raw_content = \Elementor\Plugin::instance()->frontend->get_builder_content_for_display( $settings['template_id'] );
		}

		if ( $settings['protection_mode'] === 'role' ) {
			$user          = wp_get_current_user();
			$allowed_roles = $settings['allowed_roles'] ? $settings['allowed_roles'] : array();
			$has_access    = false;

			if ( is_user_logged_in() && ! empty( array_intersect( $allowed_roles, $user->roles ) ) ) {
				$has_access = true;
			}

			if ( $has_access ) {
				echo '<div class="sifency-unlocked-content">' . esc_html( $raw_content ) . '</div>';
			} else {
				echo '<div class="sifency-protected-lock-screen">';
				echo wp_kses_post( $settings['before_content_text'] );
				echo '<p class="sf-error-msg" style="display:block;">' . esc_html( $settings['error_message'] ) . '</p>';
				echo '</div>';
			}
			return;
		}

		$encoded_content = base64_encode( rawurlencode( $raw_content ) );

		$passwords = array();
		if ( $settings['protection_mode'] === 'single' ) {
			$passwords[] = $settings['single_password'];
		} else {
			$passwords = array_map( 'trim', explode( "\n", $settings['multi_password'] ) );
		}

		$widget_id = $this->get_id();

		$js_settings = array(
			'id'        => $widget_id,
			'passwords' => $passwords,
			'cookie'    => $settings['save_cookie'] === 'yes',
			'days'      => $settings['cookie_days'],
		);
		?>

		<div class="sifency-protected-wrapper" id="sf-protect-<?php echo esc_attr( $widget_id ); ?>" data-config='<?php echo json_encode( $js_settings ); ?>'>
			
			<div class="sifency-protected-lock-screen">
				<div class="sf-before-content">
					<?php echo wp_kses_post( $settings['before_content_text'] ); ?>
				</div>
				
				<form class="sf-password-form">
					<div class="sf-input-group">
						<input type="password" class="sf-password-input" placeholder="<?php echo esc_attr( $settings['input_placeholder'] ); ?>" required />
						<button type="submit" class="sf-unlock-btn">
							<i class="fas fa-lock"></i> <?php echo esc_html( $settings['button_text'] ); ?>
						</button>
					</div>
					<div class="sf-error-msg" style="display: none;"><?php echo esc_html( $settings['error_message'] ); ?></div>
				</form>
			</div>

			<template class="sf-secret-data"><?php echo esc_html( $encoded_content ); ?></template>
			
			<div class="sifency-unlocked-content"></div>

		</div>
		<?php
	}
}
