<?php
/**
 * @package WavypointPopUps
 */
namespace WavypointPopUps\Base;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class CustomPostType extends BaseController {

    public function register() {
        add_action('init', [$this, 'wavypopup_register_popup_post_type']);
        add_action('edit_form_after_title', [$this, 'wavypopup_add_custom_html_to_cpt_form']);
        add_action('add_meta_boxes', [$this, 'wavypopup_add_popup_meta_box']);
        add_action('save_post', [$this, 'wavypopup_save_popup_meta_box']);
        add_action('edit_form_after_title', function($post){
            if ($post->post_type !== 'wavypopup') return;

            $value = get_post_meta($post->ID, '_wavypopup_type', true) ?: 'container';
            ?>
            <div class="wavypopup-type-box" style="margin:15px 0; padding:10px; border:1px solid #ddd; background:#fff;">
                <strong><?php esc_html_e('Popup Type', 'wavypoint-pop-ups'); ?></strong><br><br>
                <label>
                    <input type="radio" name="wavypopup_type" value="container" <?php checked($value, 'container'); ?> />
                    <?php esc_html_e('Container (Default)', 'wavypoint-pop-ups'); ?>
                </label> &nbsp;&nbsp;
                <label>
                    <input type="radio" name="wavypopup_type" value="banner" <?php checked($value, 'banner'); ?> />
                    <?php esc_html_e('Banner', 'wavypoint-pop-ups'); ?>
                </label>
            </div>
            <?php
        });

        add_filter('manage_wavypopup_posts_columns', function($columns) {
           $new = [];
            foreach ($columns as $key => $label) {
                if ($key === 'title') {
                    // Insert "Enabled" right after Title
                    $new[$key] = $label;
                    $new['popup_enabled'] = 'Enabled';
                } else {
                    $new[$key] = $label;
                }
            }
            return $new;
        });
        add_action('manage_wavypopup_posts_custom_column', function($column, $post_id) {
            if ($column === 'popup_enabled') {
                $enabled = get_post_meta($post_id, '_popup_enabled', true);
                echo $enabled === '1' ? '✅ Enabled' : '❌ Disabled';
            }
        }, 10, 2);


        add_action('admin_enqueue_scripts', function () {
            global $post;
            if ($post && $post->post_type === 'wavypopup') {

                wp_enqueue_script('jquery');
                wp_enqueue_media();

                $script = "
                jQuery(document).ready(function($){

                    function togglePopupFields(){
                        let type = $('input[name=\"wavypopup_type\"]:checked').val();

                        if(type === 'banner'){
                            $('#postdivrich, #wavypopup_style').hide();
                            $('#wavypopup-banner-box').show();
                        } else {
                            $('#postdivrich, #wavypopup_style').show();
                            $('#wavypopup-banner-box').hide();
                        }
                    }

                    togglePopupFields();

                    $(document).on('change','input[name=\"wavypopup_type\"]',togglePopupFields);

                    $('.upload-banner-button').click(function(e){
                        e.preventDefault();

                        var input = $('#wavypopup_banner_url');

                        var frame = wp.media({
                            title: 'Select or Upload Banner',
                            button: { text: 'Use this image' },
                            multiple: false
                        });

                        frame.on('select', function(){
                            var attachment = frame.state().get('selection').first().toJSON();
                            input.val(attachment.url);
                        });

                        frame.open();
                    });

                });
                ";

                wp_add_inline_script('jquery', $script);
            }
        });

        add_action('admin_enqueue_scripts', function ($hook) {

            if ($hook !== 'post.php' && $hook !== 'post-new.php') {
                return;
            }

            $screen = get_current_screen();

            if ($screen->post_type !== 'wavypopup') {
                return;
            }

            wp_enqueue_script('jquery');

            $script = "
            (function($){

                function toggleTargetSelectors() {

                    var val = $('select[name=\"popup_display_location\"]').val();

                    $('#target_page_selector, #target_post_selector').hide();

                    if (val === 'specific_page') {
                        $('#target_page_selector').show();
                    }

                    if (val === 'specific_post') {
                        $('#target_post_selector').show();
                    }
                }

                $(document).ready(toggleTargetSelectors);

                $(document).on('change','select[name=\"popup_display_location\"]',toggleTargetSelectors);

            })(jQuery);
            ";

            wp_add_inline_script('jquery', $script);

        });

        add_action('admin_enqueue_scripts', function ($hook) {

            if ($hook !== 'post.php' && $hook !== 'post-new.php') {
                return;
            }

            $screen = get_current_screen();

            if ($screen->post_type !== 'wavypopup') {
                return;
            }

            wp_enqueue_script('jquery');
            wp_enqueue_media();

            $script = "
            jQuery(document).ready(function($){

                var file_frame;

                $(document).on('click','.background-video-upload', function(e){

                    e.preventDefault();

                    if (file_frame) {
                        file_frame.open();
                        return;
                    }

                    file_frame = wp.media({
                        title: 'Select or Upload Background Video',
                        button: { text: 'Use this video' },
                        library: { type: 'video' },
                        multiple: false
                    });

                    file_frame.on('select', function(){

                        var attachment = file_frame.state().get('selection').first().toJSON();

                        $('#background_video_url').val(attachment.url);

                    });

                    file_frame.open();

                });

            });
            ";

            wp_add_inline_script('jquery', $script);

        });
    }

