<?php
if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly.
}

/**
 * Deprecated element
 *
 * VC KIT Shortcode Instagram Feed class.
 *
 * @since 1.0
 * @package Visual Composer KIT
 */

class Vckit_Shortcode_Instagram_Feed extends Vckit_Shortcode_Base {

  protected $shortcode = 'vckit_instagram_feed';
  protected $name = 'Old Instagram Feed';
  protected $desc = 'Instagram feed inspration.';
  protected $default_enabled = false;

  public function getDesc() {
    return 'You should update to new instagram element: Instafeed because Instagram have changed its API';
  }

  public function hooks() {
    add_action( 'wp_ajax_elegant_get_instagram_post', array( $this, 'instagramPostHandler' ) );
    add_action( 'wp_ajax_nopriv_elegant_get_instagram_post', array( $this, 'instagramPostHandler' ) );
  }

  public function instagramPostHandler() {
    // @codingStandardsIgnoreStart
    if ( isset( $_POST['id'] ) ) {
      $id = $_POST['id'];

      $this->renderPostDetail( $id );
    }
    // @codingStandardsIgnoreEnd

    die();
  }

  public function params() {
    return array(
      'icon' => vc_addons_kit_assets( 'img/icons/instagram-feed.png' ),
      'deprecated' => '5.4',
      'params' => array(
        //array(
          //"type" => "dropdown",
          //"heading" => __("Display type" , 'legocreative' ),
          //"param_name" => "display",
          //"value" =>array(
            //__("Grid", 'legocreative' ) =>"grid",
            //__("Slider", 'legocreative' ) =>"slider",
            //),
          //"description" => __("Choose display type.", 'legocreative' ),
        //),
        array(
          'type' => 'textfield',
          'heading' => __( 'Username', 'legocreative' ),
          'param_name' => 'id',
          'description' => __( 'Enter Instagram User name. eg. shabbyapple', 'legocreative' ),
          'edit_field_class' => 'vc_col-sm-6',
        ),
        array(
          'type' => 'textfield',
          'heading' => __( 'Items Display', 'legocreative' ),
          'param_name' => 'number_items',
          'value' => '6',
          'description' => __( 'This variable allows you to set the maximum amount of items displayed at a time with the widest browser width', 'legocreative' ),
        ),
        array(
          'type'       => 'textfield',
          'group' => __( 'Responsive Options', 'legocreative' ),
          'heading'    => __( 'Item spacing', 'legocreative' ),
          'param_name' => 'spacing',
          'value'      => '0',
        ),
        array(
          'type' => 'dropdown',
          'heading' => __( 'Desktop Columns Count' , 'legocreative' ),
          'param_name' => 'item_width_md',
          'group' => __( 'Responsive Options', 'legocreative' ),
          'value' => array(
            __( '1 columns - 1/1 - 12 items in a row', 'legocreative' )          => 1,
            __( '2 columns - 1/6 - 6 items in a row', 'legocreative' )           => 2,
            __( '3 columns - 1/4 - 4 items in a row', 'legocreative' )           => 3,
            __( '4 columns - 1/3 - 3 items in a row', 'legocreative' )           => 4,
            __( '6 columns - 1/2 - 2 items in a row', 'legocreative' )           => 6,
            __( '12 columns - 1/1 - 1 item in a row', 'legocreative' )           => 12,
          ),
          'std' => '2',
          'description' => __( 'Choose Desktop(PC Mode) Columns Count', 'legocreative' ),
          'edit_field_class' => 'vc_col-sm-4',
        ),
        array(
          'type' => 'dropdown',
          'heading' => __( 'Tablet Columns Count' , 'legocreative' ),
          'param_name' => 'item_width_sm',
          'group' => __( 'Responsive Options', 'legocreative' ),
          'value' => array(
            __( '1 columns - 1/1 - 12 items in a row', 'legocreative' )          => 1,
            __( '2 columns - 1/6 - 6 items in a row', 'legocreative' )           => 2,
            __( '3 columns - 1/4 - 4 items in a row', 'legocreative' )           => 3,
            __( '4 columns - 1/3 - 3 items in a row', 'legocreative' )           => 4,
            __( '6 columns - 1/2 - 2 items in a row', 'legocreative' )           => 6,
            __( '12 columns - 1/1 - 1 item in a row', 'legocreative' )           => 12,
          ),
          'std' => '3',
          'description' => __( 'Choose Tablet Columns Count', 'legocreative' ),
          'edit_field_class' => 'vc_col-sm-4',
        ),
        array(
          'type' => 'dropdown',
          'heading' => __( 'Mobile Columns Count' ,'legocreative' ),
          'param_name' => 'item_width_xs',
          'group' => __( 'Responsive Options', 'legocreative' ),
          'value' => array(
            __( '1 columns - 1/1 - 12 items in a row', 'legocreative' )          => 1,
            __( '2 columns - 1/6 - 6 items in a row', 'legocreative' )           => 2,
            __( '3 columns - 1/4 - 4 items in a row', 'legocreative' )           => 3,
            __( '4 columns - 1/3 - 3 items in a row', 'legocreative' )           => 4,
            __( '6 columns - 1/2 - 2 items in a row', 'legocreative' )           => 6,
            __( '12 columns - 1/1 - 1 item in a row', 'legocreative' )           => 12,
          ),
          'std' => '6',
          'description' => __( 'Choose Mobile Columns Count', 'legocreative' ),
          'edit_field_class' => 'vc_col-sm-4',
        ),
        array(
          'type' => 'textfield',
          'heading' => __( 'Description Length', 'legocreative' ),
          'param_name' => 'excerpt',
          'value' => '0',
          'description' => __( 'Set description length (numbers of characters), default: 0. If you set 0 no display discription in fronted site', 'legocreative' ),
        ),
        array(
          'type' => 'dropdown',
          'heading' => __( 'Hover Color scheme' , 'legocreative' ),
          'param_name' => 'color_scheme',
          'value' => array(
            __( 'Default', 'legocreative' ) => 'default',
            __( 'Yellow black', 'legocreative' ) => 'yellow-black',
            __( 'Blue white', 'legocreative' ) => 'blue-white',
            __( 'Green gray', 'legocreative' ) => 'green-gray',
            ),
          'description' => __( 'Choose color scheme.', 'legocreative' ),
        ),
        array(
          'type' => 'dropdown',
          'heading' => __( 'Open mode' , 'legocreative' ),
          'param_name' => 'mode',
          'value' => array(
            __( 'Link to Instagram', 'legocreative' ) => 'instagram',
            //__( 'Open Popup', 'legocreative' )     => 'popup',
          ),
          'description' => __( 'Choose Tablet Columns Count', 'legocreative' ),
        ),
        array(
          'type' => 'checkbox',
          'heading' => __( 'Open link in new page', 'legocreative' ),
          'param_name' => 'link_new_page',
          'value' => array(
            __( 'Yes', 'legocreative' ) => 'yes',
          ),
          'std'   => 'yes',
          'dependency' => array(
            'element' => 'mode',
            'value'   => 'instagram',
          ),
        ),
        array(
          'type'       => 'textfield',
          'heading'    => __( 'Extra class name', 'legocreative' ),
          'param_name' => 'el_class',
          'description'       => __( 'Style particular content element differently - add a class name and refer to it in custom CSS.
', 'legocreative' ),
        ),
        array(
          'type' => 'css_editor',
          'heading' => __( 'CSS feed', 'legocreative' ),
          'param_name' => 'css',
          'group' => __( 'Design Options', 'legocreative' ),
        ),
      ),
    );
  }

  /**
   * Render shortcode
   *
   * @since  2.0
   *
   * @param $atts
   * @param null $content
   * @param null $tag
   *
   * @return string
   */
  public function render( $atts, $content = null, $tag = null ) {
    // For instagram scraper
    require_once VCKIT_PLUGIN_DIR . '/includes/unirest/src/Unirest.php';
    require_once VCKIT_PLUGIN_DIR . '/includes/instagram-scraper/src/InstagramScraper.php';

    return parent::render( $atts, $content, $tag );
  }

  public function enqueueScripts() {
    vc_icon_element_fonts_enqueue( 'fontawesome' );
  }

  /***
   * Save instagram data
   */
  private function saveInstagramData( $key, $data ) {
    // do not set an empty transient - should help catch private or empty accounts.
    if ( ! empty( $data ) ) {
      $instagram = base64_encode( serialize( $data ) );
      set_transient( $key, $instagram, apply_filters( 'vckit_instagram_cache_time', HOUR_IN_SECONDS * 2 ) );
    }

    return $instagram;
  }

  /**
   * Quick-and-dirty Instagram web scrape
   *
   * @see https://gist.github.com/cosmocatalano/4544576
   *
   * @param String $username username instagram.
   * @param int    $max max.
   *
   * @return array|WP_Error
   */
  public function scrapeUser( $username, $max ) {
    $username = trim( strtolower( $username ) );
    $key = 'instagram-media-new-' . sanitize_title_with_dashes( $username ) . '-max-' . $max;

    if ( empty( $max ) ) {
      $max = 20;
    }

    if ( false === ( $mediaString = get_transient( $key ) ) ) {
      try {
        $account = InstagramScraper\Instagram::getAccount( $username );
        $medias = InstagramScraper\Instagram::getMedias( $account->getId(), $max );
        $mediaString = $this->saveInstagramData( $key, $medias );
      } catch ( Exception $e ) {
        return new WP_Error( 'no_images', $e->getMessage() );
      }
    }

    if ( ! empty( $mediaString ) ) {
      $medias = unserialize( base64_decode( $mediaString ) );
      return array_slice( $medias, 0, $max );
    } else {
      return new WP_Error( 'no_images', __( 'Instagram did not return any images.', 'legocreative' ) );
    }
  }

  /**
   * Quick-and-dirty Instagram web scrape
   *
   * @see https://gist.github.com/cosmocatalano/4544576
   *
   * @param String $hashtag hashtag instagram.
   * @param int    $max max.
   *
   * @return array|WP_Error
   */
  public function scrapeHashtagBackup( $hashtag, $max ) {
    $hashtag = trim( strtolower( $hashtag ) );
    $key = 'instagram-media-hashtag-' . sanitize_title_with_dashes( $hashtag ) . '-max-' . $max;

    if ( false === ( $mediaString = get_transient( $key ) ) ) {
      try {
        $medias = InstagramScraper\Instagram::getMediasByTag( $hashtag, $max );
        $mediaString = $this->saveInstagramData( $key, $medias );
      } catch ( Exception $e ) {
        return new WP_Error( 'no_images', $e->getMessage() );
      }
    }

    if ( ! empty( $mediaString ) ) {
      $medias = unserialize( base64_decode( $mediaString ) );
      return array_slice( $medias, 0, $max );
    } else {
      return new WP_Error( 'no_images', __( 'Instagram did not return any images.', 'legocreative' ) );
    }
  }

  public function scrapePost( $code ) {
    $code = trim( $code );
    $key = 'instagram-media-code-' . sanitize_title_with_dashes( $code );

    $insta_username = vckit_get_option( 'instagram_username' );
    $insta_password = vckit_get_option( 'instagram_password' );

    if ( ! $insta_username || ! $insta_password ) {
      return new WP_Error( 'no_images', __( 'You have to setup instagram username and password in VCKIT option page first.', 'legocreative' ) );
    }

    if ( false === ( $mediaString = get_transient( $key ) ) ) {
      try {
        $instagram = InstagramScraper\Instagram::withCredentials( $insta_username, $insta_password );
        $media = InstagramScraper\Instagram::getMediaByCode( $code );
        $comments = InstagramScraper\Instagram::getCommentsFromJson( $code );
        $media->comments = $comments;
        $mediaString = $this->saveInstagramData( $key, $media );
      } catch ( Exception $e ) {
        return new WP_Error( 'no_post', $e->getMessage() );
      }
    }

    if ( ! empty( $mediaString ) ) {
      return unserialize( base64_decode( $mediaString ) );
    } else {
      return new WP_Error( 'no_images', __( 'Instagram did not return any images.', 'legocreative' ) );
    }
  }

  public function linkify( $string ) {
    $string = preg_replace( '/@(\w+)(\W)?/', '<a href="https://instagram.com/${1}">@${1}</a>${2}', $string );
    $string = preg_replace( '/#(\w+)(\W)?/', '<a href="https://instagram.com/explore/tags/${1}">#${1}</a>${2}', $string );
    return $string;
  }

  public function renderPostDetail( $id ) {

    // XXX Does not allow Popup view
    echo 'Instagram has changed its privacy policy so Vckit Instagram feed disable Popup mode for now.';
    die;

    $instagram = $this->scrapePost( $id );

    $output = '<div class="ea-in-poup-content">';

    if ( 'video' == $instagram->type ) {
      $output .= '<div class="ea-in-image">';
      $output .= '<video controls autoplay src="' . $instagram->videoStandardResolutionUrl . '" poster="' . $instagram->imageHighResolutionUrl . '" />';
      $output .= '</div>';
    } else {
      $output .= '<figure class="ea-in-image">';
      $output .= '<img src="' . $instagram->imageHighResolutionUrl . '"/>';
      $output .= '</figure>';
    }
    $output .= '<div class="ea-in-info">';
    $output .= '<div class="ea-in-info-origin">';
    $output .= '<a class="ea-in-info-author" href="https://instagram.com/' . $instagram->owner->username . '">';
    $output .= '<img src="' . $instagram->owner->profilePicUrl . '" />';
    $output .= '<span>' . $instagram->owner->username . '</span>';
    $output .= '</a>';
    $output .= '<a class="ea-in-info-original" href="https://instagram.com/p/' . $id . '">' . __( 'View in Instagram', 'legocreative' ) . '</a>';
    $output .= '</div>';
    $output .= '<div class="ea-in-info-meta">';
    $output .= '<span class="ea-in-info-meta-item">';
    $output .= '<i class="fa fa-heart-o"></i>' . $instagram->likesCount;
    $output .= '</span>';
    $output .= '<span class="ea-in-info-meta-item">';
    $output .= '<i class="fa fa-comment-o"></i>' . $instagram->commentsCount;
    $output .= '</span>';

    if ( isset( $instagram->locationId ) ) {
      $output .= '<span class="ea-in-info-meta-item ea-in-info-meta-location">';
      $output .= '<i class="fa fa-map-marker"></i>' . $instagram->locationName;
      $output .= '</span>';
    }

    if ( isset( $instagram->date ) ) {
      $output .= '<span class="ea-in-info-meta-time">';
      $output .= ea_instagram_elapsed_string( $instagram->date );
      $output .= '</span>';
    }

    $output .= '</div>';
    $output .= '<div class="ea-in-info-content">';
    $output .= '<div class="ea-in-info-description">' . $this->linkify( $instagram->caption ) . '</div>';
    $output .= '<div class="ea-in-info-comments">';

    if ( $instagram->comments ) {
      foreach ( $instagram->comments as $comment ) {
        $output .= '<div class="ea-in-info-comment">';
        $output .= '<a class="ea-in-info-comment-author" href="https://instagram.com/' . $comment->owner->username . '">' . $comment->owner->username . '</a>&nbsp;';
        $output .= $this->linkify( $comment->text );
        $output .= '</div>';
      }
    }
    $output .= '</div>';
    $output .= '</div>';
    $output .= '</div>';
    $output .= '</div>';

    echo $output; // @codingStandardsIgnoreLine
    die();
  }
}

if ( class_exists( 'WPBakeryShortCode' ) ) {
  class WPBakeryShortCode_Vckit_Instagram_Feed extends WPBakeryShortCode {}
}
