<?php
if ( !defined( 'ABSPATH' ) ) {
    exit;
}

class BWD_Subscription_settings {

    public function __construct() {
        add_action( 'wp_head', array( $this, 'cv_global_basic_syles' ) );
        add_action( 'product_type_options', array( $this, 'add_subscription_checkbox' ) );
        add_filter( 'woocommerce_product_options_general_product_data', array( $this, 'load_subscription_checkbox_value' ) );
        add_action( 'woocommerce_process_product_meta', array( $this, 'save_subscription_data' ) );
        add_action( 'woocommerce_product_data_panels', array( $this, 'subscription_settings_content' ) );
        add_action( 'save_post', array( $this, 'save_subscription_checkbox_value' ), 10, 3 );
        add_action( 'woocommerce_after_shop_loop_item_title', array( $this, 'subscription_data_to_shop_page' ), 15 );
        add_action( 'woocommerce_after_shop_loop_item', array( $this, 'add_custom_button_to_shop_page' ), 10 );
        add_action( 'woocommerce_checkout_create_order_line_item', array( $this, 'add_subscription_data_to_order' ), 10, 4 );
        add_filter( 'woocommerce_add_cart_item_data', array( $this, 'add_subscription_data_to_cart_item' ), 10, 2 );
        add_filter( 'post_class', array( $this, 'add_unique_class_to_product_card' ), 10, 2 );
        // N
        add_action( 'woocommerce_product_query', array( $this, 'exclude_category_from_shop' ) );
        add_action( 'template_redirect', array( $this, 'clear_cart_page' ) );
        add_action( 'save_post', array( $this, 'set_default_product_category' ), 10, 3 );
        add_action( 'woocommerce_add_to_cart', array( $this, 'clear_cart_before_add' ), 10, 1 );
        add_filter( 'woocommerce_is_sold_individually', array( $this, 'product_add_once' ), 10, 2 );
        add_shortcode( 'subscription_product', array( $this, 'subscription_content_shortcode' ) );
        add_shortcode( 'cv_dashboard_setting', array( $this, 'dashboard_content_shortcode' ) );
        add_action( 'wp_enqueue_scripts', [$this, 'bwdcv_cover_letter_api_ajax'] );
        if ( !empty( get_option( 'cv_openai_api_key_text', '' ) ) ) {
            add_action( 'wp_ajax_bwdcv_openai_api_request', [$this, 'openai_api_handle_request'] );
        }
        // Checkout ajax load
        add_action( 'wp_footer', [$this, 'bwdcv_to_get_checkout_form'] );
        add_action( 'wp_enqueue_scripts', [$this, 'bwdcv_all_assets_for_the_checkout_ajax'] );
        add_action( 'template_redirect', [$this, 'ensure_cart_initialization'] );
        add_action( 'wp_ajax_bwdcv_add_to_cart_and_checkout', [$this, 'bwdcv_add_to_cart_and_checkout'] );
        add_action( 'wp_ajax_nopriv_bwdcv_add_to_cart_and_checkout', [$this, 'bwdcv_add_to_cart_and_checkout'] );
        add_action( 'wp_ajax_bwdcv_load_checkout', [$this, 'bwdcv_load_checkout_in_popup'] );
        add_action( 'wp_ajax_nopriv_bwdcv_load_checkout', [$this, 'bwdcv_load_checkout_in_popup'] );
        add_action( 'wp_ajax_bwdcv_process_checkout', [$this, 'process_checkout'] );
        add_action( 'wp_ajax_nopriv_bwdcv_process_checkout', [$this, 'process_checkout'] );
        add_filter( 'woocommerce_default_address_fields', function ( $address_fields ) {
            $address_fields['postcode']['validate'] = array();
            return $address_fields;
        } );
        add_filter( 'woocommerce_checkout_fields', [$this, 'customize_checkout_fields'] );
        register_activation_hook( __FILE__, [$this, 'dynamic_year_dropdown_activate'] );
        add_action( 'admin_init', array( $this, 'editor_access_denied_from_dashboard' ) );
        add_action( 'admin_menu', array( $this, 'restrict_editor_access' ) );
        add_action( 'admin_init', array( $this, 'block_direct_access_for_editor' ) );
        add_action( 'admin_bar_menu', array( $this, 'hide_admin_bar_items' ), 999 );
        add_action( 'admin_post_bwdcv_past_user_create_edit_page', [$this, 'bwdcv_past_user_create_and_edit_page'] );
        add_filter( 'the_title', [$this, 'remove_title_from_single'], 10, 2 );
        add_action( 'init', [$this, 'remove_post_author_date'] );
        add_action( 'wp_login', [$this, 'bwdcv_login_redirection'], 10, 2 );
        add_filter( 'single_template', [$this, 'bwdcv_load_cv_template'] );
        add_action( 'admin_footer', [$this, 'bwdcv_upgrade_pro'] );

        /**
         *
         * For custom cv subscription plans
         *
         */
        add_action( 'admin_menu', array( $this, 'bwdcv_subscription_add_admin_menu' ), 99 );
        add_action( 'admin_enqueue_scripts', array( $this, 'bwdcv_subscription_enqueue_admin_scripts' ) );

        // Add custom product type
        add_action( 'init', array( $this, 'bwdcv_subscription_register_product_type' ) );

    }

    public function bwdcv_is_block_theme() {
        return function_exists( 'wp_is_block_theme' ) && wp_is_block_theme();
    }
    public function bwdcv_load_cv_template( $single_template ) {
        global $post;
        if ( $post && $post->post_type === 'cv' ) {
            if ( $this->bwdcv_is_block_theme() ) {
                $template_path = plugin_dir_path( __FILE__ ) . '../includes/block-cv-template.php';
            } else {
                $template_path = plugin_dir_path( __FILE__ ) . '../includes/classic-cv-template.php';
            }

            if ( file_exists( $template_path ) ) {
                return $template_path;
            }
        }
        return $single_template;
    }

    /**
     *
     * For custom cv subscription plans (START)
     *
     */
    public function bwdcv_subscription_enqueue_admin_scripts( $hook ) {
        // Ensure it's only for your plugin page
        wp_enqueue_media(); // Media uploader support
        wp_enqueue_script(
            'cv-admin-script',
            plugin_dir_url( __FILE__ ) . 'cv-admin.js',
            array( 'jquery' ),
            BWDCV_VERSION,
            true
        );
    }

    public function bwdcv_subscription_add_admin_menu() {
        add_submenu_page(
            'wp-cv-builder',
            esc_html__( 'Subscription Plans', 'cv-builder' ),
            esc_html__( 'Subscription Plans', 'cv-builder' ),
            'manage_woocommerce',
            'cv-subscription-products',
            array( $this, 'bwdcv_subscription_admin_page' )
        );

        add_submenu_page(
            'wp-cv-builder',
            esc_html__( 'Subscription Orders', 'cv-builder' ),
            esc_html__( 'Subscription Orders', 'cv-builder' ),
            'manage_options',
            'subscription-orders',
            [$this, 'display_subscriptions_data']
        );

        $this->add_upgrade_pro_menu_item();
        add_submenu_page(
            'wp-cv-builder',
            esc_html__( 'Add New Product', 'cv-builder' ),
            esc_html__( 'Add New', 'cv-builder' ),
            'manage_woocommerce',
            'cv-add-product',
            array( $this, 'bwdcv_subscription_add_product_page' )
        );
    }