    public function wavypopup_register_popup_post_type() {
        register_post_type('wavypopup', [
            'labels' => [
                'name' => 'Wavy Popups',
                'singular_name' => 'Wavy Popup',
                'add_new' => 'Add New',
                'add_new_item' => 'Add New Wavy Popup',
                'edit_item' => 'Edit Wavy Popup',
                'new_item' => 'New Wavy Popup',
                'view_item' => 'View Wavy Popup',
                'search_items' => 'Search Wavy Popups',
            ],
            'public' => false,
            'show_ui' => true,
            'show_in_menu' => true,
            'menu_icon' => 'dashicons-admin-page',
            'supports' => ['title', 'editor'],
            'capability_type' => 'post',
        ]);
    }


    public function wavypopup_add_custom_html_to_cpt_form($post)
    {
        if ($post->post_type !== 'wavypopup') {
            return;
        }

        $transient_key = 'wavypoint_dashboard_banner';
        $cached_html   = get_transient($transient_key);

        // If cache exists → use it
        if ( $cached_html !== false ) {
            if ( ! empty( $cached_html ) ) {
                echo '<div class="notice notice-info is-dismissible wavypoint-dashboard-banner">';
                echo '<h3>' . esc_html__( 'Recommended From Wavy Popups', 'wavypoint-pop-ups' ) . '</h3>';
                echo wp_kses_post( $cached_html );
                echo '</div>';
            }
            return;
        }

        // Cache miss → call API
        $api_url = 'https://www.wavypoint.com/api/banner';

        $response = wp_remote_get($api_url, [
            'timeout' => 10,
        ]);

        $cached_html = '';

        if (!is_wp_error($response)) {
            $body = wp_remote_retrieve_body($response);
            $data = json_decode($body, true);

            if (!empty($data['content'])) {
                $cached_html = $data['content'];
            }
        }

        // Cache result (even empty, to avoid repeated calls)
        set_transient($transient_key, $cached_html, 6 * HOUR_IN_SECONDS);

        if (empty($cached_html)) {
            return;
        }
            echo '<div class="glow-animate">';
            echo '<h3>' . esc_html__( 'Recommended From Wavy Popups', 'wavypoint-pop-ups' ) . '</h3>';
            echo wp_kses_post( $cached_html );
            echo '</div>';
    }




    public function wavypopup_add_popup_meta_box() {

        add_meta_box(
            'wavypopup_status',
            __( 'Popup Status', 'wavypoint-pop-ups' ),
            [$this, 'wavypopup_render_popup_status_box'],
            'wavypopup',
            'side'
        );

        add_meta_box(
            'wavypopup_location',
            __( 'Popup Page Display', 'wavypoint-pop-ups' ),
            [$this, 'wavypopup_render_popup_location_box'],
            'wavypopup',
            'side'
        );

        add_meta_box(
            'wavypopup_animation',
            __( 'Popup Animation', 'wavypoint-pop-ups' ),
            [$this, 'wavypopup_render_popup_animation_box'],
            'wavypopup',
            'side'
        );

        add_meta_box(
            'wavypopup_max_width',
            __( 'Popup Max Width', 'wavypoint-pop-ups' ),
            [$this, 'wavypopup_render_popup_max_width_box'],
            'wavypopup',
            'side'
        );

        add_meta_box(
            'wavypopup_confetti',
            __( 'Confetti Effect', 'wavypoint-pop-ups' ),
            [$this, 'wavypopup_render_confetti_box'],
            'wavypopup',
            'side'
        );

        add_meta_box(
            'wavypopup_style',
             __( 'Popup Style', 'wavypoint-pop-ups' ),
            [$this, 'wavypopup_render_style_box'],
            'wavypopup',
            'normal',   // <-- under the editor (not sidebar)
            'high'      // <-- appears on top of other "normal" boxes
        );

        add_meta_box(
            'wavypopup_background_video',
            __( 'Background Video', 'wavypoint-pop-ups' ),
            [$this, 'wavypopup_render_background_video'],
            'wavypopup',
            'side'
        );

        add_meta_box(
            'wavypopup_banner',
            __('Banner Settings', 'wavypoint-pop-ups'),
            [$this, 'wavypopup_render_wavypopup_banner_box'],
            'wavypopup',
            'normal',
            'default'
        );
    }

