<?php //Custom Post :: Video Gallery

//Custom Post Type for Manual Videos
function register_video_gallery_post_type() {
	$labels = array(
        'name'                => __('YouTube Videos', 'kipya' ),
        'add_new_item'        => __( 'New Video', 'kipya' ),
        'add_new'             => __( 'New Video', 'kipya' ),
        'edit_item'           => __( 'Edit Video', 'kipya' ),
        'update_item'         => __( 'Update Video', 'kipya' ),
        'all_items'           => __( 'All Videos', 'kipya' ),
        'search_items'        => __( 'Search', 'kipya' ),
        'singular_name'       => __('Video'),
        'not_found'           => __( 'No Videos found.', 'kipya' ),
        'not_found_in_trash'  => __( 'No Videos found in Trash.', 'kipya' )
    );

    $supports = array(
        'title',
        'excerpt',
    );

    $args = array(
        'labels'              => $labels,
        'description'         => 'For all Videos',
        'supports'            => $supports,
        'hierarchical'        => false,
        'public'              => true,
        'show_ui'             => true,
        'show_in_menu'        => true,
        'show_in_admin_bar'   => true,
        'menu_position'       => 10,
        'menu_icon'           => 'dashicons-controls-skipback',
        'can_export'          => true,
        'has_archive'         => true,
		'show_in_rest' 		  => true,
        'exclude_from_search' => false,
        'capability_type'     => 'post',
        //'register_meta_box_cb' => 'add_custom_meta_boxes_Videos',
    );
    register_post_type('youtube_videos', $args);  
    register_video_category_taxonomy(); 
}
add_action('init', 'register_video_gallery_post_type');

//Video Categories Taxonomy
function register_video_category_taxonomy() {
    register_taxonomy('video_category', ['youtube_videos'], array(
        'label' => 'Video Categories',
        'rewrite' => ['slug' => 'video-category'],
        'hierarchical' => true,
        'show_in_rest' => true,
    ));
}
add_action('init', 'register_video_category_taxonomy');

//Custom Meta Box for Video Link
function add_video_link_meta_box() {
    add_meta_box(
        'video_link_meta',
        'Video Link (YouTube Embed URL)',
        'render_video_link_meta_box',
        'youtube_videos',
        'normal',
        'default'
    );
}
add_action('add_meta_boxes', 'add_video_link_meta_box');

function render_video_link_meta_box($post) {
    $video_link = get_post_meta($post->ID, '_video_link', true);
    wp_nonce_field('save_video_link', 'video_link_nonce');
    echo '<input type="text" name="video_link" value="' . esc_attr($video_link) . '" style="width:100%;" placeholder="https://www.youtube.com/embed/VIDEO_ID">';
}

function save_video_link_meta_box($post_id) {
    if (!isset($_POST['video_link_nonce']) || !wp_verify_nonce($_POST['video_link_nonce'], 'save_video_link')) return;
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;

    if (isset($_POST['video_link'])) {
        update_post_meta($post_id, '_video_link', esc_url_raw($_POST['video_link']));
    }
}
add_action('save_post', 'save_video_link_meta_box');




/** =================================================================
 *  SHORTCODE - Partners - Home PAGE
 *===================================================================*/
function youtube_videos_shortcode($atts) {
    $atts = shortcode_atts(array(
        'category' => '',
        'number' => 5,
    ), $atts, 'yvideos');

    $args = array(
        'post_type' => 'youtube_videos',
        'posts_per_page' => $atts['number'],
    );

    if (!empty($atts['category'])) {
        $args['tax_query'] = array(array(
            'taxonomy' => 'video_category',
            'field' => 'slug',
            'terms' => $atts['category']
        ));
    }

    $query = new WP_Query($args);
    ob_start();

    if ($query->have_posts()) {
        $videos = [];

        while ($query->have_posts()) {
            $query->the_post();
            $videos[] = array(
                'title' => get_the_title(),
                'link' => get_post_meta(get_the_ID(), '_video_link', true),
                'excerpt' => get_the_excerpt(),
            );
        }

        if (!empty($videos)) {
            ?>
            <div class="video-gallery">
                <div class="video-main">
                    <iframe id="main-video-frame" width="100%" height="400" src="<?php echo esc_url($videos[0]['link']); ?>" frameborder="0" allowfullscreen></iframe>
                    <div class="video-details" id="video-details">
                        <h3><?php echo esc_html($videos[0]['title']); ?></h3>
                        <p><?php echo esc_html($videos[0]['excerpt']); ?></p>
                    </div>
                </div>

                <div class="video-thumbnails">
                    <?php foreach ($videos as $index => $video) : ?>
                        <div class="thumbnail" 
                             data-link="<?php echo esc_url($video['link']); ?>"
                             data-title="<?php echo esc_attr($video['title']); ?>"
                             data-excerpt="<?php echo esc_attr($video['excerpt']); ?>">
                            <iframe width="160" height="90" src="<?php echo esc_url($video['link']); ?>?rel=0&modestbranding=1" frameborder="0" allowfullscreen></iframe>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <script>
                document.querySelectorAll('.video-thumbnails .thumbnail').forEach((thumb) => {
                    thumb.addEventListener('click', function () {
                        const videoSrc = this.getAttribute('data-link');
                        const videoTitle = this.getAttribute('data-title');
                        const videoExcerpt = this.getAttribute('data-excerpt');

                        document.getElementById('main-video-frame').src = videoSrc;
                        document.querySelector('#video-details h3').textContent = videoTitle;
                        document.querySelector('#video-details p').textContent = videoExcerpt;
                    });
                });
            </script>

            <style>
            .video-gallery {
                max-width: 960px;
                margin: 0 auto;
                padding: 1rem;
                font-family: "Segoe UI", sans-serif;
            }

            .video-main {
                position: relative;
                margin-bottom: 1rem;
            }

            .video-main iframe {
                width: 100%;
                height: 450px;
                border: none;
                border-radius: 10px;
                box-shadow: 0 5px 15px rgba(0,0,0,0.2);
            }

            .video-details {
                margin-top: 10px;
                padding: 0.5rem;
            }

            .video-details h3 {
                font-size: 1.2rem;
                margin-bottom: 0.4rem;
                color: #111;
            }

            .video-details p {
                color: #666;
                font-size: 0.95rem;
                line-height: 1.4;
            }

            .video-thumbnails {
                display: flex;
                flex-wrap: wrap;
                gap: 0.75rem;
                justify-content: center;
            }

            .video-thumbnails .thumbnail {
                cursor: pointer;
                transition: transform 0.2s ease;
                border-radius: 6px;
                overflow: hidden;
                flex: 0 0 auto;
            }

            .video-thumbnails .thumbnail:hover {
                transform: scale(1.05);
            }

            .video-thumbnails iframe {
                width: 160px;
                height: 90px;
                border: none;
                border-radius: 6px;
                pointer-events: none; /* Prevent play button from intercepting click */
                box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            }

            /* Responsive */
            @media (max-width: 768px) {
                .video-main iframe {
                    height: 240px;
                }

                .video-thumbnails iframe {
                    width: 100px;
                    height: 60px;
                }
            }
            </style>
            <?php
        }
    }

    wp_reset_postdata();
    return ob_get_clean();
}
add_shortcode('yvideos', 'youtube_videos_shortcode');