<?php
/**
 * Plugin Name: Video for Tutor LMS
 * Text Domain: video-for-tutor-lms
 * Description: Add Free Course Videos in the Tutor LMS course content, enabling potential students to watch videos before purchasing the course.
 * Version: 1.0
 * Author: Anowar Hossain Rana
 * Author URI: https://cxrana.wordpress.com/
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Enqueue admin and front-end scripts and styles
function tvft_enqueue_scripts() {
    if (is_admin()) {
        wp_enqueue_script('tvft-admin-js', plugin_dir_url(__FILE__) . 'assets/js/trial-video.js', ['jquery'], '1.5', true);
        wp_enqueue_style('tvft-admin-css', plugin_dir_url(__FILE__) . 'assets/css/admin-style.css', [], '1.5');
    } elseif (is_singular('courses')) {
        wp_enqueue_script('tvft-course-js', plugin_dir_url(__FILE__) . 'assets/js/trial-video.js', ['jquery'], '1.5', true);
        wp_enqueue_style('tvft-course-css', plugin_dir_url(__FILE__) . 'assets/css/trial-video.css', [], '1.5');
    }
}
add_action('admin_enqueue_scripts', 'tvft_enqueue_scripts');
add_action('wp_enqueue_scripts', 'tvft_enqueue_scripts');

// Add meta box for free trial videos
function tvft_add_free_trial_video_meta_box() {
    add_meta_box(
        'tvft_free_trial_video',
        esc_html__('Free Course Videos', 'video-for-tutor-lms'),
        'tvft_free_trial_video_meta_box_callback',
        'courses',
        'normal',
        'high'
    );
}
add_action('add_meta_boxes', 'tvft_add_free_trial_video_meta_box');

// Meta box callback
function tvft_free_trial_video_meta_box_callback($post) {
    wp_nonce_field('tvft_save_free_trial_video', 'tvft_free_trial_video_nonce');

    $free_trial_video_data = maybe_unserialize(get_post_meta($post->ID, '_tvft_free_trial_video_data', true));
    $free_trial_video_data = is_array($free_trial_video_data) ? $free_trial_video_data : [];

    echo '<div id="tvft-video-list">';
    foreach ($free_trial_video_data as $index => $video) {
        $url = esc_url($video['url'] ?? '');
        $title = esc_attr($video['title'] ?? '');
        echo '<div class="video-input-wrapper">';
        echo '<label for="tvft_free_trial_video_url_' . esc_attr($index) . '">' . esc_html__('Free Course Video URL', 'video-for-tutor-lms') . ' ' . esc_html($index + 1) . ':</label>';
        echo '<input type="text" id="tvft_free_trial_video_url_' . esc_attr($index) . '" name="tvft_free_trial_video_urls[]" value="' . esc_url($url) . '" style="width: 100%;" placeholder="https://www.youtube.com/watch?v=your_video_id">';
        echo '<label for="tvft_free_trial_video_title_' . esc_attr($index) . '">' . esc_html__('Video Title', 'video-for-tutor-lms') . ' ' . esc_html($index + 1) . ':</label>';
        echo '<input type="text" id="tvft_free_trial_video_title_' . esc_attr($index) . '" name="tvft_free_trial_video_titles[]" value="' . esc_attr($title) . '" style="width: 100%;" placeholder="' . esc_attr__('Enter video title here', 'video-for-tutor-lms') . '">';
        echo '<button type="button" class="remove-video-button">' . esc_html__('Remove', 'video-for-tutor-lms') . '</button><br><br>';
        echo '</div>';
    }
    echo '</div>';
    echo '<button type="button" id="add-video-button">' . esc_html__('Add Video', 'video-for-tutor-lms') . '</button>';
}

// Save the meta box data
function tvft_save_free_trial_video($post_id) {
    if (!isset($_POST['tvft_free_trial_video_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['tvft_free_trial_video_nonce'])), 'tvft_save_free_trial_video')) {
        return;
    }

    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }

    if (!current_user_can('edit_post', $post_id)) {
        return;
    }

    if (isset($_POST['tvft_free_trial_video_urls'], $_POST['tvft_free_trial_video_titles']) && !empty($_POST['tvft_free_trial_video_urls'])) {
        $free_trial_video_data = [];
        foreach ($_POST['tvft_free_trial_video_urls'] as $index => $url) {
            $sanitized_url = esc_url_raw(wp_unslash($url));
            $sanitized_title = sanitize_text_field(wp_unslash($_POST['tvft_free_trial_video_titles'][$index]));
            $free_trial_video_data[] = [
                'url' => $sanitized_url,
                'title' => $sanitized_title,
            ];
        }
        update_post_meta($post_id, '_tvft_free_trial_video_data', maybe_serialize($free_trial_video_data));
    } else {
        // Delete the metadata if no inputs are present
        delete_post_meta($post_id, '_tvft_free_trial_video_data');
    }
}
add_action('save_post', 'tvft_save_free_trial_video');

// Display free trial videos above course content
function tvft_display_free_video_content() {
    global $post;
    $free_trial_video_data = maybe_unserialize(get_post_meta($post->ID, '_tvft_free_trial_video_data', true));

    if (!empty($free_trial_video_data) && is_array($free_trial_video_data)) {
        echo '<div class="free-trial-videos tutor-mt-40">';
        echo '<h3 class="tutor-fs-5 tutor-fw-bold tutor-color-black tutor-mb-24 tutor-course-content-title">' . esc_html__('Free Course Videos', 'video-for-tutor-lms') . '</h3>';
        foreach ($free_trial_video_data as $video) {
            $video_id = tvft_get_youtube_video_id($video['url']);
            if ($video_id) {
                echo '<div class="tutor-accordion-item free-video-margin">';
                echo '<h4 class="tutor-accordion-item-header" style="cursor: pointer;">' . esc_html($video['title']) . ' <span class="tvft-unlock-icon dashicons dashicons-unlock" title="' . esc_attr__('Free Content', 'video-for-tutor-lms') . '"></span></h4>';
                echo '<div class="tutor-accordion-item-body" style="display: none;">';
                echo '<iframe class="tvft-video-iframe" src="https://www.youtube.com/embed/' . esc_attr($video_id) . '?iv_load_policy=3&modestbranding=1&playsinline=1&showinfo=0&rel=0&enablejsapi=1" frameborder="0" allowfullscreen></iframe>';
                echo '</div>';
                echo '</div>';
            }
        }
        echo '</div>';
    }
}
add_action('tutor_course/single/before/topics', 'tvft_display_free_video_content');

// Helper function to extract YouTube video ID
function tvft_get_youtube_video_id($url) {
    preg_match("/(youtu\.be\/|v=|\/embed\/|\/v\/|\/watch\?v=|\&v=)([a-zA-Z0-9_-]{11})/", $url, $matches);
    return $matches[2] ?? '';
}