    function wavypopup_render_popup_status_box($post) {
    
    $value = get_post_meta($post->ID, '_popup_enabled', true);

    if ($value === '') {
        $value = '1';
    }

    echo '<label>';
    echo '<input type="checkbox" name="popup_enabled" value="1" ' . checked($value, '1', false) . ' />';
    esc_html_e( 'Enable this popup', 'wavypoint-pop-ups' );
    echo '</label>';

    }

    public function wavypopup_render_popup_location_box($post) {
        $value = get_post_meta($post->ID, '_popup_display_location', true);
    
        $options = [
            'home'        => 'Home Page',
            'all_pages'   => 'All Pages',
            'all_posts'   => 'All Posts',
            'entire_site' => 'Entire Site',
            'specific_page' => 'Specific Page',
            'specific_post' => 'Specific Post',
        ];
    
        wp_nonce_field('popup_display_nonce', 'popup_display_nonce_field');
    
        echo '<select name="popup_display_location" style="width:100%;">';
        foreach ($options as $key => $label) {
            printf(
                '<option value="%s"%s>%s</option>',
                esc_attr($key),
                selected($value, $key, false),
                esc_html($label)
            );
        }
        echo '</select>';

        $selected_page = get_post_meta($post->ID, '_popup_target_page', true);
        $selected_post = get_post_meta($post->ID, '_popup_target_post', true);

        echo '<div id="popup-target-wrapper" style="margin-top:10px;">';

        // Pages
        $pages = get_pages();
        echo '<div id="target_page_selector" style="display:none;">';
        echo '<label><strong>Select Page:</strong></label><br>';
        echo '<select name="popup_target_page" style="width:100%;">';
        echo '<option value="">-- Select Page --</option>';
        foreach ($pages as $page) {
            printf(
                '<option value="%d"%s>%s</option>',
                esc_attr( $page->ID ),
                selected( $selected_page, $page->ID, false ),
                esc_html( $page->post_title )
            );
        }
        echo '</select>';
        echo '</div>';

        // Posts
        $posts = get_posts(['post_type' => 'post', 'numberposts' => -1]);
        echo '<div id="target_post_selector" style="display:none;">';
        echo '<label><strong>Select Post:</strong></label><br>';
        echo '<select name="popup_target_post" style="width:100%;">';
        echo '<option value="">-- Select Post --</option>';
        foreach ($posts as $p) {
            printf('<option value="%d"%s>%s</option>', esc_attr( $p->ID ), selected($selected_post, $p->ID, false), esc_html($p->post_title));
        }
        echo '</select>';
        echo '</div>';

        echo '</div>';

    }

    

    public function wavypopup_render_popup_animation_box($post) {
        $animation_value = get_post_meta($post->ID, '_popup_animation', true);
    
        $animation_options = [
            'fadeIn' => 'Fade In',
            'zoomIn' => 'Zoom In',
            'slideUp' => 'Slide Up',
            'flipIn' => 'Flip In',
            'bounceIn' => 'Bounce In',
        ];
    
        wp_nonce_field('popup_animation_nonce', 'popup_animation_nonce_field');
    
        echo '<select name="popup_animation" style="width:100%;">';
        echo '<option value="">-- Select Animation --</option>';
        foreach ($animation_options as $key => $label) {
            printf(
                '<option value="%s"%s>%s</option>',
                esc_attr($key),
                selected($animation_value, $key, false),
                esc_html($label)
            );
        }
        echo '</select>';
    }

    public function wavypopup_render_popup_max_width_box($post) {
    $width_value = get_post_meta($post->ID, '_popup_max_width', true);
    wp_nonce_field('popup_max_width_nonce', 'popup_max_width_nonce_field');

    echo '<label for="popup_max_width">Set Max Width (e.g., 400px or 80%)</label>';
    echo '<input type="text" name="popup_max_width" id="popup_max_width" value="' . esc_attr($width_value) . '" style="width:100%;" placeholder="500px">';
    }