    private function add_upgrade_pro_menu_item() {
        if ( class_exists( 'BWDCV_BLOCKS_CLASS_PRO' ) ) {
            return;
        }
        add_submenu_page(
            'wp-cv-builder',
            esc_html__( 'Upgrade Pro', 'cv-builder' ),
            esc_html__( 'Upgrade Pro', 'cv-builder' ),
            'manage_options',
            'https://wpcvbuilder.com/pricing/'
        );
    }
    public function bwdcv_upgrade_pro() {
        ?>
          <script>
            document.addEventListener('DOMContentLoaded', function () {
                const links = document.querySelectorAll('#adminmenu .toplevel_page_wp-cv-builder .wp-submenu-wrap li a');
                links.forEach(function(link) {
                    if (link.href && link.href.includes('wpcvbuilder.com/pricing')) {
                        link.setAttribute('target', '_blank');
                        link.style.color = '#fff';
                        link.style.backgroundColor = '#0066ff';
                        link.style.fontWeight = '600';
                        link.style.borderRadius = '3px';
                    }
                });
            });
        </script>
    <?php
}

    public function bwdcv_subscription_register_product_type() {
        // Register the product type with WooCommerce
        add_filter( 'woocommerce_data_stores', function ( $stores ) {
            $stores['product-cv_subscription'] = 'WC_Product_Data_Store_CPT';
            return $stores;
        } );
    }

    public function bwdcv_subscription_admin_page() {
        $product_id = isset( $_GET['product_id'] ) ? absint( $_GET['product_id'] ) : 0;
        $nonce = isset( $_GET['_wpnonce'] ) ? sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ) : '';
        // Handle delete action
        if ( isset( $_GET['action'] ) && $_GET['action'] === 'delete' && isset( $_GET['product_id'] ) && isset( $_GET['_wpnonce'] ) ) {
            if ( $product_id && wp_verify_nonce( $nonce, 'delete_cv_product_' . $product_id ) ) {
                $this->delete_product( $product_id );
            }
        }

        // Get CV subscription products
        $args = array(
            'post_type'   => 'product',
            'numberposts' => -1,
            'post_status' => array( 'publish', 'draft', 'private' ),
            'tax_query'   => array(
                array(
                    'taxonomy' => 'product_cat',
                    'field'    => 'slug',
                    'terms'    => 'cv-subscription',
                ),
            ),
        );

        $product_posts = get_posts( $args );
        $products = array();

        foreach ( $product_posts as $post ) {
            $product = wc_get_product( $post->ID );
            if ( $product ) {
                $products[] = $product;
            }
        }

        ?>
        <div class="wrap bwdcv-subscrive-info">
            <h1 class="wp-heading-inline"><?php esc_html_e( 'CV Subscription Products', 'cv-builder' ); ?></h1>
            <a href="<?php echo admin_url( 'admin.php?page=cv-add-product' ); ?>" class="page-title-action">
                <?php esc_html_e( 'Add New Subscription', 'cv-builder' ); ?>
            </a>

