<?php
/**
 * Yt_EVL_Videos_List
 * 
 * Creates a list of videos within Video Search and Your Channels / Playlists
 * 
 * @package Yt_Evolution
 * @subpackage Classes
 * @author  Chris Derenberger <https://www.ytevolution.com>
 * @copyright Copyright 2020, YTEVOLUTION®
 * @link https://www.ytevolution.com
 * @since 1.0.0
 */
 
 

class Yt_EVL_Videos_List {
  
  public static $instance;
  
  public static function init() {
      if ( is_null( self::$instance ) )
          self::$instance = new Yt_EVL_Videos_List();
      return self::$instance;
  }
      
  
  // Constructor    
  function __construct() {    

    require_once plugin_dir_path( __DIR__ ) . 'lib/transcript-api/vendor/autoload.php';

    //add_filter('manage_posts_columns' , array( $this, 'add_video_url_admin_column' ) );
    //add_filter('manage_posts_custom_column' , array( $this, 'manage_video_url_admin_column' ), 10, 2 );

    add_action('update_option_ytevo_transcript_client_id', array( $this, 'remove_token_file' ), 10, 3);
    add_action('update_option_ytevo_transcript_client_sceret', array( $this, 'remove_token_file' ), 10, 3);
      
  }

 
  // Add a column for the Video oEmbed URL in admin (NOT USED)
  function add_video_url_admin_column($columns) {
    return array_merge($columns,
        array(
          'tube_video_oembed_url' => __('YT Video', 'yt-revolution'),
        )
     );
  }
  
  
   
  // Populate the Video oEmbed URL column in admin (NOT USED)
  function manage_video_url_admin_column( $column, $post_id ) {
    
    switch ( $column ) {
   
      case 'tube_video_oembed_url' :
        
          $tube_video_oembed_url = get_post_meta($post_id, 'tube_video_oembed_url', true);
        
          $tube_video_creator_name = get_post_meta($post_id, 'tube_video_creator_name', true);
          
          if ( $tube_video_oembed_url ):
            
            echo '<a href="' . esc_url($tube_video_oembed_url) . '">' . esc_url($tube_video_oembed_url) . '</a><br />';
            
            echo esc_html($tube_video_creator_name);
            
          endif;
          
          break;
    }
      
  }
  
  function get_youtube_object($videoId){
    // $OAUTH2_CLIENT_ID = '250098806260-1vp0mfmgg5khn9p9lpkk19gkcb1oadch.apps.googleusercontent.com';
    // $OAUTH2_CLIENT_SECRET = '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';



    $OAUTH2_CLIENT_ID = get_option('ytevo_transcript_client_id');
    $OAUTH2_CLIENT_SECRET = get_option('ytevo_transcript_client_sceret');

    $client = new Google_Client();
    $client->setClientId($OAUTH2_CLIENT_ID);
    $client->setClientSecret($OAUTH2_CLIENT_SECRET);

    $client->setAccessType ("offline");
    $client->setApprovalPrompt ("force");


    $client->setScopes('https://www.googleapis.com/auth/youtube.force-ssl');
    //$url = site_url().'/wp-admin/post.php?post=455&action=edit'; 
    
    $url = admin_url('admin.php?page=yt-evolution-settings&tab=transcriptsetting');

    $redirect = filter_var($url);
    
    $client->setRedirectUri($redirect);

    $youtube = new Google_Service_YouTube($client);

    $credentialsPath = $upload_dir['basedir'] . '/yt-token/yt.json';

    if (file_exists($credentialsPath)) {
      $credentials_url = $upload_dir['baseurl'] . '/yt-token/yt.json';
      $json_accessToken = wp_remote_get($credentials_url);
      $token_obj = json_decode($json_accessToken['body']);
      
      $accessToken = (array) $token_obj;
    }
    

    $client->setAccessToken($accessToken);

    try{
      $captions = self::listCaptions($youtube, $videoId, $htmlBody);
      return $captions;
    }catch (Google_Service_Exception $e) {
      // echo  sprintf('<p>A service error occurred: <code>%s</code></p>',
      //     htmlspecialchars($e->getMessage()));
    } catch (Google_Exception $e) {
      // echo  sprintf('<p>An client error occurred: <code>%s</code></p>',
      //     htmlspecialchars($e->getMessage()));
    }

    
  }