    public function wavypopup_render_confetti_box($post) {
    $confetti_enabled = get_post_meta($post->ID, '_popup_enable_confetti', true);
    wp_nonce_field('popup_confetti_nonce', 'popup_confetti_nonce_field');

    echo '<label>';
    echo '<input type="checkbox" name="popup_enable_confetti" value="1" ' . checked($confetti_enabled, '1', false) . '> Enable Confetti';
    echo '</label>';
    }

    public function wavypopup_render_style_box($post) {

        $style_value = get_post_meta($post->ID, '_popup_style', true);

        // Define style options with image previews
        $style_options = [
            'classic' => [
                'label' => 'Classic',
                'img'   => WAVYPOINT_CDN . 'styles/classic.png'
            ],
            'style1' => [
                'label' => 'Style 1',
                'img'   => WAVYPOINT_CDN . 'styles/style1.png'
            ],
            'style2' => [
                'label' => 'Style 2',
                'img'   => WAVYPOINT_CDN . 'styles/style2.png'
            ],
            'style3' => [
                'label' => 'Style 3',
                'img'   => WAVYPOINT_CDN . 'styles/style3.png'
            ],
            'style4' => [
                'label' => 'Style 4',
                'img'   => WAVYPOINT_CDN . 'styles/style4.png'
            ],
            'style5' => [
                'label' => 'Style 5',
                'img'   => WAVYPOINT_CDN . 'styles/style5.png'
            ],
            'style6' => [
                'label' => 'Style 6',
                'img'   => WAVYPOINT_CDN . 'styles/style6.png'
            ],
            'style7' => [
                'label' => 'Style 7',
                'img'   => WAVYPOINT_CDN . 'styles/style7.png'
            ],
            'style8' => [
                'label' => 'Style 8',
                'img'   => WAVYPOINT_CDN . 'styles/style8.png'
            ],
            // 'style9' => [
            //     'label' => 'Style 9',
            //     'img'   => WAVYPOINT_CDN . 'styles/style9.png'
            // ],
            'style10' => [
                'label' => 'Style 9',
                'img'   => WAVYPOINT_CDN . 'styles/style10.png'
            ],
        ];

        wp_nonce_field('popup_style_nonce', 'popup_style_nonce_field');

        echo '<div style="display:flex; gap:20px; flex-wrap:wrap;">';

        foreach ($style_options as $key => $option) {
            $checked = checked($style_value, $key, false);

            echo '<label style="text-align:center; cursor:pointer;">';
            echo '<input type="radio" name="popup_style" value="' . esc_attr($key) . '" ' . esc_attr( $checked ) . ' style="margin-bottom:5px;" />';
            echo '<br>';
            echo '<img src="' . esc_url($option['img']) . '" alt="' . esc_attr($option['label']) . '" style="max-width:250px; border:1px solid #ccc; border-radius:4px; display:block; margin-bottom:5px;" />';
            echo '<br>' . esc_html($option['label']);
            echo '</label>';
        }

        echo '</div>';
    }

    public function wavypopup_render_background_video($post) {
            
              echo sprintf(
                    '<a href="%s"><small>%s</small></a>',
                    esc_url( 'https://www.wavypoint.com/plugins/wavypoint-pop-ups-smart-animated-visual-wordpress-popups' ),
                    esc_html__( 'Pro Only', 'wavypoint-pop-ups' )
                );
            
           
    }

    public function wavypopup_render_wavypopup_banner_box($post) {
    // Always check and sanitize values
        $banner_url  = get_post_meta($post->ID, '_wavypopup_banner_url', true);
        $target_link = get_post_meta($post->ID, '_wavypopup_target_link', true);
        $bannerMakerUrl = admin_url( 'admin.php?page=wavy-banner-maker' );
        ?>
        <div id="wavypopup-banner-box">
            <p>
                <label for="wavypopup_banner_url"><strong><?php esc_html_e('Upload Banner', 'wavypoint-pop-ups'); ?></strong></label><br>
                <input type="text" 
                    name="wavypopup_banner_url" 
                    id="wavypopup_banner_url" 
                    value="<?php echo esc_attr($banner_url); ?>" 
                    style="width:80%;" />
                <button class="button upload-banner-button"><?php esc_html_e('Upload', 'wavypoint-pop-ups'); ?></button>
            </p>

            <p>
                <label for="wavypopup_target_link"><strong><?php esc_html_e('Target Link', 'wavypoint-pop-ups'); ?></strong></label><br>
                <input type="url" 
                    name="wavypopup_target_link" 
                    id="wavypopup_target_link" 
                    value="<?php echo esc_attr($target_link); ?>" 
                    style="width:100%;" />
            </p>
             <h1><a href="<?php echo esc_url( $bannerMakerUrl ) ?>"><?php esc_html_e('Design Stunning Banners in Seconds with Wavy Banner Maker', 'wavypoint-pop-ups'); ?></a></h1>
        </div>
        <?php
    }
    

