<?php

namespace Aventa;

use Elementor\Widget_Base;
use Elementor\Controls_Manager;


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


class Rad_Card_Blog_Widget extends Widget_Base{

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

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

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

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

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

  protected function post_categories() {
    $posts_cats = [];
    $terms = get_terms(
      "category", 
      [
        "orderby"    => "term_id",
        "order"      => "ASC",
        "hide_empty" => false
      ]
    );

    foreach ($terms as $taxonomy) {
      $posts_cats[ $taxonomy->slug ] = $taxonomy->name;
    }

    return $posts_cats;
  }

  protected function register_controls() {

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

    $this->add_control(
      "cb_categories",
      [
        "label" => esc_html__( "Categories", "aventa" ),
        "type" => Controls_Manager::SELECT2,
        "options" => $this->post_categories(),
        "multiple" => true,
        "description" => esc_html__( "Leave empty to show all", "aventa" )
      ]
    );

    $this->add_control(
      "hr_1",
      [ "type" => Controls_Manager::DIVIDER ]
    );

    $this->add_control(
      "cb_post_number",
      [
        "label" => esc_html__( "Posts per Page", "aventa" ),
        "type" => Controls_Manager::NUMBER,
        "min" => 1,
        "max" => 30,
        "default" => 16
      ]
    );

    $this->add_control(
      "cb_show_load_more",
      [
        "label" => esc_html__( "Load More Button", "aventa" ),
        "type" => Controls_Manager::SWITCHER,
        "label_on" => esc_html__( "Show", "aventa" ),
        "label_off" => esc_html__( "Hide", "aventa" ),
        "return_value" => "true",
        "default" => "true"
      ]
    );

    $this->add_control(
      "hr_2",
      [ "type" => Controls_Manager::DIVIDER ]
    );

    $this->add_control(
      "cb_show_author",
      [
        "label" => esc_html__( "Author", "aventa" ),
        "type" => Controls_Manager::SWITCHER,
        "label_on" => esc_html__( "Show", "aventa" ),
        "label_off" => esc_html__( "Hide", "aventa" ),
        "return_value" => "true",
        "default" => "true",
        "condition" => [
          "cb_style" => "classic"
        ]
      ]
    );

    $this->add_control(
      "cb_show_comments",
      [
        "label" => esc_html__( "Comments", "aventa" ),
        "type" => Controls_Manager::SWITCHER,
        "label_on" => esc_html__( "Show", "aventa" ),
        "label_off" => esc_html__( "Hide", "aventa" ),
        "return_value" => "true",
        "default" => "true",
        "condition" => [
          "cb_style" => "classic"
        ]
      ]
    );

    $this->add_control(
      "cb_show_category",
      [
        "label" => esc_html__( "Category", "aventa" ),
        "type" => Controls_Manager::SWITCHER,
        "label_on" => esc_html__( "Show", "aventa" ),
        "label_off" => esc_html__( "Hide", "aventa" ),
        "return_value" => "true",
        "default" => "true"
      ]
    );

		$this->end_controls_section();

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

    $this->add_control(
      "cb_style",
      [
        "label" => esc_html__( "Style", "aventa" ),
        "type" => Controls_Manager::SELECT,
        "options" => [
          "classic" => esc_html__( "Classic", "aventa" ),
          "modern" => esc_html__( "Modern", "aventa" )
        ],
        "default" => "classic"
      ]
    );

    $this->add_control(
      "cb_layout",
      [
        "label" => esc_html__( "Layout", "aventa" ),
        "type" => Controls_Manager::SELECT,
        "options" => [
          "masonry" => esc_html__( "Masonry", "aventa" ),
          "fitRows" => esc_html__( "FitRows", "aventa" )
        ],
        "default" => "masonry",
        "condition" => [
          "cb_style" => "classic"
        ]
      ]
    );

    $this->add_control(
      "cb_columns",
      [
        "label" => esc_html__( "Columns", "aventa" ),
        "type" => Controls_Manager::SELECT,
        "options" => [
          "3" => esc_html( "3" ),
          "4" => esc_html( "4" )
        ],
        "default" => "3"
      ]
    );

    $this->add_control(
      "cb_image_size",
      [
        "label" => esc_html__( "Image Size", "aventa" ),
        "type" => Controls_Manager::SELECT,
        "options" => [
          "large"   => esc_html__( "Large", "aventa" ),
          "scaled"  => esc_html__( "Scaled", "aventa" )
        ],
        "default" => "large"
      ]
    );

    $this->end_controls_section();

    $this->start_controls_section(
			"section_design_style",
			[
				"label" => esc_html__( "Design", "aventa" ),
				"tab" => Controls_Manager::TAB_STYLE,
			]
		);

    $this->add_control(
      "cb_text_style",
      [
        "label" => esc_html__( "Card Text 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->add_control(
      "cb_bg_color",
      [
        "label" => esc_html__( "Card Background Color", "aventa" ),
        "type" => Controls_Manager::COLOR,
        "default" => "#f8f8f8"
      ]
    );

    $this->add_control(
      "cb_quote_text_color",
      [
        "label" => esc_html__( "Quote Text Color", "aventa" ),
        "type" => Controls_Manager::COLOR,
        "default" => "#fff",
        "separator" => "before"
      ]
    );

    $this->add_control(
      "cb_quote_bg_color",
      [
        "label" => esc_html__( "Quote Overlay Color", "aventa" ),
        "type" => Controls_Manager::COLOR,
        "selectors" => [
          "{{WRAPPER}} .rad-card-posts .card-post .quote-post" => "background-color: {{VALUE}} !important"
        ],
        "default" => "#000"
      ]
    );

    $this->add_control(
      "cb_video_icon_style",
      [
        "label" => esc_html__( "Video Icon Style", "aventa" ),
        "type" => Controls_Manager::CHOOSE,
        "options" => [
          "#fff" => [
            "title" => esc_html__( "Light", "aventa" ),
            "icon" => "fas fa-sun"
          ],
          "#000" => [
            "title" => esc_html__( "Dark", "aventa" ),
            "icon" => "fas fa-moon"
          ]
        ],
        "default" => "#fff",
        "selectors" => [
          "{{WRAPPER}} .rad-post-inner.video-post svg" => "fill: {{VALUE}}"
        ],
        "separator" => "before"
      ]
    );

    $this->add_control(
      "cb_sound_icon_style",
      [
        "label" => esc_html__( "Sound Icon Style", "aventa" ),
        "type" => Controls_Manager::CHOOSE,
        "options" => [
          "#fff" => [
            "title" => esc_html__( "Light", "aventa" ),
            "icon" => "fas fa-sun"
          ],
          "#000" => [
            "title" => esc_html__( "Dark", "aventa" ),
            "icon" => "fas fa-moon"
          ]
        ],
        "default" => "#fff",
        "selectors" => [
          "{{WRAPPER}} .rad-post-inner.audio-post svg" => "fill: {{VALUE}}"
        ]
      ]
    );

    $this->add_control(
      "cb_load_more_style",
      [
        "label" => esc_html__( "Load More 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",
        "separator" => "before",
        "condition" => [
          "cb_show_load_more" => "true"
        ]
      ]
    );

		$this->end_controls_section();

  }

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

    // User inputs
		$blog_category                = $settings[ "cb_categories" ];
		$blog_post_number             = esc_attr( $settings[ "cb_post_number" ] );
		$blog_foreground_color        = esc_attr( $settings[ "cb_text_style" ] );
		$blog_style                   = esc_attr( $settings[ "cb_style" ] );
		$load_more_visibility         = esc_attr( $settings[ "cb_show_load_more" ] );
		$blog_column                  = esc_attr( $settings[ "cb_columns" ] );
		$blog_layout_mode             = ( $blog_style == "modern" )
      ? "masonry"
      : esc_attr( $settings[ "cb_layout" ] );
		$blog_image_size              = esc_attr( $settings[ "cb_image_size" ] );
		$blog_background_color        = esc_attr( $settings[ "cb_bg_color" ] );
		$blog_category_visibility     = esc_attr( $settings[ "cb_show_category" ] );
		$show_author                  = esc_attr( $settings[ "cb_show_author" ] );
		$show_comments                = esc_attr( $settings[ "cb_show_comments" ] );
		$quote_blog_text_color        = esc_attr( $settings[ "cb_quote_text_color" ] );
		$load_more_style              = esc_attr( $settings[ "cb_load_more_style" ] );

    // Logic
    $show_video_audio = false;

    $id       = rad_element_id("blg");
    $post_page = isset($_GET["postpage"]) ? (int) $_GET["postpage"] : 1;
    $arg     = array(
      "posts_per_page" => $blog_post_number,
      "paged"          => $post_page,
      "post_type"      => "post"
    );

    if ( $blog_category ) {
      $arg["tax_query"] = array(
        array(
          "taxonomy" => "category",
          "field"    => "slug",
          "terms"    => $blog_category
        ),
      );
    }

    $query = new \WP_Query($arg);
    $max   = ceil($query->found_posts / $blog_post_number);

    $html = "";

    $classes   = array("card-blog", $blog_style . "-card", $blog_foreground_color, "column-" . $blog_column);
    $classes[] = ($load_more_visibility != "true") ? "no-load-more" : "";

    $attrs = "data-page='1' ";
    $attrs .= "data-maxpages='" . esc_attr( $max ) . "' ";
    $html .= rad_make_container("div", "", $id, implode(" ", array_filter($classes)), "", $attrs, false);

    $attrs = "data-columnnumber='" . esc_attr($blog_column) . "' ";
    $attrs .= "data-layout='" . esc_attr($blog_layout_mode) . "' ";
    $html .= rad_make_container("div", "", "", "rad-card-posts isotope", "", $attrs, false);

    $stickies = array();
    while ($query->have_posts()) {
        $query->the_post();

        $format = rad_get_post_format(get_the_ID());
        if ($blog_image_size == "large") {
          $thumb = rad_get_image_url(get_post_thumbnail_id(), "large");
        } else {
          $thumb = rad_get_image_url(get_post_thumbnail_id(), "rad_thumbnail-auto-height");
        }

        $sticky     = (is_sticky(get_the_ID()) && !in_array(get_the_ID(), $stickies)) ? " sticky" : "";
        $stickies[] = get_the_ID();

        $html .= "<div class=\"card-post isotope-item" . $sticky . "\">";
        $html .= "<div class=\"rad-post-wrap target-anim\">";
        $style = $blog_background_color != "" ? "background-color:" . esc_attr($blog_background_color) . ";" : "";
        $html .= rad_make_container("div", "", "", "rad-post-inner " . $format . "-post", $style, "", false);

        if ($format == "audio") {
          if ($show_video_audio) {
            $audio = rad_get_meta("audio-url", true, get_the_ID());
            if ($audio != null) {
              $html .= do_shortcode("[audio_soundcloud soundcloud_id=\"" . esc_url($audio) . "\"]");
            }
          } else {
            if ($thumb != "") {
              $html .= "<div class=\"image-container lazy-load bg-lazy-load lazy-load-on-load\" data-src=\"" . esc_url($thumb) . "\">";
              $html .= "<a href=\"" . esc_url(get_the_permalink()) . "\">";
              $html .= \rad_Icon_Manager::get_icon("sound", "external");
              $html .= "</a>";
              $html .= "</div>";
            }
          }

        } else if ($format == "gallery") {
            $images = explode(",", rad_get_meta("gallery", true, get_the_ID()));
            if (count($images) > 0) {
              $html .= "<div class=\"swiper-container clearfix\" data-visibleitems=\"1\">";
              $html .= "<div class=\"slides swiper-wrapper\">";
              foreach ($images as $img_id) {
                if ($blog_image_size == "large") {
                  $img = rad_get_image_url($img_id, "large");
                } else {
                  $img = rad_get_image_url($img_id, "rad_thumbnail-auto-height");
                }
                $html .= "<div class=\"swiper-slide\" style=\"background-image:url(" . esc_url($img) . ");\"></div>";
              }
              $html .= "</div>";
              if (count($images) > 1) {
                $html .= "<div class=\"rad-carousel-prev unselectable\"></div>";
                $html .= "<div class=\"rad-carousel-next unselectable\"></div>";
              }
              $html .= "</div>";
            }

        } else if ($format == "video") {

          if ($show_video_audio) {
            $videoUrl = rad_get_meta("video-id", true, get_the_ID());
            $host     = rad_get_meta("video-type", true, get_the_ID());

            $video_display_type = "embeded_video_$host";

            if ($video_display_type == "embeded_video_vimeo") {

              $html .= "<div data-id=\"" . esc_attr($id) . "\">";
              $html .= do_shortcode("[rad_video video_display_type=\"embeded_video_vimeo\" video_vimeo_id=\"" . esc_url($videoUrl) . "\"]");
              $html .= "</div>";

            } else if ($video_display_type == "embeded_video_youtube") {

              $video_id = explode("?v=", $videoUrl); // detect youtube id form url
              if (empty($video_id[1])) {
                $video_id = explode("/v/", $videoUrl);
              }
              if (!empty($video_id[1])) {
                $video_id = explode("&", $video_id[1]); // removing any other params
                $video_id = $video_id[0];
              } else {
                $video_id = $videoUrl;
              }
              $html .= "<div data-id=\"" . esc_attr($id) . "\">";
              $html .= "<div class=\"wpb_video_widget wpb_content_element vc_clearfix vc_video-aspect-ratio-169\">";
              $html .= "<div class=\"wpb_wrapper\">";
              $html .= "<div class=\"wpb_video_wrapper\">";
              $html .= "<iframe title=\"" . esc_attr__("YouTube video player", "aventa") . "\" src=\"https://www.youtube.com/embed/" . esc_url($video_id) . "\" allowfullscreen></iframe>";
              $html .= "</div>";
              $html .= "</div>";
              $html .= "</div>";
              $html .= "</div>";

            }
          } else {
            if ($thumb != "") {
              $html .= "<div class=\"image-container lazy-load bg-lazy-load lazy-load-on-load\" data-src=\"" . esc_url($thumb) . "\">";
              $html .= "<a href=\"" . esc_url(get_the_permalink()) . "\">";
              $html .= \rad_Icon_Manager::get_icon("caret-right", "solid");
              $html .= "</a>";
              $html .= "</div>";
            }
          }

        } elseif ($format == "quote") {
          if ($thumb != "") {
            $html .= "<div class=\"image-container lazy-load bg-lazy-load lazy-load-on-load\" data-src=\"" . esc_url($thumb) . "\"></div>";
          }
        } else {
          //standard format
          if ($thumb != "") {
            $html .= "<div class=\"image-container lazy-load bg-lazy-load lazy-load-on-load\" data-src=\"" . esc_url($thumb) . "\">";
            $html .= "<a href=\"" . esc_url(get_the_permalink()) . "\"></a>";
            $html .= "</div>";
          }
        }

        if ($format == "quote") {
          $quote_content = rad_get_meta("quote_content", true, get_the_ID());
          $quote_author  = rad_get_meta("quote_author", true, get_the_ID());

          $html .= "<a class=\"quote-wrap-link\" href=\"" . esc_url(get_the_permalink()) . "\">";
          $html .= "<div class=\"rad-content\">";
          $html .= "<blockquote style=\"color:" . esc_attr($quote_blog_text_color) . ";\">";
          $html .= "<p style=\"color:" . esc_attr($quote_blog_text_color) . ";\">" . esc_html($quote_content) . "</p>";
          $html .= "<cite class=\"author\" style=\"color:" . esc_attr($quote_blog_text_color) . ";\">";
          $html .= esc_html($quote_author) . "</cite>";
          $html .= "</blockquote>";
          $html .= "</div>";
          $html .= "</a>";

        } else {
          $more = (strlen(get_the_excerpt()) > 100) ? "..." : "";
          $html .= "<div class=\"rad-content\">";
          $html .= "<span class=\"rad-cats\">";
          if ($blog_category_visibility == "true") {
            $terms = get_the_category(get_the_ID());
            if ($terms) {
              foreach ($terms as $term) {
                $html .= "<a href=\"" . esc_url(get_category_link(get_cat_ID($term->cat_name))) . "\" class=\"rad-cat underline-style\" title=\"" . esc_attr($term->cat_name) . "\">";
                $html .= esc_html($term->cat_name) . "</a>";
              }
            }
          }

          $title = get_the_title();

          $html .= "</span>";
          $html .= "<a href=\"" . esc_url(get_the_permalink()) . "\" title=\"" . $title . "\">";
          $html .= "<h2>" . $title . "</h2>";
          $html .= "</a>";
          if ($blog_style != "modern") {
            $html .= "<p class=\"rad-post-excerpt\">";
            $html .= mb_substr(get_the_excerpt(), 0, 100) . $more;
            $html .= "</p>";
            $html .= "<div class=\"rad-post-meta\">";
            if ($show_author == "true") {
              $html .= "<span class=\"post-author\">";
              $html .= get_avatar(get_the_author_meta("user_email"), 35);
              $html .= get_the_author_posts_link();
              $html .= "</span>";
            }

            $html .= "<span class=\"rad-post-date\">";
            $html .= get_the_time(get_option("date_format"));
            $html .= "</span>";

            if ($show_comments == "true") {
              $html .= "<a class=\"rad-post-comments\" href=\"" . esc_url(get_comments_link()) . "\">" . get_comments_number_text(esc_html__("No comment", "aventa"), esc_html__("1 comment", "aventa"), esc_html__("% comments", "aventa")) . "</a>";
            }

            $html .= "</div>";
          }
          $html .= "<a class=\"rad-post-link\" href=\"" . esc_url(get_the_permalink()) . "\">" . esc_html__("Read more", "aventa") . "</a>";

          $html .= "</div>";

        }
        $html .= "</div>";
        $html .= "</div>";
        $html .= "</div>";
    }
    wp_reset_postdata();

    $html .= "</div>";
    if ($load_more_visibility == "true") {
      $html .= "<div class=\"card-blog-load-more " . esc_attr($load_more_style) . "\">";
      $html .= "<a href=\"#\">" . esc_html__("Load more", "aventa") . "</a>";
      $html .= "</div>";
    }
    $html .= "</div>";

    echo "$html";
  }

}