  function get_error_transcript($err){
    echo esc_html($err);
  }

  /* Get transcript from video */
  function listCaptions(Google_Service_YouTube $youtube, $videoId, &$htmlBody) {

      $captions = $youtube->captions->listCaptions("snippet", $videoId);
      
      if(isset($captions->items[0]['id'])){
        $captionId = $captions->items[0]['id'];
        $list =  self::downloadCaption($youtube, $captionId, $htmlBody);
        return $list;
      }else{
        return self::get_error_transcript('Transcript not found on this video');
      }
      
  }

  function downloadCaption(Google_Service_YouTube $youtube, $captionId, &$htmlBody) {
    // Call the YouTube Data API's captions.download method to download an existing caption.

   // try {
      
      $captionResouce = $youtube->captions->download($captionId, array(
        'tfmt' => "srt",
        'alt' => "media"
      ));
      return $response = $captionResouce->getBody()->getContents();

    /*} catch(Exception $e) {
        echo "error";
    }*/

  }

   
  function show_videos_list( $videos, $site ){ 
    $en_arfo =  get_option('ytevo_transcript_enable_option');
    
    $source_post_id = get_the_id();  
    $termids = NULL;

    if($source_post_id != NULL){
      $source_term_ids = get_post_meta( $source_post_id, 'tube_source_term_ids', true );
      
      if(!empty($source_term_ids)){
        $termids = implode(',', $source_term_ids);
      }
    }   
    
    global $tube_video_curator;
      
    $existing_ids = $tube_video_curator -> get_external_video_ids( $site ) ;
    ?>
        
    <div class="tube-admin-list-videos">
      <?php 
      
      foreach ( $videos as $video ): 
        
        $existing_video_data = array();
        $existing_video_data['status'] = 'new';
          
        if ( array_key_exists($video['id'], $existing_ids) ): 
              $existing_video_data = $existing_ids[ $video['id'] ];
        endif;
          
        $video_date_raw = $video['date'];
        
        $date_format = get_option('date_format');
      
        $time_format = get_option('time_format');          
      
        // uses custom function in functions-formatting
        try {
         $wordpress_timezone = new DateTimeZone( $this -> get_timezone_string() );
        } catch(Exception $e) {
          //  echo $e->getMessage() . '<br />';
        }
          
        
        $captions = '';
        if($en_arfo){
          //kkh
         // $captions = self::get_youtube_object($video['id']);
        }
         

         $trans_text = '';
         if(!empty($captions)){
            $trans_text = $captions;
         }

        $trans_arr = explode(',', $trans_text);
        $trans_merge = '';
        foreach ($trans_arr as $key => $value) {
           if($key != 0 && $key != 1){
            $trans_merge .= $value;
           }
         }

         $trans_text = preg_replace('/[0-0]+/', '', $trans_merge);


          //$trans_text = 'This is transcript';
    
          // create a $dt object with the UTC timezone
          $dt = new DateTime($video_date_raw, new DateTimeZone('UTC'));
          
          $dt->setTimeZone( $wordpress_timezone );
          
          // format the datetime
          $video_date_formatted = $dt->format( $date_format );

          $video_time_formatted = $dt->format( $time_format );
    
          $tags = NULL;
          
          if ( array_key_exists( 'tags', $video ) && $video['tags'] ):
            
            $tags = implode(',', $video['tags']);
            
          endif;
          
         //$video_date_formatted =  date( get_option( 'date_format' ), strtotime($video['date']) );
         $skip_desc = get_option('tube_vc_default_restrict_desc');
         
         $video_description_truncated =  wp_trim_words( $video['content'], 40 );
         if($skip_desc) $video_description_truncated = '';
             
              switch ($existing_video_data['status']) {
                case 'skipped':
                  $video_label = __( 'SKIPPED', 'yt-revolution' );
                  $video_label_class = 'text-highlight';
                  break;
                  
                case 'pending':
                  $video_label = __( 'PENDING', 'yt-revolution' );
                  $video_label_class = 'text-highlight';
                  break;
                  
                case 'draft':
                  $video_label = __( 'DRAFT', 'yt-revolution' );
                  $video_label_class = 'text-highlight';
                  break;
                  
                case 'publish':
                  $video_label = __( 'PUBLISHED', 'yt-revolution' );
                  $video_label_class = 'text-notification';
                  break;
                
                default:
                  
                  $video_label = NULL;                  
                  break;
              }
              
        ?>
        <div class="result video-status-<?php echo sanitize_html_class($existing_video_data['status']); ?>">
          <div class="tube-video-thumbnail">
            
            <img src="<?php echo esc_url( $video['thumb_image_url'] ); ?>" class="thumbnail" alt="" width="150" />
            
          </div>
          <div class="tube-video-summary">
              
            <p class="video-title">  
            
              <?php if (  $video_label ): ?>
                <strong class="wp-ui-<?php echo sanitize_html_class( $video_label_class ); ?>">[<?php echo esc_html( $video_label ); ?>]</strong>                
              <?php endif; ?>
                <a href="<?php echo esc_url( $video['media_url'] ); ?>" target="_blank"><strong><?php echo esc_html( $video['title'] ); ?></strong></a>
            </p>
              
            <p class="video-meta description">
              <strong><?php echo esc_html( $video['creator_name'] ); ?></strong> | 
              <?php echo esc_html( $video_date_formatted ); ?> | <?php echo esc_html( $video_time_formatted ); ?>
            </p>
            <p class="video-description">
              <?php echo esc_html( $video_description_truncated ); ?>
            </p>
          </div>
          
          
          
            
          <div class="tube-video-buttons tube-video-skipped-buttons">
            <a class="button btn-restore" data-postid="<?php if ( $existing_video_data['status'] == 'skipped' ) echo esc_attr($existing_ids[ $video['id']]['id']); ?>" href="#">
              <?php _e( 'Restore', 'yt-revolution' ); ?>
            </a>                  
          </div>
            
              
          <div class="tube-video-buttons tube-video-published-buttons">
                  
            <a  class="btn-view button" href="<?php if ( ( $existing_video_data['status'] == 'publish' ) || ( $existing_video_data['status'] == 'draft' ) ) echo esc_attr($existing_video_data['permalink']); ?>">
              <?php _e( 'View', 'yt-revolution' ); ?>                    
            </a>  
                            
            <br /> 
                           
            <a  class="btn-edit" href="<?php if ( ( $existing_video_data['status'] == 'publish' ) || ( $existing_video_data['status'] == 'draft' ) ) echo esc_attr($existing_video_data['edit']); ?>">
              <?php _e( 'Edit', 'yt-revolution' ); ?>
            </a>
                 
          </div>
              
                
          <div class="tube-video-buttons tube-video-pending-buttons">
                
            <a  class="btn-view button" href="<?php if (  $existing_video_data['status'] == 'pending' ) echo esc_attr($existing_video_data['edit']); ?>">
              <?php _e( 'Review/Edit', 'yt-revolution' ); ?>
            </a>
            
            <br />
          
            <a  class="btn-edit" href="<?php if (  $existing_video_data['status'] == 'pending' ) echo esc_attr($existing_video_data['permalink']); ?>">
              <?php _e( 'Preview', 'yt-revolution' ); ?>
            </a>
                 
          </div>
          
              
             <div class="tube-video-buttons tube-video-new-buttons">
               
                <a publishattr="ron" data-transcript="<?php echo esc_attr($trans_text); ?>" data-site="<?php echo esc_attr($site); ?>"  data-title="<?php echo esc_attr($video['title']); ?>" data-channel-id="<?php echo esc_attr($video['channel_id']); ?>"  data-id="<?php echo esc_attr($video['id']); ?>" data-src="<?php echo esc_url($video['media_url']); ?>" data-content="<?php echo esc_attr($video['content']); ?>" data-date="<?php echo esc_attr($video['date']); ?>" data-embed-url="<?php echo esc_url($video['embed_url']); ?>" data-media-url="<?php echo esc_url($video['media_url']); ?>" data-image-url="<?php echo esc_url($video['image_url']); ?>" data-creator-name="<?php echo esc_attr($video['creator_name']); ?>"  data-term-ids="<?php echo esc_attr($termids); ?>" data-tags="<?php echo esc_attr($tags); ?>"  data-status="publish" class="btn-import btn-publish button button-primary" href="#"><?php _e( 'Publish', 'yt-revolution' ); ?>
                
                   
                </a>
                
                <br />
                
               <a data-transcript="<?php echo esc_attr($trans_text); ?>" data-site= "<?php echo esc_attr($site); ?>" data-title= "<?php echo esc_attr($video['title']); ?>" data-channel-id="<?php echo esc_attr($video['channel_id']); ?>"  data-id="<?php echo esc_attr($video['id']); ?>" data-src="<?php echo esc_url($video['media_url']); ?>" data-content="<?php echo esc_attr($video['content']); ?>" data-date="<?php echo esc_attr($video['date']); ?>" data-embed-url="<?php echo esc_url($video['embed_url']); ?>" data-media-url="<?php echo esc_url($video['media_url']); ?>" data-image-url="<?php echo esc_url($video['image_url']); ?>" data-creator-name="<?php echo esc_attr($video['creator_name']); ?>"  data-term-ids="<?php echo esc_attr($termids); ?>" data-tags="<?php echo esc_attr($tags); ?>" data-status="pending" class="btn-import btn-pending" href="#"><?php _e( 'Pending', 'yt-revolution' ); ?></a>
                
                <br />
                
               <a data-transcript="<?php echo esc_attr($trans_text); ?>" data-site= "<?php echo esc_attr($site); ?>" data-title= "<?php echo esc_attr($video['title']); ?>" data-channel-id="<?php echo esc_attr($video['channel_id']); ?>"  data-id="<?php echo esc_attr($video['id']); ?>" data-src="<?php echo esc_url($video['media_url']); ?>" data-content="<?php echo esc_attr($video['content']); ?>" data-date="<?php echo esc_attr($video['date']); ?>" data-embed-url="<?php echo esc_url($video['embed_url']); ?>" data-media-url="<?php echo esc_url($video['media_url']); ?>" data-image-url="<?php echo esc_url($video['image_url']); ?>" data-creator-name="<?php echo esc_attr($video['creator_name']); ?>"   data-term-ids="<?php echo esc_attr($termids); ?>" class="btn-skip" href="#"><?php _e( 'Skip', 'yt-revolution' ); ?></a>
               
              </div>
          
        </div> <!-- .result --> 
      <?php endforeach; ?>        
    </div>

  <?php
  }

  

