<?php

/*
Plugin Name: Embed Peertube Playlist
Plugin URI: 
Version: 1.04
Description: Display Peertube playlists
Author: Manu225
Author URI: 
Network: false
Text Domain: embed-peertube-playlist
Domain Path: 
*/


register_activation_hook( __FILE__, 'playlist_peertube_install' );
register_uninstall_hook(__FILE__, 'playlist_peertube_desinstall');

function playlist_peertube_install() {

	global $wpdb;

	$playlist_peertube_table = $wpdb->prefix . "playlists_peertube";

	require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

	$sql = "
        CREATE TABLE `".$playlist_peertube_table."` (
          id int(11) NOT NULL AUTO_INCREMENT,
          name varchar(50) NOT NULL,          
          playlist_id varchar(50) NOT NULL,
          show_title int(1) NOT NULL,
          show_description int(1) NOT NULL,
          template int(11) NOT NULL,
          text_size int(3) NOT NULL,
          text_color varchar(20) NOT NULL,
          desc_text_color varchar(20) NOT NULL,
          bg_color varchar(20) NOT NULL,
          PRIMARY KEY  (id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
    ";

    dbDelta($sql);

}

function playlist_peertube_desinstall() {

	global $wpdb;

	$playlist_peertube_table = $wpdb->prefix . "playlists_peertube";

	//suppression des tables
	$sql = "DROP TABLE ".$playlist_peertube_table.";";
	$wpdb->query($sql);
}

add_action( 'admin_menu', 'register_playlist_peertube_menu' );

function register_playlist_peertube_menu() {

	add_menu_page('Peertube Playlists', 'Peertube Playlists', 'edit_pages', 'playlists_peertube', 'playlists_peertube', plugins_url('images/logo.svg', __FILE__), 32);
	add_submenu_page( 'playlists_peertube', 'Settings for Peertube Playlist', 'Settings', 'manage_options', 'playlist-pt-settings', 'playlist_peertube_settings' );
	//call register settings function
	add_action( 'admin_init', 'register_playlist_peertube_settings' );

}

add_action('admin_print_styles', 'playlist_peertube_css' );
function playlist_peertube_css() {
    wp_enqueue_style( 'PlaylistPTStylesheet', plugins_url('css/admin.css', __FILE__) );
    wp_enqueue_style( 'wp-color-picker' );
}

add_action( 'admin_enqueue_scripts', 'playlist_peertube_admin_script' );
function playlist_peertube_admin_script() {
    wp_enqueue_script( 'wp-color-picker');
}

function register_playlist_peertube_settings() {
	//register our settings
	add_option( 'pl_peertube_url', 'https://peertube.fr');
}

function playlist_peertube_settings(){

	//formulaire soumis ?
	if(sizeof($_POST))
	{
		check_admin_referer( 'pl_peertube_settings' );		
		$url = sanitize_text_field($_POST['pl_peertube_url']);
		update_option('pl_peertube_url', $url);

	}
	else
		$type = get_option('nice_page_transition_type');
	include(plugin_dir_path( __FILE__ ) . 'views/settings.php');

}

function playlists_peertube() {

	if (is_admin()) {

		global $wpdb;

		$playlist_peertube_table = $wpdb->prefix . "playlists_peertube";


		if(sizeof($_POST) > 0)
		{
			$playlist_id = sanitize_key($_POST['playlist_id']);

			if(empty($_POST['name']) || empty($_POST['playlist_id']))
				echo '<h2>You must enter a name and the ID of the Peertube playlist!</h2>';
			else if(strlen($playlist_id) != 36)
				echo '<h2>Playlist ID isn\'t right. Must be like this: 009bc84a-00f3-4c60-b2a9-4694a62eb7b3</h2>';
			else if(!is_numeric($_POST['text_size']))
				echo '<h2>Text size must be a number</h2>';
			else if(!is_numeric($_POST['id'])) //nouvelle playlist
			{
				check_admin_referer( 'new_pl_peertube' );
				$show_title = 1;
				$show_description = isset($_POST['show_description']) ? 1 : 0;
				$desc_text_color = "#ffffff";
				$bg_color = "rgba(0, 0, 0, 0.7)";

				$query = $wpdb->prepare( "INSERT INTO ".$playlist_peertube_table." (`name`, `playlist_id`, `template`, `text_size`, `text_color`, `desc_text_color`, `bg_color`, `show_title`, `show_description`) VALUES (%s, %s, %d, %d, %s, %s, %s, %d, %d)", sanitize_text_field($_POST['name']), $playlist_id, 'grid', (int)$_POST['text_size'], sanitize_hex_color($_POST['text_color']), $desc_text_color, $bg_color, $show_title, $show_description);
				$wpdb->query($query);
			}
			else //mise à jour d'une playlist
			{
				check_admin_referer( 'update_pl_peertube_'.$_POST['id'] );
				$show_title = isset($_POST['show_title']) ? 1 : 0;
				$show_description = isset($_POST['show_description']) ? 1 : 0;
				$query = $wpdb->prepare( "UPDATE ".$playlist_peertube_table." SET `name` = %s, `playlist_id` = %s, `template` = %d, `text_size` = %d, `text_color` = %s, `show_description` = %d WHERE id = %d",
				sanitize_text_field($_POST['name']), $playlist_id, 'grid', (int)$_POST['text_size'], sanitize_hex_color($_POST['text_color']), $show_description, (int)$_POST['id'] );
				$wpdb->query($query);
			}
		}
			
		//on récupère toutes les cards
		$playlists = $wpdb->get_results("SELECT * FROM ".$playlist_peertube_table);
		include(plugin_dir_path( __FILE__ ) . 'views/playlists.php');
	}
}

//Ajax : suppression d'une playlist
add_action( 'wp_ajax_remove_playlist_peertube', 'remove_playlist_peertube_callback' );

function remove_playlist_peertube_callback() {

	check_ajax_referer( 'remove_playlist_peertube' );

	if (is_admin()) {

		global $wpdb;

		$playlist_peertube_table = $wpdb->prefix . "playlists_peertube";

		if(is_numeric($_POST['id']))
		{
			//supprime toutes les images
			$query = $wpdb->prepare( 
				"DELETE FROM ".$playlist_peertube_table."
				 WHERE id=%d", $_POST['id']
			);
			$res = $wpdb->query( $query	);
			
		}
		wp_die();
	}
}

add_shortcode('playlist_peertube', 'display_playlist_peertube');
function display_playlist_peertube($atts) {

	$peertube_url = get_option('pl_peertube_url');
	$peertube_url = 'https://peertube.hatthieves.es';

	if(empty($peertube_url))
		return '<strong>You need to set your Peertube instance url in the <a href="'.admin_url( 'admin.php?page=playlist-pt-settings') .'">settings</a> to use Peertube Playlist</strong>';

	if(is_numeric($atts['id']))
	{

		global $wpdb;

		$playlist_peertube_table = $wpdb->prefix . "playlists_peertube";
		$query = "SELECT * FROM ".$playlist_peertube_table." WHERE id = %d";
		$query = $wpdb->prepare( $query, $atts['id'] );
		$playlist = $wpdb->get_row($query);

		if($playlist)
		{
				//on inclut jquery
				wp_enqueue_script( 'jquery' );	

				$apiURL = "/api/v1";		

				$url = $peertube_url.$apiURL."/video-playlists/".$playlist->playlist_id."/videos";
				$response = wp_remote_get( $url );
				$json = wp_remote_retrieve_body( $response );

				if(!empty($json))
				{
					$data = json_decode($json);

					if($data)
					{

						if(!isset($data->error) && !isset($data->errors))
						{
							wp_enqueue_style( 'playlist_peertube_grid_css', plugins_url( 'css/grid.css', __FILE__ ));
							$view = plugin_dir_path( __FILE__ ) . 'views/grid.php';
							
							ob_start();
							include( $view );
							$playlist_html = ob_get_clean();

							return $playlist_html;
						}
						else
						{
							$error_msg = 'Error retrieve playlist from Peertube API on instance '.$peertube_url.' (you change this in the Peertube Playlist settings)<br />';
							if(!empty($data->error))
								$error_msg .= 'API error: '.$data->error.'<br />';
							else
								$error_msg .= 'API errors: '.print_r($data->errors, true).'<br />';
							return $error_msg;
						}

					}
					else
						return 'Error convert JSON data';
				}
				else
					return 'Error retrieve playlist from Peertube API on instance '.$peertube_url.' (you change this in the Peertube Playlist settings)';
		}
		else
			return "Error : Peertube playlist id ".$atts['id'].' not found !';

	}
	else
		return 'Missing playlist ID!';

}

add_action( 'wp_enqueue_scripts', function() {	wp_enqueue_script( 'jquery' ); });	