    public function wavypopup_save_popup_meta_box($post_id) {
        // 1. Primary Security & Environment Checks
        if ( ! isset( $_POST['popup_display_nonce_field'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['popup_display_nonce_field'] ) ), 'popup_display_nonce' ) ) {
            return; // This is the only return we keep; if the main form isn't legit, stop.
        }

        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
        if (!current_user_can('edit_post', $post_id)) return;

        // 2. Save Basic Display Location & Targets
        if ( isset( $_POST['popup_display_location'] ) ) {
            update_post_meta( $post_id, '_popup_display_location', sanitize_text_field( wp_unslash( $_POST['popup_display_location'] ) ) );
        }
        if (isset($_POST['popup_target_page'])) {
            update_post_meta($post_id, '_popup_target_page', intval($_POST['popup_target_page']));
        }
        if (isset($_POST['popup_target_post'])) {
            update_post_meta($post_id, '_popup_target_post', intval($_POST['popup_target_post']));
        }

        // 3. Save Animation
        if ( isset( $_POST['popup_animation_nonce_field'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['popup_animation_nonce_field'] ) ), 'popup_animation_nonce' ) ) {
            if ( isset( $_POST['popup_animation'] ) ) {
                update_post_meta( $post_id, '_popup_animation', sanitize_text_field( wp_unslash( $_POST['popup_animation'] ) ) );
            }
        }

        // 4. Save Max Width
        if ( isset( $_POST['popup_max_width_nonce_field'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['popup_max_width_nonce_field'] ) ), 'popup_max_width_nonce' ) ) {
            if ( isset( $_POST['popup_max_width'] ) ) {
                update_post_meta( $post_id, '_popup_max_width', sanitize_text_field( wp_unslash( $_POST['popup_max_width'] ) ) );
            }
        }

        // 5. Save Confetti
        if ( isset( $_POST['popup_confetti_nonce_field'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['popup_confetti_nonce_field'] ) ), 'popup_confetti_nonce' ) ) {
            update_post_meta( $post_id, '_popup_enable_confetti', isset( $_POST['popup_enable_confetti'] ) ? 1 : 0 );
        }

        // 6. Save Style
        if ( isset( $_POST['popup_style_nonce_field'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['popup_style_nonce_field'] ) ), 'popup_style_nonce' ) ) {
            if ( isset( $_POST['popup_style'] ) ) {
                update_post_meta( $post_id, '_popup_style', sanitize_text_field( wp_unslash( $_POST['popup_style'] ) ) );
            }
        }

        // 7. VIDEO BACKGROUND (The Pro Section)
        if ( isset( $_POST['background_video_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['background_video_nonce'] ) ), 'background_video_nonce_action' ) ) {
            
            // Video URL
            if (isset($_POST['background_video_url'])) {
                update_post_meta($post_id, '_background_video_url', esc_url_raw( wp_unslash($_POST['background_video_url']) ) );
            }

            // Video Opacity
            if ( isset( $_POST['background_video_opacity'] ) ) {
                update_post_meta( $post_id, '_background_video_opacity', floatval( wp_unslash( $_POST['background_video_opacity'] ) ) );
            }

            // Video Loop (Note: In your render function, this uses the same nonce as the video URL)
            $loop = ( isset( $_POST['background_video_loop'] ) && $_POST['background_video_loop'] === 'yes' ) ? 'yes' : 'no';
            update_post_meta( $post_id, '_background_video_loop', $loop );
        }

        // 8. Save Popup Type (The part you were missing!)
        if ( isset( $_POST['wavypopup_type'] ) ) {
            update_post_meta( $post_id, '_wavypopup_type', sanitize_text_field( wp_unslash( $_POST['wavypopup_type'] ) ) );
        }

        // 9. Save Banner Settings
        if (isset($_POST['wavypopup_banner_url'])) {
            update_post_meta($post_id, '_wavypopup_banner_url', esc_url_raw( wp_unslash( $_POST['wavypopup_banner_url'] ) ));
        }
        if (isset($_POST['wavypopup_target_link'])) {
            update_post_meta($post_id, '_wavypopup_target_link', esc_url_raw( wp_unslash( $_POST['wavypopup_target_link'] ) ));
        }

        // 10. Save Global Status (Checkbox)
        update_post_meta($post_id, '_popup_enabled', isset($_POST['popup_enabled']) ? '1' : '0');
    }
        
    
   

    
}