  /**
   * https://www.skyverge.com/blog/down-the-rabbit-hole-wordpress-and-timezones/
   *
   * Returns the timezone string for a site, even if it's set to a UTC offset
   *
   * Adapted from http://www.php.net/manual/en/function.timezone-name-from-abbr.php#89155
   *
   * @return string valid PHP timezone string
   */
  
  function get_timezone_string()
  {
  
    // if site timezone string exists, return it  
    if ($timezone = get_option('timezone_string')) return $timezone;
  
    // get UTC offset, if it isn't set then return UTC  
    if (0 === ($utc_offset = get_option('gmt_offset', 0))) return 'UTC';
  
    // adjust UTC offset from hours to seconds  
    $utc_offset*= 3600;
  
    // attempt to guess the timezone string from the UTC offset  
    if ($timezone = timezone_name_from_abbr('', $utc_offset, 0)) {
      return $timezone;
    }
  
    // last try, guess timezone string manually  
    $is_dst = date('I');
    foreach(timezone_abbreviations_list() as $abbr) {
      foreach($abbr as $city) {
        if ($city['dst'] == $is_dst && $city['offset'] == $utc_offset) return $city['timezone_id'];
      }
    }
  
    // fallback to UTC  
    return 'UTC';
  }

  /* Remove token file when update or change client id */
  function remove_token_file($option_name, $old_value, $new_value){
    $credentialsPath = plugin_dir_path( __DIR__ ) . 'token/yt.json';
    if(file_exists($credentialsPath)){
      unlink($credentialsPath);
    }
  }

}