<?php
if ( ! class_exists( 'IPVisc_Viewer' ))
{
  /**
   * Viewer class
   *
   * @package wp-video-attention
   * @author InstaProduct
   * @link http://insta-product.com/
   */

  class IPVisc_Viewer
  {
    //{{ dashboard

    /**
     * Manage page viewer
     *
     * @return void
     */
    public function dashboard()
    {
      //Render view
      $this->pageId = IPVISC_PAGENAME;
      $this->view( 'manage/dashboard' );
    }

    //}}
    //{{ addnew

    /**
     * Add new page viewer
     *
     * @return void
     */
    public function addnew()
    {
      $this->manage();
    }

    //}}
    //{{ edit

    /**
     * Edit page viewer
     *
     * @return void
     */
    public function edit()
    {
      if ( empty( $_GET['id'] )) {
        wp_die( __('You attempted to edit an item that doesn&#8217;t exist. Perhaps it was deleted?', IPVISC_SLUG ) );
      }
      $id = absint( $_GET['id'] );
      if ( ! $video = get_post( $id ) ) {
        wp_die( __('You attempted to edit an item that doesn&#8217;t exist. Perhaps it was deleted?', IPVISC_SLUG ) );
      }
      $this->manage( $video );
    }

    //}}
    //{{ manage

    /**
     * Manage page viewer
     *
     * @param object $video
     * @return void
     */
    public function manage( $video = false )
    {
      //
      //Including script
      wp_enqueue_media();
      wp_enqueue_script('wp-color-picker');
      wp_enqueue_style('wp-color-picker');

      $videoId = 0;
      if ( $video ) {
        $videoId = $video->ID;
      }
      $setting    = new IPVisc_Setting( $videoId, '__ipvisc-setting' );
      $formAction = admin_url( 'admin-ajax.php' ) . '?doajax=1&ipvisc=1&action=update';

      if ( $video )
      {
        $pageTitle   = __( 'Edit Video', IPVISC_SLUG );
        $submitLabel = __( 'Save Change', IPVISC_SLUG );
        $submitId    = 'ipvisc-edit-video';
        $formId      = 'ipvisc-form-update';
        $submitIcon  = 'floppy-o';
        $pageId      = IPVISC_PAGENAME;

      } else
      {
        $pageTitle   = __( 'Add Video', IPVISC_SLUG );
        $submitLabel = __( 'Add Video', IPVISC_SLUG );
        $submitId    = 'ipvisc-add-video';
        $formId      = 'ipvisc-form-add';
        $submitIcon  = 'plus-circle';
        $pageId      = IPVISC_PAGENAME . '-addnew';
      }
      $this->pageId      = $pageId;
      $this->pageTitle   = $pageTitle;
      $this->submitLabel = $submitLabel;
      $this->submitId    = $submitId;
      $this->formId      = $formId;
      $this->submitIcon  = $submitIcon;
      $this->setting     = $setting;
      $this->video       = $video;
      $this->videoId     = $videoId;
      $this->formAction  = $formAction;
      $this->styles      = $this->_getStyles();

      $tab = 'ipvisc-section-general';
      if ( ! empty( $_REQUEST['tab'] )) {
        $tab = $_REQUEST['tab'];
      }
      $this->tab = $tab;

      //Render view
      $this->view( 'manage/main' );
    }

    //}}
    //{{ style

    /**
     * Manage style page viewer
     *
     * @return void
     */
    public function style()
    {
      //Render view
      $this->pageId = IPVISC_PAGENAME . '-style';
      $this->view( 'style/dashboard' );
    }

    //}}
    //{{ addStyle

    /**
     * Add new style page viewer
     *
     * @return void
     */
    public function addStyle()
    {
      $this->manageStyle();
    }

    //}}
    //{{ editStyle

    /**
     * Edit style page viewer
     *
     * @return void
     */
    public function editStyle()
    {
      if ( empty( $_GET['id'] )) {
        wp_die( __('You attempted to edit an item that doesn&#8217;t exist. Perhaps it was deleted?', IPVISC_SLUG ) );
      }
      $id = absint( $_GET['id'] );
      if ( ! $style = get_post( $id ) ) {
        wp_die( __('You attempted to edit an item that doesn&#8217;t exist. Perhaps it was deleted?', IPVISC_SLUG ) );
      }
      $this->manageStyle( $style );
    }

    //}}
    //{{ manageStyle

    /**
     * Manage style page viewer
     *
     * @param object $style
     * @return void
     */
    public function manageStyle( $style = false )
    {
      //
      //Including script
      wp_enqueue_media();
      wp_enqueue_script('wp-color-picker');
      wp_enqueue_style('wp-color-picker');

      $styleId = 0;
      if ( $style ) {
        $styleId = $style->ID;
      }
      $setting    = new IPVisc_Setting( $styleId, '__ipvisc-style-setting' );
      $formAction = admin_url( 'admin-ajax.php' ) . '?doajax=1&ipvisc=1&action=update_style';
      if ( $style )
      {
        $pageTitle   = __( 'Edit Style', IPVISC_SLUG );
        $submitLabel = __( 'Save Change', IPVISC_SLUG );
        $submitId    = 'ipvisc-edit-style';
        $formId      = 'ipvisc-form-style-update';
        $submitIcon  = 'floppy-o';
        $pageId      = IPVISC_PAGENAME . '-style';

      } else
      {
        $pageTitle   = __( 'Add Style', IPVISC_SLUG );
        $submitLabel = __( 'Add Style', IPVISC_SLUG );
        $submitId    = 'ipvisc-add-style';
        $formId      = 'ipvisc-form-style-add';
        $submitIcon  = 'plus-circle';
        $pageId      = IPVISC_PAGENAME . '-style';
      }
      $this->pageId      = $pageId;
      $this->pageTitle   = $pageTitle;
      $this->submitLabel = $submitLabel;
      $this->submitId    = $submitId;
      $this->formId      = $formId;
      $this->submitIcon  = $submitIcon;
      $this->setting     = $setting;
      $this->style       = $style;
      $this->styleId     = $styleId;
      $this->formAction  = $formAction;

      $tab = 'ipvisc-section-general';
      if ( ! empty( $_REQUEST['tab'] )) {
        $tab = $_REQUEST['tab'];
      }
      $this->tab = $tab;

      //Render view
      $this->view( 'style/main' );
    }

    //}}
    //{{ shortcodeBackend

    /**
     * Shortcode Backend viewer
     *
     * @return void
     */
    public function shortcodeBackend()
    {
      $this->videos = $this->_getVideos();
      //Render view
      $this->view( 'shortcode/backend/main' );
    }

    //}}
    //{{ shortcode

    /**
     * Shortcode frontend viewer
     *
     * @param array  $atts
     * @param string $content
     * @return void
     */
    public function shortcode( $atts, $content = '' )
    {
      global $user_ID;
      if ( empty( $atts['video'] )) {
        return '';
      }
      //
      //Get video
      $videoId = absint( $atts['video'] );
      if ( ! $video = get_post( $videoId )) {
        return '';
      }
      $setting = new IPVisc_Setting( $videoId, '__ipvisc-setting' );

      //
      //Render view
      $isPublish  = ($video->post_status == 'publish');
      $restricted = false;
      $restValue  = $setting->getSetting( 'restricted', 'false' );
      if ( $restValue == 'true' )
      {
          if ( empty( $user_ID )) {
              $restricted = true;
          }
      }
      $output = '';
      if ( $isPublish && ! $restricted )
      {
        //
        //Set variables
        $this->videoPost = $video;
        $this->setting   = $setting;

        //
        //Widget style
        $style   = false;
        $styleId = $setting->getSetting( 'widget_style', 0 );
        if ( ! empty( $styleId )) {
          $style = get_post( $styleId );
        }
        $styleSetting = new IPVisc_Setting( $styleId, '__ipvisc-style-setting' );

        $this->style        = $style;
        $this->styleSetting = $styleSetting;

        $videoCode = md5(rand( 100, 999999 )+$videoId);
        $this->videoCode = $videoCode;

        //Render view
        ob_start();
        $this->view( 'shortcode/frontend/main' );
        $output = ob_get_contents();
        ob_end_clean();
      }
      return $output;
    }

    //}}
    //{{ view

    /**
     * Get admin view file
     *
     * @param string $filename
     * @return void
     */
    public function view( $filename )
    {
      $path  = IPVISC_VIEW;
      $path .= $filename . '.php';
      if ( file_exists( $path )) {
        include( $path );
      }
    }

    //}}
    //{{ _getStyles

    /**
     * Get styles list
     *
     * @return array
     */
    protected function _getStyles()
    {
      $args = array(
        'orderby'        => 'post_title',
        'order'          => 'DESC',
        'post_type'      => 'ipvisc-style',
        'post_status'    => array('publish'),
        'posts_per_page' => -1,
        'paged'          => 1
      );
      $query   = new WP_Query;
      $videos = $query->query( $args );
      return $videos;
    }

    //}}
    //{{ _getVideos

    /**
     * Get styles list
     *
     * @return array
     */
    protected function _getVideos()
    {
      $args = array(
        'orderby'        => 'post_title',
        'order'          => 'DESC',
        'post_type'      => 'ipvisc-item',
        'post_status'    => array('publish'),
        'posts_per_page' => -1,
        'paged'          => 1
      );
      $query   = new WP_Query;
      $videos = $query->query( $args );
      return $videos;
    }

    /**
     * Fix youtube url
     *
     * @param  string $url
     * @return string
     */
    public function fix_youtube_url( $url )
    {
      if ( $url )
      {
        if ( strpos( $url, 'embed' ) === false ) {
          if ( strpos( $url, 'watch' ) !== false ) {
            $id     = '';
            $parsed = parse_url( $url );
            if ( ! empty( $parsed['query'] )) {
              parse_str( $parsed['query'], $args );
              if ( ! empty( $args['v'] )) {
                $id = $args['v'];
              }
            }
            $url = 'http://youtube.com/embed/' . $id;

          } elseif ( strpos( $url, 'youtu.be' ) !== false ) {
            $id     = '';
            $parsed = parse_url( $url );
            if ( ! empty( $parsed['path'] )) {
              $id = trim( $parsed['path'], '/' );
            }
            $url = 'http://youtube.com/embed/' . $id;

          }
        }
        $url .= '?rel=0';
      }
      return $url;
    }

    /**
     * Get video id
     *
     * @param  string $url
     * @return string
     */
    public function getVideoId( $url )
    {
        $id = '';
        if ( strpos( $url, 'embed' ) === false ) {
            if ( strpos( $url, 'watch' ) !== false ) {
                $parsed = parse_url( $url );
                if ( ! empty( $parsed['query'] )) {
                    parse_str( $parsed['query'], $args );
                    if ( ! empty( $args['v'] )) {
                        $id = $args['v'];
                    }
                }
            } elseif ( strpos( $url, 'youtu.be' ) !== false ) {
                $parsed = parse_url( $url );
                if ( ! empty( $parsed['path'] )) {
                    $id = trim( $parsed['path'], '/' );
                }
            }
        } else {
            $parsed = parse_url( $url );
            if ( ! empty( $parsed['path'] )) {
                $id = str_replace( 'embed/', '', $parsed['path'] );
            }
        }
        return $id;
    }

    //}}
    //{{ getShareLink

    /**
     * Get share link
     *
     * @param  string $type
     * @return string
     */
    public function getShareLink( $type )
    {
      $pagetitle = urlencode( get_the_title() );
      $pageurl   = urlencode( get_permalink() );
      $actions   =  array(
        'facebook'      => 'http://www.facebook.com/share.php?u=' . $pageurl,
        'twitter'       => 'https://twitter.com/share?url=' . $pageurl . '&text=' . $pagetitle,
        'google-plus'   => 'https://plusone.google.com/_/+1/confirm?hl=en&url=' . $pageurl,
        'pinterest'     => 'http://pinterest.com/pin/create/button/?url=' . $pageurl . '&media=&description=' . $pagetitle,
        'linkedin'      => 'http://www.linkedin.com/shareArticle?mini=true&url=' . $pageurl .'&title=' . $pagetitle,
        'tumblr'        => 'http://www.tumblr.com/share?v=3&u=' . $pageurl,
        'stumbleupon'   => 'http://www.stumbleupon.com/submit?url=' . $pageurl . '&title=' . $pagetitle,
        'digg'          => 'http://digg.com/submit?url=' . $pageurl . '&title=' . $pagetitle,
        'email'         => 'mailto:?subject=' . $pagetitle
      );
      $link = '#';
      if ( array_key_exists( $type, $actions )) {
        $link = $actions[$type];
      }
      return $link;
    }

    //}}
    //{{ getGoogleFontFamily

    /**
     * Get google font family name
     *
     * @param  string $name
     * @return string|false
     */
    public function getGoogleFontFamily( $name )
    {
        $family = false;
        $fonts  = IPVisc_Font::getLinks();
        if ( array_key_exists( $name, $fonts )){
            $family = $fonts[$name];
        }
        return $family;
    }

    //}}
  }
}