            <div class="cv-products-list bwdcv-subscrive-info-wrap">
                <?php if ( empty( $products ) ): ?>
                    <div class="cv-no-products">
                        <p><?php esc_html_e( 'No CV subscription products found.', 'cv-builder' ); ?></p>
                        <a href="<?php echo admin_url( 'admin.php?page=cv-add-product' ); ?>" class="button button-primary">
                            <?php esc_html_e( 'Add Your First Product', 'cv-builder' ); ?>
                        </a>
                    </div>
                <?php else: ?>
                    <table class="wp-list-table widefat fixed striped">
                        <thead>
                            <tr>
                                <th><?php esc_html_e( 'Image', 'cv-builder' ); ?></th>
                                <th><?php esc_html_e( 'Title', 'cv-builder' ); ?></th>
                                <th><?php esc_html_e( 'Plan Name', 'cv-builder' ); ?></th>
                                <th><?php esc_html_e( 'Price', 'cv-builder' ); ?></th>
                                <th><?php esc_html_e( 'Billing Period', 'cv-builder' ); ?></th>
                                <th><?php esc_html_e( 'Downloads', 'cv-builder' ); ?></th>
                                <th><?php esc_html_e( 'Status', 'cv-builder' ); ?></th>
                                <th><?php esc_html_e( 'Actions', 'cv-builder' ); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ( $products as $product ): ?>
                                <tr>
                                    <td>
                                        <?php
$image_id = $product->get_image_id();
        $image_url = $image_id ? wp_get_attachment_image_url( $image_id, 'thumbnail' ) : '';
        if ( $image_url ) {
            echo '<img src="' . esc_url( $image_url ) . '" alt="' . esc_attr( $product->get_name() ) . '" style="width: 50px; height: 50px; object-fit: cover; border-radius: 4px; border: 1px solid #ddd;">';
        } else {
            echo '<div style="width: 50px; height: 50px; background: #f0f0f0; border: 1px solid #ddd; border-radius: 4px; display: flex; align-items: center; justify-content: center;">';
            echo '<span class="dashicons dashicons-format-image" style="font-size: 24px; color: #999;"></span>';
            echo '</div>';
        }
        ?>
                                    </td>
                                    <td>
                                        <strong><?php echo esc_html( $product->get_name() ); ?></strong>
                                        <div class="row-actions">
                                            <span class="id">ID: <?php echo $product->get_id(); ?></span>
                                        </div>
                                    </td>
                                    <td><?php echo esc_html( $product->get_meta( '_subscription_plan_name' ) ); ?></td>
                                    <td>
                                        <?php if ( $product->get_sale_price() && $product->get_sale_price() < $product->get_regular_price() ): ?>
                                            <strong><?php echo wc_price( $product->get_sale_price() ); ?></strong>
                                        <small>
                                            <del><?php echo wc_price( $product->get_regular_price() ); ?></del>
                                        </small>
                                        <?php else: ?>
                                            <?php echo wc_price( $product->get_regular_price() ); ?>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php
$period = $product->get_meta( '_subscription_billing_period' );
        $period_labels = array(
            '1'   => esc_html__( 'Daily', 'cv-builder' ),
            '30'  => esc_html__( 'Monthly', 'cv-builder' ),
            '90'  => esc_html__( 'Three Month', 'cv-builder' ),
            '183' => esc_html__( 'Half Year', 'cv-builder' ),
            '365' => esc_html__( 'Yearly', 'cv-builder' ),
        );
        echo isset( $period_labels[$period] ) ? $period_labels[$period] : $period;
        ?>
                                    </td>
                                    <td><?php echo intval( $product->get_meta( '_subscription_per_download' ) ); ?></td>
                                    <td>
                                        <?php
$status = get_post_status( $product->get_id() );
        $status_labels = array(
            'publish' => esc_html__( 'Published', 'cv-builder' ),
            'draft'   => esc_html__( 'Draft', 'cv-builder' ),
            'private' => esc_html__( 'Private', 'cv-builder' ),
        );
        echo isset( $status_labels[$status] ) ? $status_labels[$status] : ucfirst( $status );
        ?>
                                    </td>
                                    <td>
                                        <a href="<?php echo admin_url( 'admin.php?page=cv-add-product&edit=' . $product->get_id() ); ?>"
                                        class="button button-small bwd-active-text"><?php esc_html_e( 'Edit', 'cv-builder' ); ?></a>
                                        <a href="<?php echo wp_nonce_url( admin_url( 'admin.php?page=cv-subscription-products&action=delete&product_id=' . $product->get_id() ), 'delete_cv_product_' . $product->get_id() ); ?>"
                                        class="button button-small cv-delete-product bwd-deactive-text"
                                        onclick="return confirm('<?php esc_html_e( 'Are you sure you want to delete this product?', 'cv-builder' ); ?>')">
                                        <?php esc_html_e( 'Delete', 'cv-builder' ); ?>
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
            </div>
        </div>
        <?php
}

    public function bwdcv_subscription_add_product_page() {
        $product = null;
        $edit_mode = false;
        $message = '';

        // Handle form submission
        if ( isset( $_POST['cv_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['cv_nonce'] ) ), 'cv_subscription_nonce' ) ) {
            $result = $this->save_product();
            if ( $result['success'] ) {
                $message = '<div class="notice notice-success"><p>' . $result['message'] . '</p></div>';
                if ( isset( $result['product_id'] ) ) {
                    $product = wc_get_product( $result['product_id'] );
                    $edit_mode = true;
                }
            } else {
                $message = '<div class="notice notice-error"><p>' . $result['message'] . '</p></div>';
            }
        }

        // Load existing product for editing
        if ( isset( $_GET['edit'] ) && is_numeric( $_GET['edit'] ) ) {
            $product_id = intval( $_GET['edit'] );
            $product = wc_get_product( $product_id );
            if ( $product && ( $product->get_type() === 'cv_subscription' || $product->get_meta( '_subscription_plan_name' ) ) ) {
                $edit_mode = true;
            } else {
                $message = '<div class="notice notice-error"><p>' . esc_html__( 'Product not found or not a CV subscription product.', 'cv-builder' ) . '</p></div>';
            }
        }

        // Pull meta if product is set
        $plan_name = $product ? $product->get_meta( '_subscription_plan_name' ) : 'Premium';
        $billing_period = $product ? $product->get_meta( '_subscription_billing_period' ) : '';
        $per_download = $product ? $product->get_meta( '_subscription_per_download' ) : '';
        ?>

        <div class="wrap  bwdcv-subscription-form bwdcv-custom-subscription-table">
            <h1><?php echo $edit_mode ? esc_html__( 'Edit CV Subscription Product', 'cv-builder' ) : esc_html__( 'Add New CV Subscription Product', 'cv-builder' ); ?></h1>
            <?php echo $message; ?>
            <form method="post" action="" class="cv-product-form">
                <?php wp_nonce_field( 'cv_subscription_nonce', 'cv_nonce' ); ?>

                <?php if ( $edit_mode ): ?>
                    <input type="hidden" name="product_id" value="<?php echo esc_attr( $product->get_id() ); ?>">
                <?php endif; ?>

                <table class='form-table'>
                    <tr>
                        <th><label for='product_title'><?php esc_html_e( 'Product Title', 'cv-builder' ); ?></label></th>
                        <td><input type="text" id="product_title" name="product_title" class="regular-text bwdcv-text-input" required value="<?php echo $product ? esc_attr( $product->get_name() ) : ''; ?>"></td>
                    </tr>

                    <tr>
                        <th><label for="regular_price"><?php esc_html_e( 'Regular Price', 'cv-builder' ); ?></label></th>
                        <td><input type="number" id="regular_price" name="regular_price" class="regular-text bwdcv-number-input" required step="0.01" min="0" value="<?php echo $product ? esc_attr( $product->get_regular_price() ) : ''; ?>"></td>
                    </tr>

                    <tr>
                        <th><label for="sale_price"><?php esc_html_e( 'Sale Price', 'cv-builder' ); ?></label></th>
                        <td>
                            <input type="number" id="sale_price" name="sale_price" class="regular-text bwdcv-number-input" step="0.01" min="0" value="<?php echo $product ? esc_attr( $product->get_sale_price() ) : ''; ?>">
                            <p class="description"><?php esc_html_e( 'Leave empty if no sale price', 'cv-builder' ); ?></p>
                        </td>
                    </tr>

                    <tr>
                        <th><label for="product_image"><?php esc_html_e( 'Product Image', 'cv-builder' ); ?></label></th>
                        <td>
                            <div class="cv-image-upload">
                                <input type="hidden" id="product_image" name="product_image" class="bwdcv-text-input" value="<?php echo $product ? $product->get_image_id() : ''; ?>">
                                <div class="cv-image-preview">
                                    <?php if ( $product && $product->get_image_id() ) {
            echo wp_get_attachment_image( $product->get_image_id(), [150, 150] );
        }?>
                                </div>
                                <button type="button" class="button cv-upload-image bwdcv-text-input"><?php esc_html_e( 'Choose Image', 'cv-builder' ); ?></button>
                                <button type="button" class="button cv-remove-image" style="<?php echo( !$product || !$product->get_image_id() ) ? 'display:none;' : ''; ?>"><?php esc_html_e( 'Remove Image', 'cv-builder' ); ?></button>
                            </div>
                        </td>
                    </tr>

                    <tr>
                        <th><label for="short_description"><?php esc_html_e( 'Product Description', 'cv-builder' ); ?></label></th>
                        <td class="bwdcv-form-input bwdcv-editor-container">
                            <?php
$short_description = $product ? $product->get_short_description() : '';
        wp_editor(
            wp_kses_post( $short_description ),
            'short_description',
            [
                'textarea_name' => 'short_description',
                'media_buttons' => true,
                'textarea_rows' => 10,
                'teeny'         => false,
                'tinymce'       => true,
                'quicktags'     => true,
                'editor_class'  => 'bwdcv-rich-editor',
            ]
        );
        ?>
                        </td>
                    </tr>

                    <tr>
                        <th><label for="subscription_plan_name"><?php esc_html_e( 'Plan Name', 'cv-builder' ); ?></label></th>
                        <td><input type="text" id="subscription_plan_name" name="subscription_plan_name" class="regular-text bwdcv-text-input" value="<?php echo esc_attr( $plan_name ); ?>"></td>
                    </tr>

                    <tr>
                        <th><label for="subscription_billing_period"><?php esc_html_e( 'Billing Period', 'cv-builder' ); ?></label></th>
                        <td>
                            <select id="subscription_billing_period" name="subscription_billing_period" class="regular-text bwdcv-select-input">
                                <option value=""><?php esc_html_e( 'Choose a billing period', 'cv-builder' ); ?></option>
                                <?php
$periods = [
            '1'   => esc_html__( 'Daily', 'cv-builder' ),
            '30'  => esc_html__( 'Monthly', 'cv-builder' ),
            '90'  => esc_html__( 'Three Month', 'cv-builder' ),
            '183' => esc_html__( 'Half Year', 'cv-builder' ),
            '365' => esc_html__( 'Yearly', 'cv-builder' ),
        ];
        foreach ( $periods as $value => $label ) {
            echo '<option value="' . esc_attr( $value ) . '" ' . selected( $billing_period, $value, false ) . '>' . esc_html( $label ) . '</option>';
        }
        ?>
                            </select>
                            <p class="description"><?php esc_html_e( 'Select a billing period OR enter a download number below (not both)', 'cv-builder' ); ?></p>
                        </td>
                    </tr>

                    <tr>
                        <th><label for="subscription_per_download"><?php esc_html_e( 'Download CV Number', 'cv-builder' ); ?></label></th>
                        <td>
                            <input type="number"
                                   id="subscription_per_download"
                                   name="subscription_per_download"
                                   class="regular-text bwdcv-number-input"
                                   min="1"
                                   step="1"
                                   value="<?php echo $per_download && $per_download > 0 ? esc_attr( $per_download ) : ''; ?>"
                                   placeholder="<?php esc_html_e( 'Enter number of downloads', 'cv-builder' ); ?>">
                            <p class="description"><?php esc_html_e( 'Enter the number of downloads allowed for this subscription. Leave empty if using billing period above.', 'cv-builder' ); ?></p>
                        </td>
                    </tr>

                    <tr>
                        <th><label for="product_status"><?php esc_html_e( 'Status', 'cv-builder' ); ?></label></th>
                        <td>
                            <select id="product_status" name="product_status" class="regular-text bwdcv-select-input">
                                <option value="publish" <?php selected( $product ? $product->get_status() : '', 'publish' ); ?>><?php esc_html_e( 'Published', 'cv-builder' ); ?></option>
                                <option value="draft" <?php selected( $product ? $product->get_status() : '', 'draft' ); ?>><?php esc_html_e( 'Draft', 'cv-builder' ); ?></option>
                            </select>
                        </td>
                    </tr>
                </table>

                <div class="cv-form-actions">
                    <button type="submit" class="button button-primary"><?php echo $edit_mode ? esc_html__( 'Update Product', 'cv-builder' ) : esc_html__( 'Save Product', 'cv-builder' ); ?></button>
                    <a href="<?php echo admin_url( 'admin.php?page=cv-subscription-products' ); ?>" class="button"><?php esc_html_e( 'Cancel', 'cv-builder' ); ?></a>
                </div>
            </form>
        </div>

        <?php
}

    public function save_product() {
        // Check user permissions
        if ( !current_user_can( 'manage_woocommerce' ) ) {
            return array( 'success' => false, 'message' => esc_html__( 'Insufficient permissions', 'cv-builder' ) );
        }

        try {
            // Extract and sanitize data
            $product_data = array(
                'title'                       => sanitize_text_field( $_POST['product_title'] ),
                'regular_price'               => floatval( $_POST['regular_price'] ),
                'sale_price'                  => !empty( $_POST['sale_price'] ) ? floatval( $_POST['sale_price'] ) : '',
                'image_id'                    => !empty( $_POST['product_image'] ) ? intval( $_POST['product_image'] ) : '',
                'short_description'           => sanitize_textarea_field( $_POST['short_description'] ),
                'subscription_plan_name'      => sanitize_text_field( $_POST['subscription_plan_name'] ),
                'subscription_billing_period' => sanitize_text_field( $_POST['subscription_billing_period'] ),
                'subscription_per_download'   => intval( $_POST['subscription_per_download'] ),
                'status'                      => isset( $_POST['product_status'] ) ? sanitize_text_field( $_POST['product_status'] ) : 'publish',
            );

            // Validate required fields
            $required_fields = array( 'title', 'regular_price' );
            foreach ( $required_fields as $field ) {
                if ( empty( $product_data[$field] ) ) {
                    return array( 'success' => false, 'message' => sprintf( esc_html__( 'Field %s is required', 'cv-builder' ), $field ) );
                }
            }

            $cv_category = get_term_by( 'slug', 'cv-subscription', 'product_cat' );
            if ( !$cv_category ) {
                return array( 'success' => false, 'message' => esc_html__( 'CV Subscription category not found', 'cv-builder' ) );
            }

            if ( isset( $_POST['product_id'] ) && !empty( $_POST['product_id'] ) ) {
                // Update existing product
                $product_id = intval( $_POST['product_id'] );
                $product = wc_get_product( $product_id );

                if ( !$product ) {
                    return array( 'success' => false, 'message' => esc_html__( 'Product not found', 'cv-builder' ) );
                }

                // Update post data
                wp_update_post( array(
                    'ID'           => $product_id,
                    'post_title'   => $product_data['title'],
                    'post_excerpt' => $product_data['short_description'],
                    'post_status'  => $product_data['status'],
                ) );

            } else {
                // Create new product
                $post_data = array(
                    'post_title'   => $product_data['title'],
                    'post_content' => '',
                    'post_excerpt' => $product_data['short_description'],
                    'post_status'  => $product_data['status'],
                    'post_type'    => 'product',
                );

                $product_id = wp_insert_post( $post_data );

                if ( is_wp_error( $product_id ) ) {
                    return array( 'success' => false, 'message' => esc_html__( 'Failed to create product', 'cv-builder' ) );
                }
            }

            // Set product type and basic properties
            wp_set_object_terms( $product_id, 'cv_subscription', 'product_type' );
            wp_set_object_terms( $product_id, array( $cv_category->term_id ), 'product_cat' );

            // Ensure product type meta is set correctly
            update_post_meta( $product_id, '_product_type', 'cv_subscription' );

            // Update product meta
            update_post_meta( $product_id, '_regular_price', $product_data['regular_price'] );
            update_post_meta( $product_id, '_price', $product_data['sale_price'] ?: $product_data['regular_price'] );

            if ( $product_data['sale_price'] ) {
                update_post_meta( $product_id, '_sale_price', $product_data['sale_price'] );
            } else {
                delete_post_meta( $product_id, '_sale_price' );
            }

            // Set image
            if ( $product_data['image_id'] ) {
                $attachment = get_post( $product_data['image_id'] );
                if ( $attachment && $attachment->post_type === 'attachment' ) {
                    set_post_thumbnail( $product_id, $product_data['image_id'] );
                    update_post_meta( $product_id, '_thumbnail_id', $product_data['image_id'] );
                }
            } else {
                delete_post_thumbnail( $product_id );
                delete_post_meta( $product_id, '_thumbnail_id' );
            }

            // Set as virtual and downloadable
            update_post_meta( $product_id, '_is_subscription', 'yes' );

            // Update custom subscription meta
            update_post_meta( $product_id, '_subscription_plan_name', $product_data['subscription_plan_name'] );
            update_post_meta( $product_id, '_subscription_billing_period', $product_data['subscription_billing_period'] );
            update_post_meta( $product_id, '_subscription_per_download', $product_data['subscription_per_download'] );

            // Clear cache
            wc_delete_product_transients( $product_id );

            return array(
                'success'    => true,
                'message'    => isset( $_POST['product_id'] ) ? esc_html__( 'Product updated successfully', 'cv-builder' ) : esc_html__( 'Product created successfully', 'cv-builder' ),
                'redirect'   => wp_redirect( admin_url( 'admin.php?page=cv-subscription-products' ) ),
                'product_id' => $product_id,
            );
        } catch ( Exception $e ) {
            return array( 'success' => false, 'message' => $e->getMessage() );
        }
    }

    public function delete_product( $product_id ) {
        $product = wc_get_product( $product_id );

        if ( !$product || ( $product->get_type() !== 'cv_subscription' && !$product->get_meta( '_subscription_plan_name' ) ) ) {
            add_action( 'admin_notices', function () {
                echo '<div class="notice notice-error"><p>' . esc_html__( 'Product not found or not a CV subscription product', 'cv-builder' ) . '</p></div>';
            } );
            return;
        }

        // Move to trash instead of permanent delete for safety
        $result = wp_trash_post( $product_id );

        if ( $result === false ) {
            add_action( 'admin_notices', function () {
                echo '<div class="notice notice-error"><p>' . esc_html__( 'Failed to delete product', 'cv-builder' ) . '</p></div>';
            } );
        } else {
            add_action( 'admin_notices', function () {
                echo '<div class="notice notice-success"><p>' . esc_html__( 'Product moved to trash successfully', 'cv-builder' ) . '</p></div>';
            } );
        }
    }
    /**
     *
     * For custom cv subscription plans (END)
     *
     */

    public function bwdcv_login_redirection( $user_login, $user ) {
        if ( !$user ) {
            return;
        }
        if ( !user_can( $user, 'cv_editor' ) ) {
            return;
        }
        $options = get_option( 'bwd_userfronted_options' );
        $redirect_url = get_permalink( $options['dashboard_page'] );
        if ( $redirect_url ) {
            wp_redirect( $redirect_url );
            exit;
        }
    }

    public function remove_post_author_date() {
        if ( is_singular( 'cv' ) ) {
            add_filter( 'the_author', '__return_false' );
            add_filter( 'get_the_author_display_name', '__return_false' );
            add_filter( 'the_date', '__return_false' );
            add_filter( 'the_time', '__return_false' );
            add_filter( 'get_the_date', '__return_false' );
            add_filter( 'get_the_time', '__return_false' );
        }
    }
    // Function to remove the title from single posts
    public function remove_title_from_single( $title, $id ) {
        if ( is_singular( 'cv' ) ) {
            return '';
        }
        return $title;
    }

    public function bwdcv_past_user_create_and_edit_page() {
        if ( !is_user_logged_in() || !current_user_can( 'edit_cvs' ) ) {
            wp_die( 'You do not have permission to access this page.' );
        }
        $user_id = get_current_user_id();
        $user_info = get_userdata( $user_id );
        $username = $user_info->user_login;

        // Create page
        $cv_page_id = wp_insert_post( array(
            'post_title'   => $username . "'s CV Page",
            'post_content' => '',
            'post_status'  => 'publish',
            'post_author'  => $user_id,
            'post_type'    => 'cv',
        ) );

        if ( !is_wp_error( $cv_page_id ) ) {
            update_user_meta( $user_id, 'cv_page_id', $cv_page_id );

            // Default block
            $bwdcvBlock = '
            <!-- wp:bwdcv/wp-cv-builder {"heading":"WP CV Builder","subheading":"A Block"} /-->
            ';
            wp_update_post( array(
                'ID'           => $cv_page_id,
                'post_content' => $bwdcvBlock,
            ) );

            delete_post_meta( $cv_page_id, '_wp_page_template' );

            // Edit page redirect
            wp_redirect( admin_url( 'post.php?post=' . $cv_page_id . '&action=edit' ) );
            exit;
        }
    }

    public function hide_admin_bar_items() {
        if ( current_user_can( 'cv_editor' ) ) {
            global $wp_admin_bar;
            $wp_admin_bar->remove_node( 'comments' );
            $wp_admin_bar->remove_node( 'new-content' );
            $wp_admin_bar->remove_node( 'view-site' );
        }
    }

    public function editor_access_denied_from_dashboard() {
        if ( current_user_can( 'cv_editor' ) && $this->is_dashboard() ) {
            update_user_meta( get_current_user_id(), 'admin_color', 'blue' );
            wp_die( 'You do not have sufficient permissions to access this page.' );
        }
    }

    public function is_dashboard() {
        if ( is_admin() ) {
            $screen = get_current_screen();
            return isset( $screen->base ) && in_array( $screen->base, array( 'dashboard', 'index' ) );
        }
        return false;
    }

    public function restrict_editor_access() {
        if ( current_user_can( 'cv_editor' ) ) {
            remove_menu_page( 'edit.php' );
            remove_menu_page( 'index.php' );
            remove_menu_page( 'edit.php?post_type=page' );
            remove_menu_page( 'upload.php' );
            remove_menu_page( 'profile.php' );
            remove_menu_page( 'admin.php' );
            remove_menu_page( 'wc-products' );
            remove_menu_page( 'tools.php' );
            remove_menu_page( 'edit-comments.php' );
            remove_menu_page( 'edit.php?post_type=product' );
            remove_menu_page( 'options-general.php' );

            remove_action( 'admin_notices', 'update_nag', 3 );
            remove_action( 'admin_notices', 'do_action' );
            remove_action( 'all_admin_notices', 'wp_admin_bar', 999 );
            remove_action( 'admin_notices', 'plugin_update_message' );
            remove_action( 'admin_notices', 'woocommerce_update_message' );
        }
    }

    public function block_direct_access_for_editor() {
        if ( current_user_can( 'cv_editor' ) ) {
            global $pagenow;
            $restricted_pages = array( 'edit.php', 'index.php', 'upload.php', 'profile.php', 'admin.php', 'tools.php', 'edit-comments.php', 'options-general.php' );
            if ( ( $pagenow === 'edit.php' && isset( $_GET['post_type'] ) && in_array( $_GET['post_type'], array( 'page', 'product', 'product_review' ) ) ) || in_array( $pagenow, $restricted_pages ) ) {
                wp_redirect( home_url() );
                exit;
            }
        }
    }

    public function dynamic_year_dropdown_activate() {
        if ( get_option( 'dynamic_year_dropdown_activation_date' ) === false ) {
            $activation_date = current_time( 'mysql' );
            add_option( 'dynamic_year_dropdown_activation_date', $activation_date );
        }
    }

    public function subscription_content_shortcode() {
        $query = new WP_Query( array(
            'post_type'      => 'product',
            'posts_per_page' => -1,
            'tax_query'      => array(
                array(
                    'taxonomy' => 'product_cat',
                    'field'    => 'slug',
                    'terms'    => 'cv-subscription',
                ),
            ),
        ) );
        if ( !$query->have_posts() ) {
            return '<p>No products found in the CV Subscription category.</p>';
        }

        ob_start();
        echo '<div class="cv-subscription-products">';
        while ( $query->have_posts() ) {
            $query->the_post();
            global $product;
            $categories = wp_get_post_terms( $product->get_id(), 'product_cat', array( 'fields' => 'slugs' ) );
            $is_cv_subscription = in_array( 'cv-subscription', $categories );
            $plan_name = $product->get_meta( '_subscription_plan_name', true );
            $per_download = $product->get_meta( '_subscription_per_download', true );
            $billing_period = $product->get_meta( '_subscription_billing_period', true );
            $is_subscription = get_post_meta( get_the_ID(), '_is_subscription', true );
            ?>
            <div class="bwdcv-product">
                <?php if ( has_post_thumbnail() ) {
                echo $product->get_image();
            }?>
                <h2 class="product-title"><?php the_title(); ?></h2>
                <p class="product-description"><?php echo $product->get_short_description(); ?></p>
                <p><?php echo $product->get_price_html(); ?></p>
                 <?php
        if ( !empty( $plan_name ) ) {
                $default = esc_html__( 'Plan Name:', 'cv-builder' );
                $planName = !empty( get_option( 'cv_plan_name_bwd', $default ) ) ? get_option( 'cv_plan_name_bwd', $default ) : '';
                echo '<p class="custom-meta cv-plan-name">' . esc_html( $planName ) . esc_html( $plan_name ) . '</p>';
            }
            if ( !empty( $per_download ) ) {
                $default = esc_html__( 'Per Download:', 'cv-builder' );
                $perDownload = !empty( get_option( 'cv_per_download_bwd', $default ) ) ? get_option( 'cv_per_download_bwd', $default ) : '';
                echo '<p class="custom-meta cv-per-download">' . esc_html( $perDownload ) . esc_html( $per_download ) . '</p>';
            }
            if ( !empty( $billing_period ) ) {
                $default = esc_html__( 'Billing Period:', 'cv-builder' );
                $billingPeriod = !empty( get_option( 'cv_billing_period_bwd', $default ) ) ? get_option( 'cv_billing_period_bwd', $default ) : '';
                $findDay = $billing_period == 1 ? 'Day' : 'Days';
                echo '<p class="custom-meta cv-billing-period">' . esc_html( $billingPeriod ) . esc_html( $billing_period ) . ' ' . esc_html( $findDay ) . '</p>';
            }
            ?>
                <?php if ( is_user_logged_in() ): ?>
                    <?php if ( has_term( 'cv-subscription', 'product_cat', $product->get_id() ) ): ?>
                        <?php $default = esc_html__( 'Subscribe', 'cv-builder' ); ?>
                        <a href="#" class="button custom-buy-now-button s-buy-now-btn" data-product-id="<?php echo esc_attr( $product->get_id() ); ?>">
                            <?php echo esc_html( get_option( 'cv_buy_now_text', $default ) ); ?>
                        </a>
                    <?php endif; ?>
                <?php else: ?>
                    <?php $options = get_option( 'bwd_userfronted_options' ); ?>
                    <a href="<?php echo esc_url( get_permalink( $options['registration_page'] ) ); ?>" class="button s-buy-now-btn">
                        <?php echo esc_html( get_option( 'cv_buy_now_text', $default ) ); ?>
                    </a>
                <?php endif; ?>
            </div>
            <?php
}
        echo '</div>';
        wp_reset_postdata();
        return ob_get_clean();
    }

    public function openai_api_handle_request() {
        $required_fields = ['userName', 'email', 'receiverName', 'companyName', 'userDesignation', 'tags', 'userInput'];

        foreach ( $required_fields as $field ) {
            if ( !isset( $_POST[$field] ) || empty( trim( $_POST[$field] ) ) ) {
                echo wp_json_encode( ['error' => 'Please fill in all fields.'] );
                wp_die();
            }
        }

        $userName = sanitize_text_field( $_POST['userName'] );
        $email = sanitize_email( $_POST['userEmail'] );
        $receiverName = sanitize_text_field( $_POST['receiverName'] );
        $companyName = sanitize_text_field( $_POST['companyName'] );
        $userDesignation = sanitize_text_field( $_POST['userDesignation'] );
        $tags = sanitize_text_field( $_POST['tags'] );
        $userInput = sanitize_textarea_field( $_POST['userInput'] );

        $prompt = "Generate a professional cover letter using the following details:
        Name: $userName
        Email: $email
        Receiver: $receiverName
        Company: $companyName
        Designation: $userDesignation
        Skills: $tags
        Description: $userInput
        Must follow below options:
        1. Give me a professional cover letter.
        2. Don't add any empty data.
        3. Must avoid all bracketed text.
        4. Must avoid extra line breaks.
        5. Please don't add extra information something.
        ";

        $apiKey = get_option( 'cv_openai_api_key_text', '' );

        $response = wp_remote_post( 'https://api.openai.com/v1/chat/completions', array(
            'body'    => wp_json_encode( array(
                'model'      => 'gpt-3.5-turbo',
                'messages'   => array(
                    array( 'role' => 'user', 'content' => $prompt ),
                ),
                'max_tokens' => 500,
            ) ),
            'headers' => array(
                'Content-Type'  => 'application/json',
                'Authorization' => 'Bearer ' . $apiKey,
            ),
        ) );

        if ( is_wp_error( $response ) ) {
            echo wp_json_encode( ['error' => $response->get_error_message()] );
        } else {
            $body = wp_remote_retrieve_body( $response );
            $data = json_decode( $body, true );
            if ( isset( $data['choices'] ) && count( $data['choices'] ) > 0 ) {
                echo wp_json_encode( ['response' => $data['choices'][0]['message']['content']] );
            } else {
                echo wp_json_encode( ['error' => 'No response from AI'] );
            }
        }

        wp_die();
    }

    public function bwdcv_cover_letter_api_ajax() {
        if ( current_user_can( 'cv_editor' ) ) {
            wp_enqueue_script( 'bwdcv-openai-api-script', plugin_dir_url( __FILE__ ) . '../assets/public/js/ai-api.js', array( 'jquery' ), null, true );
            wp_localize_script( 'bwdcv-openai-api-script', 'bwdcv_openai_api_vars', array(
                'api_url' => admin_url( 'admin-ajax.php' ),
            ) );
        }
    }

    private const ONES = [
        0  => 'zero', 1      => 'one', 2      => 'two', 3      => 'three', 4 => 'four',
        5  => 'five', 6      => 'six', 7      => 'seven', 8    => 'eight', 9 => 'nine',
        10 => 'ten', 11      => 'eleven', 12  => 'twelve', 13  => 'thirteen',
        14 => 'fourteen', 15 => 'fifteen', 16 => 'sixteen', 17 => 'seventeen',
        18 => 'eighteen', 19 => 'nineteen',
    ];

    private const TENS = [
        2 => 'twenty', 3 => 'thirty', 4  => 'forty', 5  => 'fifty',
        6 => 'sixty', 7  => 'seventy', 8 => 'eighty', 9 => 'ninety',
    ];

    private const OPERATORS = ['+', '-', '*'];

    /**
     * Convert a number to its word representation
     *
     * @param int $number The number to convert
     * @return string The word representation
     */
    public function dashToWords( int $number ): string {
        if ( $number < 0 ) {
            return 'negative ' . $this->dashToWords( abs( $number ) );
        }

        if ( $number < 20 ) {
            return self::ONES[$number];
        }

        if ( $number < 100 ) {
            return self::TENS[floor( $number / 10 )] . ( $number % 10 ? ' ' . self::ONES[$number % 10] : '' );
        }

        return 'Number too large';
    }

    public function dashboard_content_shortcode() {
        ob_start();
        if ( current_user_can( 'cv_editor' ) ) {
            include 'dashboard/user-dash.php';
        } else {
            $current_user = wp_get_current_user();
            $options = get_option( 'bwd_userfronted_options' );
            if ( is_user_logged_in() && !in_array( 'cv_editor', $current_user->roles ) ) {
                echo '<h2>Only CV register users can see the page.</h2> <p>Leave from current user and <a href="' . esc_url( wp_logout_url( get_permalink( $options['login_page'] ) ) ) . '">' . esc_html__( 'Login', 'cv-builder' ) . '</a> as CV user.</p>';
            } else {
                $getRegPageID = $options['registration_page'];
                $getLogPageID = $options['login_page'];
                echo '<h2>User not found. Please <a href="' . get_permalink( $getRegPageID ) . '">Sign Up</a> or <a href="' . get_permalink( $getLogPageID ) . '">' . esc_html__( 'Login', 'cv-builder' ) . '</a>.</h2>';
            }
        }
        return ob_get_clean();
    }

    public function cv_global_basic_syles() {
        include 'dashboard/custom-style.php';
    }

    public function clear_cart_before_add( $cart_item_key ) {
        $cart = WC()->cart;
        $added_product_id = $cart->get_cart_item( $cart_item_key )['product_id'];
        $is_cv_subscription = has_term( 'cv-subscription', 'product_cat', $added_product_id );

        foreach ( $cart->get_cart() as $key => $item ) {
            $product_id = $item['product_id'];
            if ( $is_cv_subscription ) {
                if ( $key !== $cart_item_key ) {
                    $cart->remove_cart_item( $key );
                }
            } else {
                if ( has_term( 'cv-subscription', 'product_cat', $product_id ) ) {
                    $cart->remove_cart_item( $key );
                }
            }
        }
    }

    public function product_add_once( $sold_individually, $product ) {
        if ( has_term( 'cv-subscription', 'product_cat', $product->get_id() ) ) {
            return true;
        }
        return $sold_individually;
    }

    public function customize_checkout_fields( $fields ) {
        $current_user = wp_get_current_user();
        // default values for billing fields
        $fields['billing']['billing_first_name']['default'] = $current_user->display_name;
        $fields['billing']['billing_email']['default'] = $current_user->user_email;
        // remove the fields
        unset( $fields['billing']['billing_company'] );
        unset( $fields['billing']['billing_country'] );

        unset( $fields['billing']['billing_last_name'] );
        unset( $fields['billing']['billing_phone'] );
        unset( $fields['billing']['billing_address_1'] );
        unset( $fields['billing']['billing_city'] );
        unset( $fields['billing']['billing_postcode'] );

        unset( $fields['order']['order_comments'] );

        return $fields;
    }
    public function process_checkout() {
        if ( !class_exists( 'WooCommerce' ) ) {
            wp_send_json_error( ['message' => esc_html__( 'WooCommerce is not active.', 'cv-builder' )] );
        }
        if ( isset( $_POST['checkout_data'] ) && !empty( $_POST['checkout_data'] ) ) {
            $checkout = WC()->checkout();
            $result = $checkout->process_checkout();
            if ( $result ) {
                wp_send_json_success( ['redirect_url' => wc_get_checkout_url()] );
            } else {
                wp_send_json_error( ['message' => esc_html__( 'There was an error processing your order.', 'cv-builder' )] );
            }
        } else {
            wp_send_json_error( ['message' => esc_html__( 'Checkout data is missing.', 'cv-builder' )] );
        }
    }

    public function exclude_category_from_shop( $query ) {
        if ( !is_admin() && $query->is_main_query() && is_shop() ) {
            $query->set( 'tax_query', array(
                array(
                    'taxonomy' => 'product_cat',
                    'field'    => 'slug',
                    'terms'    => 'cv-subscription',
                    'operator' => 'NOT IN',
                ),
            ) );
        }
    }

    public function clear_cart_page() {
        if ( is_checkout() && isset( $_POST['clear_cart'] ) && $_POST['clear_cart'] == 1 ) {
            WC()->cart->empty_cart();
            if ( isset( $_POST['add-to-cart'] ) ) {
                $product_id = intval( $_POST['add-to-cart'] );
                if ( wc_get_product( $product_id ) ) {
                    WC()->cart->add_to_cart( $product_id );
                }
            }
        }
    }

    public function bwdcv_load_checkout_in_popup() {
        ob_start();
        echo do_shortcode( '[woocommerce_checkout]' );
        $checkout_content = ob_get_clean();
        wp_send_json_success( $checkout_content );
    }

    public function ensure_cart_initialization() {
        if ( is_page() || ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
            if ( null === WC()->cart ) {
                WC()->cart = new WC_Cart();
            }
        }

        /**
         *
         * Page redirect to CV page after order completion
         *
         */
        if ( !is_wc_endpoint_url( 'order-received' ) ) {
            return;
        }

        if ( !is_user_logged_in() ) {
            return;
        }

        $order_id = absint( get_query_var( 'order-received' ) );

        if ( !$order_id ) {
            return;
        }

        $order = wc_get_order( $order_id );
        if ( !$order || !$order->is_paid() ) {
            return;
        }

        $has_cv_subscription = false;
        foreach ( $order->get_items() as $item ) {
            $product_id = $item->get_product_id();
            $terms = get_the_terms( $product_id, 'product_cat' );
            if ( !empty( $terms ) ) {
                foreach ( $terms as $term ) {
                    if ( $term->slug === 'cv-subscription' ) {
                        $has_cv_subscription = true;
                        break 2;
                    }
                }
            }
        }

        if ( $has_cv_subscription ) {
            $user_id = get_current_user_id();

            $args = array(
                'post_type'      => 'cv',
                'post_status'    => 'publish',
                'author'         => $user_id,
                'posts_per_page' => 1,
            );

            $query = new WP_Query( $args );
            if ( $query->have_posts() ) {
                $query->the_post();
                $url = get_permalink();
                wp_reset_postdata();

                // Prevent infinite loop
                if ( !is_page( $url ) ) {
                    wp_safe_redirect( $url );
                    exit;
                }
            }
        }
    }

    public function bwdcv_add_to_cart_and_checkout() {
        if ( !isset( $_POST['product_id'] ) || !is_numeric( $_POST['product_id'] ) ) {
            wp_send_json_error( ['message' => esc_html__( 'Invalid product ID.', 'cv-builder' )] );
        }
        $product_id = intval( $_POST['product_id'] );
        WC()->cart->add_to_cart( $product_id );
        wp_send_json_success( ['message' => esc_html__( 'Product added to cart.', 'cv-builder' )] );
    }

    public function bwdcv_all_assets_for_the_checkout_ajax() {
        $current_user = wp_get_current_user();
        if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
            wp_enqueue_script( 'wc-checkout' );
            wp_enqueue_script( 'woocommerce' );
            wp_enqueue_script( 'wc-cart' );
            wp_enqueue_script( 'jquery' );
            wp_enqueue_style( 'woocommerce-general' );
            wp_enqueue_style( 'woocommerce-checkout' );
        }
        wp_enqueue_script( 'bwdcv-custom-popup-script', plugin_dir_url( __FILE__ ) . '../assets/public/js/custom-popup.js', array( 'jquery' ), '1.0', true );
        wp_enqueue_style( 'bwdcv-custom-style-script', plugin_dir_url( __FILE__ ) . '../assets/public/css/custom-popup.css', null, '1.0', 'all' );
        wp_localize_script( 'bwdcv-custom-popup-script', 'bwdcv_popup_ajax', array(
            'ajax_url'     => admin_url( 'admin-ajax.php' ),
            'display_name' => $current_user->display_name,
            'user_email'   => $current_user->user_email,
        ) );

        wp_enqueue_script( 'bwdcv-custom-ajax', plugin_dir_url( __FILE__ ) . '../assets/public/js/loading-popup.js', ['jquery'], null, true );
        wp_localize_script( 'bwdcv-custom-ajax', 'bwdcv_ajax_object', [
            'ajax_url' => admin_url( 'admin-ajax.php' ),
        ] );

    }

    public function bwdcv_to_get_checkout_form() {
        ?>
        <div id="checkout-popup">
            <button id="close-popup">&times;</button>
            <div id="checkout-content">
                <p>Loading...</p>
            </div>
        </div>
        <div id="popup-overlay" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:999;"></div>

        <div id="bwdcv-loading-popup" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:9999; text-align:center;">
            <div style="position:absolute; top:50%; left:50%; transform:translate(-50%, -50%); background:#fff; padding:20px; border-radius:5px;">
                <div class="loader"></div>
                <p>Processing payment... Please wait</p>
            </div>
        </div>
        <?php
// Enqueue the Cloudflare Turnstile script
        echo '<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>';
    }

    public function set_default_product_category( $post_id ) {
        if ( get_post_type( $post_id ) !== 'product' || wp_is_post_revision( $post_id ) ) {
            return;
        }
        $default_category = get_term_by( 'slug', 'cv-subscription', 'product_cat' );
        if ( empty( wp_get_post_terms( $post_id, 'product_cat' ) ) ) {
            wp_set_post_terms( $post_id, array( $default_category->term_id ), 'product_cat' );
        }
    }

    public function add_subscription_checkbox( $product_type_options ) {
        if ( !is_array( $product_type_options ) ) {
            $product_type_options = [];
        }
        $product_type_options['subscription'] = array(
            'id'            => '_is_subscription',
            'wrapper_class' => 'show_if_simple',
            'label'         => esc_html__( 'CV Subscription', 'cv-builder' ),
            'description'   => esc_html__( 'Enable this product as a subscription.', 'cv-builder' ),
            'default'       => 'no',
        );
        return $product_type_options;
    }

    public function save_subscription_checkbox_value( $post_id, $post, $update ) {
        if ( 'product' != $post->post_type ) {
            return;
        }
        if ( isset( $_POST['_is_subscription'] ) ) {
            update_post_meta( $post_id, '_is_subscription', 'yes' );
        } else {
            update_post_meta( $post_id, '_is_subscription', 'no' );
        }
    }

    public function load_subscription_checkbox_value() {
        global $post;
        $is_subscription = get_post_meta( $post->ID, '_is_subscription', true );
        if ( empty( $is_subscription ) ) {
            $is_subscription = 'no';
        }
        ?>
        <script type="text/javascript">
            jQuery(document).ready(function() {
                if ('<?php echo esc_js( $is_subscription ); ?>' === 'yes') {
                    jQuery('#_is_subscription').prop('checked', true);
                }
            });
        </script>
        <?php
}

    public function subscription_settings_content() {
        echo '<div id="subscription_settings_data" class="panel woocommerce_options_panel hidden">';
        echo '<div class="options_group">';
        woocommerce_wp_text_input( array(
            'id'          => '_subscription_plan_name',
            'label'       => esc_html__( 'Plan Name', 'cv-builder' ),
            'default'     => esc_html__( 'Premium', 'cv-builder' ),
            'description' => esc_html__( 'Enter the plan name', 'cv-builder' ),
            'desc_tip'    => true,
        ) );
        woocommerce_wp_text_input( array(
            'id'                => '_subscription_per_download',
            'label'             => esc_html__( 'Download CV Number', 'cv-builder' ),
            'description'       => esc_html__( 'Enter the number of downloads allowed for this subscription.', 'cv-builder' ),
            'desc_tip'          => true,
            'type'              => 'number',
            'custom_attributes' => array(
                'min' => '1',
            ),
        ) );
        woocommerce_wp_select( [
            'id'      => '_subscription_billing_period',
            'label'   => esc_html__( 'Billing Period', 'cv-builder' ),
            'options' => [
                ''    => esc_html__( 'Choose a billing period', 'cv-builder' ),
                '1'   => esc_html__( 'Daily', 'cv-builder' ),
                '30'  => esc_html__( 'Monthly', 'cv-builder' ),
                '90'  => esc_html__( 'Three Month', 'cv-builder' ),
                '183' => esc_html__( 'Half Year', 'cv-builder' ),
                '365' => esc_html__( 'Yearly', 'cv-builder' ),
            ],
        ] );
        echo '</div>';
        echo '</div>';
    }

    public function save_subscription_data( $post_id ) {
        // Save the Subscription Checkbox value.
        if ( isset( $_POST['_is_subscription'] ) ) {
            update_post_meta( $post_id, '_is_subscription', 'yes' );
        } else {
            update_post_meta( $post_id, '_is_subscription', 'no' );
        }
        if ( isset( $_POST['_subscription_plan_name'] ) ) {
            update_post_meta( $post_id, '_subscription_plan_name', sanitize_text_field( $_POST['_subscription_plan_name'] ) );
        }
        if ( isset( $_POST['_subscription_per_download'] ) ) {
            update_post_meta( $post_id, '_subscription_per_download', sanitize_text_field( $_POST['_subscription_per_download'] ) );
        }
        if ( isset( $_POST['_subscription_billing_period'] ) ) {
            update_post_meta( $post_id, '_subscription_billing_period', sanitize_text_field( $_POST['_subscription_billing_period'] ) );
        }
    }

    // Data Display on Shop Page
    public function subscription_data_to_shop_page() {
        global $product;
        $plan_name = get_post_meta( $product->get_id(), '_subscription_plan_name', true );
        $cv_download = get_post_meta( $product->get_id(), '_subscription_per_download', true );
        $billing_period = get_post_meta( $product->get_id(), '_subscription_billing_period', true );
        if ( !empty( $plan_name ) ) {
            echo '<div class="subscription-details">';
            echo '<p>' . sprintf(
                esc_html__( 'Plan Name: %s', 'cv-builder' ),
                esc_html( $plan_name )
            ) . '</p>';
            if ( !empty( $cv_download ) ) {
                echo '<p>' . sprintf(
                    esc_html__( 'Downloads: %s', 'cv-builder' ),
                    esc_html( $cv_download )
                ) . '</p>';
            }
            if ( empty( $cv_download ) && !empty( $billing_period ) ) {
                echo '<p>' . sprintf(
                    esc_html__( 'Billing Period: %s', 'cv-builder' ),
                    esc_html( $billing_period )
                ) . ' Days</p>';
            }
            echo '</div>';
        }
    }

    public function add_unique_class_to_product_card( $classes, $post_id ) {
        if ( 'product' === get_post_type( $post_id ) ) {
            $terms = get_the_terms( $post_id, 'product_cat' );
            if ( $terms && !is_wp_error( $terms ) ) {
                foreach ( $terms as $term ) {
                    if ( $term->slug === 'cv-subscription' ) {
                        $classes[] = 'bwdcv-product-card';
                        break;
                    }
                }
            }
        }
        return $classes;
    }

    public function display_subscriptions_data() {
        include 'dashboard/display-subscription.php';
    }

    // Add custom button
    public function add_custom_button_to_shop_page() {
        global $product;
        if ( is_user_logged_in() ) {
            if ( has_term( 'cv-subscription', 'product_cat', $product->get_id() ) ) {?>
                <a href="#" class="button custom-buy-now-button s-buy-now-btn" data-product-id="<?php echo esc_attr( $product->get_id() ); ?>">
                    <?php echo esc_html( get_option( 'cv_buy_now_text', esc_html__( 'Subscribe', 'cv-builder' ) ) ); ?>
                </a>
                <?php
}
        } else {
            $options = get_option( 'bwd_userfronted_options' );
            ?>
            <a href="<?php echo get_permalink( $options['registration_page'] ); ?>" class="button s-buy-now-btn">
                <?php echo esc_html( get_option( 'cv_buy_now_text', esc_html__( 'Subscribe', 'cv-builder' ) ) ); ?>
            </a>
            <?php
}
    }

    // cart item data
    public function add_subscription_data_to_cart_item( $cart_item_data, $product_id ) {
        $cart_item_data['subscription_plan_name'] = get_post_meta( $product_id, '_subscription_plan_name', true );
        $cart_item_data['subscription_per_download'] = get_post_meta( $product_id, '_subscription_per_download', true );
        $cart_item_data['subscription_billing_period'] = get_post_meta( $product_id, '_subscription_billing_period', true );

        return $cart_item_data;
    }

    public function add_subscription_data_to_order( $item, $cart_item_key, $values, $order ) {
        if ( isset( $values['subscription_plan_name'] ) ) {
            $item->add_meta_data( esc_html__( 'Subscription Plan Name', 'cv-builder' ), $values['subscription_plan_name'] );
        }
        if ( isset( $values['subscription_per_download'] ) ) {
            $item->add_meta_data( esc_html__( 'Subscription Per Download', 'cv-builder' ), $values['subscription_per_download'] );
        }
        if ( isset( $values['subscription_billing_period'] ) ) {
            if ( $values['subscription_billing_period'] ) {
                $daysCheck = $values['subscription_billing_period'] == 1 ? ' Day' : 'Days';
                $item->add_meta_data( esc_html__( 'Subscription Billing Period', 'cv-builder' ), $values['subscription_billing_period'] . $daysCheck );
            }
        }
    }

}

new BWD_Subscription_settings();
