<?php
/**
 * Plugin Name:       Flexi Flick
 * Description:       Gutenberg block for flickity slider with custom post type option
 * Requires at least: 6.1
 * Requires PHP:      7.4
 * Version:           0.1.4
 * Author:            rashmiwp
 * Author URI:        https://profiles.wordpress.org/rashmiwp/
 * License:           GPL-3.0-or-later
 * License URI:       https://www.gnu.org/licenses/gpl-3.0.html
 * Text Domain:       flexi-flick
 *
 * @package FlexiFlick
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly.
}

function flexiflick_register_taxonomy() {
    register_taxonomy(
        'flexiflick_slider_group',
        'flexiflick_slide_cpt', // Your custom post type
        array(
            'labels' => array(
                'name' => 'Slider Groups',
                'singular_name' => 'Slider Group',
            ),
            'public' => true,
            'hierarchical' => true,
            'show_ui' => true,
            'show_in_rest' => true, // Enable Gutenberg support
            'has_archive' => false,
            'exclude_from_search' => true,
        )
    );
}
add_action('init', 'flexiflick_register_taxonomy');

// Register Custom Post Type for Slides
function flexiflick_create_slide_post_type() {

    $labels = array(
        'name'               => 'FlexiFlick Slides',
        'singular_name'      => 'Slide',
        'menu_name'          => 'FlexiFlick Slides',
        'name_admin_bar'     => 'Slide',
        'add_new'            => 'Add New',
        'add_new_item'       => 'Add New Slide',
        'new_item'           => 'New Slide',
        'edit_item'          => 'Edit Slide',
        'view_item'          => 'View Slide',
        'all_items'          => 'All Slides',
        'not_found'          => 'No slides found.',
        'not_found_in_trash' => 'No slides found in Trash.',
    );

    $args = array(
        'labels' => $labels,
        'public' => true,
        'publicly_queryable' => false,
        'show_ui' => true,
        'show_in_menu' => true,
        'query_var' => true,
        'rewrite' => false, // Updated slug
        'capability_type' => 'post',
        'has_archive' => false,
        'exclude_from_search' => true,
        'hierarchical' => false,
        'menu_position' => null,
        'show_in_rest' => true,
        'supports' => array('title', 'editor', 'thumbnail'),
    );

    register_post_type('flexiflick_slide_cpt', $args); // Updated post type slug to have custom post type
}
add_action('init', 'flexiflick_create_slide_post_type');

// Register Block Type and Attributes
function flexiflick_register_block() {
    register_block_type( __DIR__ . '/build', array(
        'render_callback' => 'flexiflick_render_slider',
        'editor_script' => 'flexiflick-editor-script',
        'editor_style'  => 'flexiflick-editor-style',
        'attributes'      => array(
            'sliderGroup' => array(
                'type' => 'string',
            ),
            'showArrows' => array(
                'type'    => 'boolean',
                'default' => true,
            ),
            'showPager' => array(
                'type'    => 'boolean',
                'default' => true,
            ),
            'draggable' => array(
                'type'    => 'boolean',
                'default' => false,
            ),
            'wrapAround' => array(
                'type'    => 'boolean',
                'default' => false,
            ),
            'freeScroll' => array(
                'type'    => 'boolean',
                'default' => true,
            ),
            'pauseAutoPlayOnHover' => array(
                'type'    => 'boolean',
                'default' => false,
            ),
            'autoPlay' => array(  // New autoPlay setting
                'type'    => 'number',
                'default' => 0, // Default is 0 (no autoplay)
            ),
            'minHeight' => array(  // New autoPlay setting
                'type'    => 'number',
                'default' => 450, // Default is 0 (no autoplay)
            ),
        ),
    ));
}
add_action( 'init', 'flexiflick_register_block' );

// Render the FlexiFlick Slider
function flexiflick_render_slider($attributes) {

  // Only load frontend CSS and JS if this block actually renders
    wp_enqueue_style(
    'flexiflick-frontend-style',
    plugins_url( 'build/view.css', __FILE__ ),
    [],
    '0.1.3' // your plugin version
    );

    wp_enqueue_script(
        'flexiflick-frontend-script',
        plugins_url( 'build/view.js', __FILE__ ),
        [ 'jquery' ],
        '0.1.3',
        true
    );



    $slider_group = isset($attributes['sliderGroup']) ? $attributes['sliderGroup'] : '';
    $args = array(
        'post_type' => 'flexiflick_slide_cpt', // Updated post type slug
        'posts_per_page' => -1,
    );
    if ($slider_group) {
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'flexiflick_slider_group',
                'field' => 'id',
                'terms' => $slider_group,
            ),
        );
    }

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

    if ($slides->have_posts()) {
      $animation_speed = (floor($attributes['autoPlay']/1000) + 2) ?? 0;

      $min_height = $attributes['minHeight'] ?? '450'; // Example attribute value from block
        echo '<div class="flickity-wrap" style="--slider-min-height: ' . esc_attr($min_height) . 'px; --slider-ani-speed: ' . esc_attr($animation_speed) . 's"><div data-flickity=\'{ 
            "draggable": ' . esc_attr($attributes['draggable'] ? 'true' : 'false') . ', 
            "freeScroll": ' . esc_attr($attributes['freeScroll'] ? 'true' : 'false') . ', 
            "autoPlay": ' . esc_attr($attributes['autoPlay'] > 0 ? $attributes['autoPlay'] : 'false') . ', 
            "wrapAround": ' . esc_attr($attributes['wrapAround'] ? 'true' : 'false') . ', 
            "pageDots": ' . esc_attr($attributes['showPager'] ? 'true' : 'false') . ', 
            "prevNextButtons": ' . esc_attr($attributes['showArrows'] ? 'true' : 'false') . ' 
        }\'>';
        
        while ($slides->have_posts()) : $slides->the_post();
            echo '<div class="flickity-slide" >';
            if (has_post_thumbnail()) {
                the_post_thumbnail('full');
            }
            echo '<div class="flickity-slide-content">';
            the_title('<h2>', '</h2>');
            the_content();
            echo '</div></div>';
        endwhile;
        echo '</div></div>';
        wp_reset_postdata();
        
    }

    return ob_get_clean();
}


// Enqueue Scripts and Styles
function flexiflick_enqueue_scripts() {
    // Only enqueue on the frontend and if the FlexiFlick block is being used or singular CPT page is loaded
    if ( has_block( 'flexiflick/slider-block' ) || is_singular( 'flexiflick_slide_cpt' ) ) {
        // Enqueue the Flickity CSS file
        wp_enqueue_style(
            'flexiflick-flickity-css', 
            plugins_url('/assets/css/flickity.min.css', __FILE__), 
            array(), 
            '2.2.1'
        );

        // Add custom inline styles (arrows or button styles)
        wp_add_inline_style( 'flexiflick-flickity-css', flexiflick_custom_css() );

        // Enqueue the Flickity JS file
        wp_enqueue_script(
            'flexiflick-flickity-js', 
            plugins_url('/assets/js/flickity.pkgd.min.js', __FILE__), 
            array('jquery'), 
            '2.2.1', 
            true
        );
    }
}
add_action('wp_enqueue_scripts', 'flexiflick_enqueue_scripts');

// Custom inline CSS function to add background image to buttons
function flexiflick_custom_css() {
    $image_url = plugins_url( 'assets/arrow-iconsvg.svg', __FILE__ );
    return "
        .flickity-slide-content .wp-block-button a:after {
            background-image: url('{$image_url}');
            
        }
    ";
}

wp_register_style(
    'flexiflick-editor-style',
    plugins_url( 'build/index.css', __FILE__ ),
    [],
    '1.0'
);

wp_register_script(
    'flexiflick-editor-script',
    plugins_url( 'build/index.js', __FILE__ ),
    [ 'wp-blocks', 'wp-element', 'wp-editor' ],
    '1.0',
    true
);

function flexiflick_register_assets() {
    wp_register_script(
        'flexiflick-editor-script',
        plugins_url( 'build/index.js', __FILE__ ),
        [ 'wp-blocks', 'wp-element', 'wp-editor', 'wp-components', 'wp-i18n', 'wp-data', 'wp-block-editor' ],
        '1.0',
        true
    );

    wp_register_style(
        'flexiflick-editor-style',
        plugins_url( 'build/index.css', __FILE__ ),
        [],
        '1.0'
    );
}
add_action( 'init', 'flexiflick_register_assets' );
