<?php

namespace Aventa;

use Elementor\Widget_Base;
use Elementor\Controls_Manager;


if ( !defined( "ABSPATH" ) ) exit; 

class Rad_Newsletter_Widget extends Widget_Base{

  public function get_name() {
    return "rad-newsletter";
  }

  public function get_title() {
    return esc_html__("Newsletter", "aventa");
  }

  public function get_keywords() {
		return [ "mailchimp", "aventa" ];
	}

  public function get_icon() {
    return "eicon-mailchimp";
  }

  public function get_categories() {
    return [ Rad_Helpers::WIDGETS_CATEGORY ];
  }

  protected function register_controls() {

		// Widget content
    $this->start_controls_section(
			"section_title",
			[
				"label" => esc_html__( "Newsletter", "aventa" ),
			]
		);

    $newsletter_forms = array_flip( rad_get_MC4WP_forms() );

    $this->add_control(
			"nl_form", [
				"label" => esc_html__( "Form", "aventa" ),
				"type" => Controls_Manager::SELECT,
        "options" => $newsletter_forms,
        "description" => esc_html__( "New forms can be added through: WordPress Menu > MC4WP > Form", "aventa" )
			]
		);

		$this->end_controls_section();

    // General style
    $this->start_controls_section(
			"section_general_style",
			[
				"label" => esc_html__( "General", "aventa" ),
				"tab" => Controls_Manager::TAB_STYLE,
			]
		);

    Rad_Helpers::alignment( $this, "nl_align" );

    $this->add_control(
      "nl_style",
      [
        "label" => esc_html__( "Style", "aventa" ),
        "type" => Controls_Manager::CHOOSE,
        "options" => [
          "light" => [
            "title" => esc_html__( "Light", "aventa" ),
            "icon" => "fas fa-sun"
          ],
          "dark" => [
            "title" => esc_html__( "Dark", "aventa" ),
            "icon" => "fas fa-moon"
          ]
        ],
        "default" => "dark"
      ]
    );


		$this->end_controls_section();

  }

  protected function render() {
    $settings = $this->get_settings_for_display();

		if ( !$settings[ "nl_form" ] ) {
			return;
		}

    $classes = [ 
      "rad-newsletter"
    ];

    // User inputs
		$form_id  = esc_attr( $settings[ "nl_form" ] );
		$style    = esc_attr( $settings[ "nl_style" ] );
		$align    = esc_attr( $settings[ "nl_align" ] );

    
    if ( !class_exists("MC4WP_MailChimp") || $form_id == "" ) {
      return;
    }

    // Add classes based on selected options
    $classes[] = $align;
    $classes[] = $style;

    // Attributes
    $this->add_render_attribute( "newsletter_container", "class", implode( " ", $classes ) );

    // HTML
    $newsletter_html = do_shortcode( shortcode_unautop( "[mc4wp_form id='$form_id']" ) );

    // Final HTML to render
    $html = sprintf( 
      '<div %1$s>%2$s</div>', 
      $this->get_render_attribute_string( "newsletter_container" ),
      $newsletter_html
    );

    echo "$html";

  }

}