<?php

namespace Bestwpdeveloper\CVBuilder;

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

define( "BWDCV_ASFSK_ASSETS_PUBLIC_DIR_FILE", plugin_dir_url( __FILE__ ) . "assets/public" );
define( "BWDCV_ASFSK_ASSETS_ADMIN_DIR_FILE", plugin_dir_url( __FILE__ ) . "assets/admin" );

class ClassBWDCVvilder {

    private static $_instance = null;
    public static function instance() {
        if ( is_null( self::$_instance ) ) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function bwdcv_all_assets_for_the_public() {

        $asset_url = plugin_dir_url( __FILE__ ) . 'assets/public/';

        /* -----------------------------
         * License Check
         * ----------------------------- */
        $license_status = 'deactivate';
        if ( class_exists( 'BWDCV_BLOCKS_CLASS_PRO' ) ) {
            $license_status = \BWDCV_BLOCKS_CLASS_PRO::instance()->bwdcv_get_license_status();
        }
        if ( $license_status == 'activate' && is_singular() ) {
            global $post;
            $page_author_id = $post->post_author;
            $customer_orders = wc_get_orders( array(
                'customer_id' => $page_author_id,
                'status'      => ['completed', 'processing'],
                'limit'       => -1,
            ) );
            if ( !empty( $customer_orders ) ) {
                $has_subscription_meta = false;
                foreach ( $customer_orders as $order ) {
                    $items = $order->get_items();
                    $purchase_date = $order->get_date_created();
                    $formatted_purchase_date = $purchase_date ?
                    $purchase_date->setTimezone( new \DateTimeZone( wp_timezone_string() ) )->format( 'Y-m-d' ) : esc_html__( 'N/A', 'cv-builder' );

                    foreach ( $items as $item ) {
                        $product_id = $item->get_product_id();
                            $cv_download = $order->get_meta( '_subscription_per_download', true );
                            if ( $cv_download === '' || $cv_download === null || $cv_download === false ) {
                                $cv_download = get_post_meta( $product_id, '_subscription_per_download', true );
                                $cv_download = is_numeric( $cv_download ) ? (int) $cv_download : 0;
                                $order->update_meta_data( '_subscription_per_download', $cv_download );
                                $order->save();
                            } else {
                                $cv_download = is_numeric( $cv_download ) ? (int) $cv_download : 0;
                            }
                        $subscription_billing_period = (int) $order->get_meta( '_subscription_billing_period', true );
                        if ( !$subscription_billing_period ) {
                            $subscription_billing_period = get_post_meta( $product_id, '_subscription_billing_period', true );
                            $order->update_meta_data( '_subscription_billing_period', $subscription_billing_period );
                            $order->save();
                        }
                        $expire_date = '';
                        if ( $subscription_billing_period ) {
                            $billing_days = 0;
                            if ( $subscription_billing_period == '1' ) {
                                $billing_days = 1;
                            } elseif ( $subscription_billing_period == '30' ) {
                                $billing_days = 30;
                            } elseif ( $subscription_billing_period == '90' ) {
                                $billing_days = 90;
                            } elseif ( $subscription_billing_period == '183' ) {
                                $billing_days = 183;
                            } elseif ( $subscription_billing_period == '365' ) {
                                $billing_days = 365;
                            }
                            if ( $purchase_date && $billing_days ) {
                                $purchase_date_obj = new \DateTime( $formatted_purchase_date );
                                $purchase_date_obj->modify( "+$billing_days days" );
                                $newDate = $purchase_date_obj->format( 'Y-m-d' );
                                $expire_date = $subscription_billing_period ? $newDate : '';
                            }
                        } else {
                            $expire_date = esc_html__( 'Unlimited', 'cv-builder' );
                        }
                        $expireCheck = '';
                        if ( \DateTime::createFromFormat( 'Y-m-d', $expire_date ) !== false ) {
                            $expireCheck = $expire_date;
                        }
                        $current_date = date( "Y-m-d" );
                        if ( !$cv_download >= 1 || !$current_date <= $expireCheck ) {
                            if ( !empty( $cv_download ) || !empty( $subscription_billing_period ) ) {
                                $has_subscription_meta = true;
                                break 2;
                            }
                        }
                    }
                }

                if ( $has_subscription_meta == false ) {
                    wp_enqueue_script( 'bwdcv-watermark', $asset_url . 'js/watermark.js', array( 'jquery' ), BWDCV_VERSION, true );
                }
            }
        }

        /* -----------------------------
         * Core Libraries
         * ----------------------------- */

        wp_enqueue_script( 'bwdcv-html2canvas', $asset_url . 'lib/js/html2canvas.min.js', array(), '1.4.1', true );
        wp_enqueue_script( 'bwdcv-jspdf', $asset_url . 'lib/js/jspdf.umd.min.js', array(), '2.5.1', true );
        wp_enqueue_script( 'bwdcv-arabic-reshaper', $asset_url . 'lib/js/index.min.js', array(), '1.0.0', true );

        wp_enqueue_script( 'bwdcv-qr-code', $asset_url . 'lib/js/qrcode.min.js', array( 'jquery' ), '1.0.0', true );

        /* -----------------------------
         * Plugin Scripts
         * ----------------------------- */

        wp_localize_script( 'bwdcv-watermark', 'bwdcvSettings', [
          
            /*
            * For text
            */
            'wCV2Allow'            => get_option( 'w_cv_2allow' ),
            'wCVAllow'             => get_option( 'w_cv_allow', 'on' ),
            'wTextImageAllow'      => get_option( 'w_text_img_allow', 'w-text' ),
            'wImageURL'            => get_option( 'w_image_url', plugin_dir_url( __FILE__ ) . 'assets/public/img/bestwpdeveloper.svg' ),
            'watermarkText'        => get_option( 'watermark_text', 'BWD' ),
        
            /*
            * Settings
            */
            'wRightClickCheck'     => get_option( 'w_right_click_check', 'off' ),
            'wDeveloperToolsCheck' => get_option( 'w_developer_tools_check', 'off' ),
            'imgOpacity'           => get_option( 'w_img_opacity_value', 1 ),
            'textRotation'         => get_option( 'w_text_rotation', '' ),
            /*
            * Styles
            */
            'textColor'            => get_option( 'w_text_color', '#a5a5a52e' ),
            'fontSize'             => get_option( 'w_text_font_value', 30 ),
            'fontFamily'           => get_option( 'w_text_font_family', 'Arial' ),
            'fontWeight'           => get_option( 'w_text_font_weight', '400' ),
            'fontStyle'            => get_option( 'w_text_font_style', 'normal' ),
        ] );

        wp_enqueue_script(
            'bwdcv-qr-page-link',
            $asset_url . 'js/qr-page-link.js',
            array( 'bwdcv-qr-code' ),
            BWDCV_VERSION,
            true
        );

        wp_enqueue_script(
            'bwdcv_cv_min_js',
            $asset_url . 'js/min.js',
            array( 'jquery', 'bwdcv-jspdf', 'bwdcv-html2canvas', 'bwdcv-arabic-reshaper' ),
            BWDCV_VERSION,
            true
        );

        wp_enqueue_script(
            'bwdcv-cv-scripts',
            $asset_url . 'js/scripts.js',
            array( 'jquery' ),
            BWDCV_VERSION,
            true
        );

        /* -----------------------------
         * Styles
         * ----------------------------- */

        wp_enqueue_style( 'bwdcv-style', $asset_url . 'css/style.css', array(), BWDCV_VERSION );
        wp_enqueue_style( 'bwdcv-subscription', $asset_url . 'css/subscription-list.css', array(), BWDCV_VERSION );
        wp_enqueue_style( 'bwdcv_cv_builder_user_dashboard', $asset_url . 'css/user-dashboard.css', array(), BWDCV_VERSION );
        wp_enqueue_style( 'font-awesome-cov', $asset_url . 'lib/css/all.min.css', array(), '6.5.1' );

        /* -----------------------------
         * Download Count
         * ----------------------------- */

        if ( apply_filters( 'bwdcv_download_handle_js', true ) && get_option( 'w_cv_2allow' ) !== 'on' ) {

            wp_enqueue_script( 'bwdcv-custom-script', $asset_url . 'js/download-count.js', array( 'jquery' ), BWDCV_VERSION, true );

            wp_localize_script( 'bwdcv-custom-script', 'bwd_ajax_object', [
                'ajax_url' => admin_url( 'admin-ajax.php' ),
                'security' => wp_create_nonce( 'bwd_download_nonce' ),
            ] );
        }

        /* -----------------------------
         * Datatables
         * ----------------------------- */

        wp_enqueue_style( 'bwdcv-user-dashboard', BWDCV_ASFSK_ASSETS_ADMIN_DIR_FILE . '/css/datatables.min.css', array(), BWDCV_VERSION, 'all' );
        wp_enqueue_script( 'bwdcv-user-dashboard', BWDCV_ASFSK_ASSETS_ADMIN_DIR_FILE . '/js/datatables.min.js', array( 'jquery' ), BWDCV_VERSION, true );
        wp_enqueue_style( 'bwdcv-user-dashboard-responsivec', BWDCV_ASFSK_ASSETS_ADMIN_DIR_FILE . '/css/responsive.dataTables.min.css', array(), BWDCV_VERSION, 'all' );
        wp_enqueue_script( 'bwdcv-user-dashboard-responsive', BWDCV_ASFSK_ASSETS_ADMIN_DIR_FILE . '/js/dataTables.responsive.min.js', array( 'jquery' ), BWDCV_VERSION, true );

    }

    public function bwdcv_all_assets_for_the_admin( $hook ) {

        $asset_url = plugin_dir_url( __FILE__ ) . 'assets/admin/';

        $allowed_pages = array(
            'toplevel_page_wp-cv-builder',
            'wp-cv-builder_page_bwdcv-cv-settings',
            'wp-cv-builder_page_subscription-settings',
            'wp-cv-builder_page_cv-subscription-products',
            'wp-cv-builder_page_subscription-orders',
        );

        /* -----------------------------
         * Welcome Screen
         * ----------------------------- */

        if ( $hook === 'toplevel_page_wp-cv-builder' ) {

            wp_enqueue_style( 'bwdcv-welcome-screen-bootstrap', $asset_url . 'lib/css/bootstrap.min.css', array(), BWDCV_VERSION, 'all' );
            wp_enqueue_style( 'bwdcv-welcome-screen-style', $asset_url . 'welcome-screen/cv.css', array(), BWDCV_VERSION, 'all' );
            wp_enqueue_style( 'bwdcv-welcome-screen-nice-select', $asset_url . 'welcome-screen/nice-select.css', array(), BWDCV_VERSION, 'all' );
            wp_enqueue_script( 'bwdcv-welcome-screen-googleapis', $asset_url . 'lib/js/jquery.min.js', array( 'jquery' ), BWDCV_VERSION, true );
            wp_enqueue_script( 'bwdcv-welcome-screen-chart', $asset_url . 'lib/js/chart.js', array( 'jquery' ), BWDCV_VERSION, true );
            wp_enqueue_script( 'bwdcv-welcome-screen-cv', $asset_url . 'welcome-screen/cv.js', array( 'jquery' ), BWDCV_VERSION, true );
            wp_enqueue_script( 'bwdcv-welcome-screen-script', $asset_url . 'welcome-screen/script.js', array( 'jquery' ), BWDCV_VERSION, true );
            wp_enqueue_script( 'bwdcv-welcome-screen-nice-select', $asset_url . 'welcome-screen/jquery.nice-select.min.js', array( 'jquery' ), BWDCV_VERSION, true );
            wp_enqueue_script( 'bwdcv-cv-informations-script', $asset_url . 'js/cv-informations.js', array( 'jquery' ), BWDCV_VERSION, true );
        }

        /* -----------------------------
         * Subscription Orders Page
         * ----------------------------- */

        if ( $hook === 'wp-cv-builder_page_subscription-orders' ) {

            wp_enqueue_script( 'bwdcv-subs-filter-script', $asset_url . 'js/subs-filter.js', array( 'jquery' ), BWDCV_VERSION, true );
            wp_enqueue_style( 'bwdcv-s-tab-select2', $asset_url . 'lib/css/select2.min.css', array(), BWDCV_VERSION, 'all' );
            wp_enqueue_script( 'bwdcv-subs-filter-select2', $asset_url . 'lib/js/select2.min.js', array( 'jquery' ), BWDCV_VERSION, true );
        }

        /* -----------------------------
         * DataTables (Settings + Orders + Products)
         * ----------------------------- */

        if (
            in_array(
                $hook,
                array(
                    'toplevel_page_wp-cv-builder',
                    'wp-cv-builder_page_bwdcv-cv-settings',
                    'wp-cv-builder_page_cv-subscription-products',
                    'wp-cv-builder_page_subscription-orders',
                    'wp-cv-builder_page_cv-add-product',
                ),
                true
            )
        ) {

            wp_enqueue_style( 'bwdcv-datatables', $asset_url . '/css/datatables.min.css', array(), BWDCV_VERSION, 'all' );
            wp_enqueue_script( 'bwdcv-datatables', $asset_url . '/js/datatables.min.js', array( 'jquery' ), BWDCV_VERSION, true );

            wp_enqueue_style( 'bwdcv-datatables-responsivec', $asset_url . '/css/responsive.dataTables.min.css', array(), BWDCV_VERSION, 'all' );
            wp_enqueue_script( 'bwdcv-datatables-responsive', $asset_url . '/js/dataTables.responsive.min.js', array( 'jquery' ), BWDCV_VERSION, true );

            wp_enqueue_style( 'bwdcv-s-tab-style', $asset_url . 's-tab/style.css', array(), BWDCV_VERSION, 'all' );
            wp_enqueue_script( 'bwdcv-s-tab-script', $asset_url . 's-tab/script.js', array( 'jquery' ), BWDCV_VERSION, true );
            wp_enqueue_script( 'bwdcv-s-tab-scripts', $asset_url . 's-tab/scripts.js', array( 'jquery' ), BWDCV_VERSION, true );
            wp_enqueue_media();
            wp_enqueue_script( 'wp-color-picker' );
            wp_enqueue_style( 'wp-color-picker' );

            wp_enqueue_style( 'bwdcv-nice-select', $asset_url . 'css/nice-select.css', array(), BWDCV_VERSION, 'all' );
            wp_enqueue_script( 'bwdcv-nice-select', $asset_url . 'js/jquery.nice-select.min.js', array( 'jquery' ), BWDCV_VERSION, true );
        }

        wp_enqueue_script( 'bwdcv-cv-subscription-orders', $asset_url . 'js/subscription-settings.js', array( 'jquery' ), BWDCV_VERSION, true );
        wp_enqueue_style( 'bwdcv-subscription-add-style', $asset_url . 'css/subscription-add.css', array(), BWDCV_VERSION, 'all' );

    }

    public function bwd_handle_pdf_download() {
        check_ajax_referer( 'bwd_download_nonce', 'security' );

        $order_id = isset( $_POST['order_id'] ) ? absint( $_POST['order_id'] ) : 0;
        $cv_download = isset( $_POST['cv_download'] ) ? absint( $_POST['cv_download'] ) : 0;
        $subscription_billing_period = isset( $_POST['subscription_billing_period'] ) ? sanitize_text_field( $_POST['subscription_billing_period'] ) : '';
        $template_style = isset( $_POST['template_style'] ) ? sanitize_text_field( $_POST['template_style'] ) : '';

        /*
        * Handle subscription/pro downloads
        */
        if ( $order_id && ( $cv_download > 0 || !empty( $subscription_billing_period ) ) ) {
            $billing_days = 0;

            if ( !empty( $subscription_billing_period ) ) {
                switch ( $subscription_billing_period ) {
                case '1':$billing_days = 1;
                    break;
                case '30':$billing_days = 30;
                    break;
                case '90':$billing_days = 90;
                    break;
                case '183':$billing_days = 183;
                    break;
                case '365':$billing_days = 365;
                    break;
                }

                if ( $billing_days > 0 ) {
                    $order = wc_get_order( $order_id );
                    if ( $order ) {
                        $order_date = $order->get_date_created();
                        if ( $order_date ) {
                            $expiration_date = $order_date->modify( "+{$billing_days} days" );
                            $current_date = new \DateTime();
                            if ( $current_date >= $expiration_date ) {
                                wp_send_json_error( ['message' => esc_html__( 'Your subscription has expired.', 'cv-builder' )] );
                                return;
                            }
                        }
                    } else {
                        wp_send_json_error( ['message' => esc_html__( 'Order not found.', 'cv-builder' )] );
                        return;
                    }
                }
            }

            if ( $cv_download > 0 ) {
                $cv_download -= 1;
            }

            $order = wc_get_order( $order_id );
            if ( $order ) {
                $order->update_meta_data( '_subscription_per_download', $cv_download );
                $total_downloads = (int) $order->get_meta( '_total_downloads', true );
                $total_downloads += 1;
                $order->update_meta_data( '_total_downloads', $total_downloads );
                $order->save();

                $homeURL = home_url();
                $current_user = wp_get_current_user();
                $username = $homeURL . '/cv/' . $current_user->user_login . 's-cv-page';

                if ( $username ) {
                    wp_send_json_success( [
                        'message'             => esc_html__( 'Download successful!', 'cv-builder' ),
                        'remaining_downloads' => $cv_download,
                        'total_downloads'     => $total_downloads,
                    ] );
                    return;
                }
            }

            wp_send_json_error( ['message' => esc_html__( 'Order processing failed.', 'cv-builder' )] );
            return;
        }

        
        /*
        * Handle free downloads
        */
        if ( !empty( $template_style ) ) {
            $style_number = preg_replace( '/[^0-9]/', '', $template_style );

            if ( !empty( $style_number ) ) {
                $main_options = get_option( 'bwdcv_preview_options', array() );
                $cvAllowStyleKey = 'cv_allow_style' . $style_number;
                $isTemplatePro = isset( $main_options[$cvAllowStyleKey] ) && $main_options[$cvAllowStyleKey];

                if ( !$isTemplatePro ) {
                    $homeURL = home_url();
                    $current_user = wp_get_current_user();
                    $username = $homeURL . '/cv/' . $current_user->user_login . 's-cv-page';

                    if ( $username ) {
                         wp_send_json_success( [
                            'message' => esc_html__( 'Free download successful!', 'cv-builder' ),
                        ] );
                        return;
                    }
                }
            }
        }
        wp_send_json_error( ['message' => esc_html__( 'Please upgrade to download this premium template.', 'cv-builder' )] );
    }

    /*
    * Settings register
    */
    public function insert_registration_shortcode() {
        $options = get_option( 'bwd_userfronted_options' );
        $registration_page_id = isset( $options['registration_page'] ) ? $options['registration_page'] : '';
        if ( !empty( $registration_page_id ) && get_post_type( $registration_page_id ) === 'page' ) {
            $post_content = get_post_field( 'post_content', $registration_page_id );
            if ( strpos( $post_content, '[custom_registration]' ) === false ) {
                $post_content .= "\n[custom_registration]";
                wp_update_post( array(
                    'ID'           => $registration_page_id,
                    'post_content' => $post_content,
                ) );
            }
        }
    }

    /*
    * Settings sub
    */
    public function insert_sub_shortcode() {
        $options = get_option( 'bwd_userfronted_options' );
        $subscription_page_id = isset( $options['subscription_page'] ) ? $options['subscription_page'] : '';
        if ( !empty( $subscription_page_id ) && get_post_type( $subscription_page_id ) === 'page' ) {
            $post_content = get_post_field( 'post_content', $subscription_page_id );
            if ( strpos( $post_content, '[subscription_product]' ) === false ) {
                $post_content .= "\n[subscription_product]";
                wp_update_post( array(
                    'ID'           => $subscription_page_id,
                    'post_content' => $post_content,
                ) );
            }
        }
    }

    /*
    * Settings dashboard
    */
    public function insert_dashboard_shortcode() {
        $options = get_option( 'bwd_userfronted_options' );
        $dashboard_page_id = isset( $options['dashboard_page'] ) ? $options['dashboard_page'] : '';
        if ( !empty( $dashboard_page_id ) && get_post_type( $dashboard_page_id ) === 'page' ) {
            $post_content = get_post_field( 'post_content', $dashboard_page_id );
            if ( strpos( $post_content, '[cv_dashboard_setting]' ) === false ) {
                $post_content .= "\n[cv_dashboard_setting]";
                wp_update_post( array(
                    'ID'           => $dashboard_page_id,
                    'post_content' => $post_content,
                ) );
            }
        }
    }

    public function register_settings() {
        if ( current_user_can( 'cv_editor' ) ) {
            remove_all_actions( 'admin_notices' );
            remove_all_actions( 'all_admin_notices' );
            remove_all_actions( 'network_admin_notices' );
            remove_all_actions( 'user_admin_notices' );
        }

        register_setting(
            'bwd_userfronted_options',
            'bwd_userfronted_options',
            [
                'type'              => 'array',
                'sanitize_callback' => [$this, 'bwdcv_sanitize_userfronted_options'],
            ]
        );

        add_settings_section(
            'bwd_userfronted_section',
            esc_html__( 'Settings Section', 'cv-builder' ),
            null,
            'bwd-userfronted-settings'
        );

        $this->add_settings_fields();
    }

    /**
     * Sanitize bwd_userfronted_options array.
     * Call add_settings_fields() এর field definitions দেখে
     * প্রতিটা key-এর জন্য সঠিক sanitizer নির্ধারণ করা হয়েছে।
     *
     * @param mixed $input
     * @return array
     */
    public function bwdcv_sanitize_userfronted_options( $input ) {
        if ( !is_array( $input ) ) {
            return [];
        }

        $sanitized = [];
        foreach ( $input as $key => $value ) {
            $key = sanitize_key( $key );

            if ( is_array( $value ) ) {
                $sanitized[$key] = array_map( 'sanitize_text_field', $value );
            } else {
                $sanitized[$key] = sanitize_text_field( $value );
            }
        }

        return $sanitized;
    }

    private function add_settings_fields() {
        add_settings_field(
            'bwd_userfronted_login_page',
            esc_html__( 'Login Page', 'cv-builder' ),
            array( $this, 'combined_field_callback' ),
            'bwd-userfronted-settings',
            'bwd_userfronted_section',
            array( 'id' => 'bwd_userfronted_login_page' )
        );

        add_settings_field(
            'bwd_userfronted_registration_page',
            esc_html__( 'Registration Page', 'cv-builder' ),
            array( $this, 'combined_field_callback' ),
            'bwd-userfronted-settings',
            'bwd_userfronted_section',
            array( 'id' => 'bwd_userfronted_registration_page' )
        );

        add_settings_field(
            'bwd_userfronted_subscription_page',
            esc_html__( 'Subcription Page', 'cv-builder' ),
            array( $this, 'combined_field_callback' ),
            'bwd-userfronted-settings',
            'bwd_userfronted_section',
            array( 'id' => 'bwd_userfronted_subscription_page' )
        );

        add_settings_field(
            'bwd_userfronted_dashboard_page',
            esc_html__( 'Dashboard Page', 'cv-builder' ),
            array( $this, 'combined_field_callback' ),
            'bwd-userfronted-settings',
            'bwd_userfronted_section',
            array( 'id' => 'bwd_userfronted_dashboard_page' )
        );

        add_settings_field(
            'bwdcv_instant_cv_create_shotcode',
            esc_html__( 'Instant CV Create:', 'cv-builder' ),
            array( $this, 'combined_field_callback' ),
            'bwd-userfronted-settings',
            'bwd_userfronted_section',
            array( 'id' => 'bwdcv_instant_cv_create_shotcode' )
        );
    }

    public function combined_field_callback( $args ) {
        $options = get_option( 'bwd_userfronted_options' );
        $this->render_select_field( $args['id'], $options );
    }

    private function render_select_field( $field_id, $options ) {
        switch ( $field_id ) {
        case 'bwd_userfronted_login_page':
            ?>
                <div class="cv-usersettings-card-header">
                    <div class="cv-usersettings-icon"></div>
                    <h3 class="cv-usersettings-title">Login Page</h3>
                </div>
                <?php
$selected = isset( $options['login_page'] ) ? $options['login_page'] : '';
            $shortcode_output = '[custom_login]';
            ?>
                <select class="bwdcv-nice-select" name="bwd_userfronted_options[login_page]">
                    <option><?php esc_html_e( 'Select Page', 'cv-builder' ); ?></option>
                    <?php $this->render_page_options( $selected ); ?>
                </select>
                <div class="description">
                    <?php esc_html_e( 'Use shortcode:', 'cv-builder' ); ?>
                    <span id="bwd-login-shortcode-copy" class="bwdcv-shortcode-button">
                        <span><?php echo esc_html( $shortcode_output ); ?></span>
                        <div id="copy-login-message" style="display:none;">Copied</div>
                    </span>
                    <input type="text" value="<?php echo esc_attr( $shortcode_output ); ?>" id="hidden-login-copy-text" style="position: absolute; left: -9999px;">
                </div>
                <?php
break;
        case 'bwd_userfronted_registration_page':
            ?>
                <div class="cv-usersettings-card-header">
                    <div class="cv-usersettings-icon"></div>
                    <h3 class="cv-usersettings-title">Registration Page</h3>
                </div>
                <?php
$selected = isset( $options['registration_page'] ) ? $options['registration_page'] : '';
            $shortcode_output = '[custom_registration]';
            ?>
                <select class="bwdcv-nice-select" name="bwd_userfronted_options[registration_page]">
                    <option><?php esc_html_e( 'Select Page', 'cv-builder' ); ?></option>
                    <?php $this->render_page_options( $selected ); ?>
                </select>
                <div class="description">
                    <?php esc_html_e( 'Use shortcode:', 'cv-builder' ); ?>
                    <span id="bwd-shortcode-copy" class="bwdcv-shortcode-button">
                        <span><?php echo esc_html( $shortcode_output ); ?></span>
                        <div id="copy-message" style="display:none;">Copied</div>
                    </span>
                    <input type="text" value="<?php echo esc_attr( $shortcode_output ); ?>" id="hidden-copy-text" style="position: absolute; left: -9999px;">
                </div>
                <?php
break;
        case 'bwd_userfronted_subscription_page':
            ?>
                <div class="cv-usersettings-card-header">
                    <div class="cv-usersettings-icon"></div>
                    <h3 class="cv-usersettings-title">Subcription Page</h3>
                </div>
                <?php
$selected = isset( $options['subscription_page'] ) ? $options['subscription_page'] : '';
            $shortcode_output = '[subscription_product]';
            ?>
                <select class="bwdcv-nice-select" name="bwd_userfronted_options[subscription_page]">
                    <option value=""><?php echo esc_html__( 'Select Page', 'cv-builder' ); ?></option>
                    <?php $this->render_page_options( $selected ); ?>
                </select>
                <div class="description">
                    <?php esc_html_e( 'Use shortcode:', 'cv-builder' ); ?>
                    <span id="bwd-shortcode-subscription" class="bwdcv-shortcode-button">
                        <span><?php echo esc_html( $shortcode_output ); ?></span>
                        <div id="subscription-message" style="display:none;">Copied</div>
                    </span>
                    <input type="text" value="<?php echo esc_attr( $shortcode_output ); ?>" id="hidden-subscription-text" style="position: absolute; left: -9999px;">
                </div>
                <?php
break;
        case 'bwd_userfronted_dashboard_page':
            ?>
                <div class="cv-usersettings-card-header">
                    <div class="cv-usersettings-icon"></div>
                    <h3 class="cv-usersettings-title">Dashboard Page</h3>
                </div>
                <?php
$selected = isset( $options['dashboard_page'] ) ? $options['dashboard_page'] : '';
            $shortcode_output = '[cv_dashboard_setting]';
            ?>
                <select class="bwdcv-nice-select" name="bwd_userfronted_options[dashboard_page]">
                    <option value=""><?php echo esc_html__( 'Select Page', 'cv-builder' ); ?></option>
                    <?php $this->render_page_options( $selected ); ?>
                </select>
                <div class="description">
                    <?php esc_html_e( 'Use shortcode:', 'cv-builder' ); ?>
                    <span id="bwd-shortcode-dashboard" class="bwdcv-shortcode-button">
                        <span><?php echo esc_html( $shortcode_output ); ?></span>
                        <div id="dashboard-message" style="display:none;">Copied</div>
                    </span>
                    <input type="text" value="<?php echo esc_attr( $shortcode_output ); ?>" id="hidden-dashboard-text" style="position: absolute; left: -9999px;">
                </div>
                <?php
break;
        case 'bwdcv_instant_cv_create_shotcode':
            $shortcode_output = '[instantly_cv_create text="Create CV"]';
            ?>
                <p class="description">
                    <span id="bwd-shortcode-instant-cv-create" style="cursor: pointer; color: #646464; background: #bbbbbb;padding: 5px;">
                        <?php echo esc_html( $shortcode_output ); ?>
                    </span>
                    <input type="text" value="<?php echo esc_attr( $shortcode_output ); ?>" id="hidden-instant-cv-create-text" style="position: absolute; left: -9999px;">
                    <p style="color: #ff8d00;font-size: 12px;"><?php esc_html_e( 'Add Cloudflare API settings from the API tab to protect against bots.', 'cv-builder' ); ?></p>
                    <div id="instant-cv-create-message" style="display:none; color: green;"><?php esc_html_e( 'Copied', 'cv-builder' ); ?></div>
                </p>
                <?php
break;
        }
    }

    /*
    * Get all published pages
    */
    private function render_page_options( $selected ) {
        
        $pages = get_posts( array(
            'post_type'   => 'page',
            'post_status' => 'publish',
            'numberposts' => -1,
        ) );

        if ( !empty( $pages ) ) {
            foreach ( $pages as $page ) {
                $author_id = $page->post_author;
                $user = get_userdata( $author_id );
                if ( in_array( 'cv_editor', (array) $user->roles ) ) {
                    continue;
                }
                ?>
                <option value="<?php echo esc_attr( $page->ID ); ?>" <?php selected( $selected, $page->ID ); ?>>
                    <?php echo esc_html( ucwords( $page->post_title ) ); ?>
                </option>
                <?php
}
        } else {
            ?>
            <option disabled><?php esc_html_e( 'No pages found', 'cv-builder' ); ?></option>
            <?php
}
    }

    public function bwdcv_license_admin_notice() {
        $license_status = 'inactive';
        if ( class_exists( '\BWDCV_BLOCKS_CLASS_PRO' ) ) {
            $license_status = \BWDCV_BLOCKS_CLASS_PRO::instance()->bwdcv_get_license_status();
        }
        if ( $license_status !== 'activate' ) {
            $message = sprintf(
                /* translators: 1: opening strong, 2: closing strong, 3: license page URL */
                esc_html__( '%1$sWP CV Builder%2$s cannot function because your %1$slicense%2$s is inactive. Please verify that your %1$slicense%2$s is valid and %1$sactive%2$s to restore access. %3$s', 'cv-builder' ),
                '<strong>',
                '</strong>',
                '<a href="https://bestwpdeveloper.com/my-account/" target="_blank">' . esc_html__( 'Find license..', 'cv-builder' ) . '</a>'
            );

            printf(
                '<div class="notice notice-warning is-dismissible"><p>%s</p></div>',
                wp_kses_post( $message )
            );
        }
    }

    public function restrict_media_library_to_user( $query ) {
        if ( !is_admin() ) {
            return;
        }
        if ( current_user_can( 'cv_editor' ) && isset( $query->query_vars['post_type'] ) && $query->query_vars['post_type'] == 'attachment' ) {
            $current_user_id = get_current_user_id();
            $query->set( 'author', $current_user_id );
        }
    }
    
    /*
    * Login logo change
    */
    public function bwdcv_custom_login_logo() {
        if ( function_exists( 'has_site_icon' ) && has_site_icon() ) {
            echo '<style type="text/css">
                #login h1 a {
                    background-image: url("' . esc_url( get_site_icon_url() ) . '") !important;
                    background-size: contain !important;
                    background-repeat: no-repeat !important;
                    height: 80px !important;
                    width: 100% !important;
                    padding-bottom: 30px !important;
                }
            </style>';
        }
    }

    public function __construct() {
        add_action( 'pre_get_posts', [$this, 'restrict_media_library_to_user'] );
      
        /*
        * count download request with AJAX
        */
        $bwdcv_download_handle = apply_filters( 'bwdcv_download_handle_js', true );
        if ( $bwdcv_download_handle && get_option( 'w_cv_2allow' ) != 'on' ) {
            add_action( 'wp_ajax_bwd_handle_pdf_download', [$this, 'bwd_handle_pdf_download'] );
            add_action( 'wp_ajax_nopriv_bwd_handle_pdf_download', [$this, 'bwd_handle_pdf_download'] );
        }
        add_action( 'wp_enqueue_scripts', [$this, 'bwdcv_all_assets_for_the_public'] );
        add_action( 'admin_enqueue_scripts', [$this, 'bwdcv_all_assets_for_the_admin'] );
        add_action( 'admin_init', array( $this, 'register_settings' ) );
        add_action( 'update_option_bwd_userfronted_options', array( $this, 'insert_registration_shortcode' ) );
        add_action( 'update_option_bwd_userfronted_options', array( $this, 'insert_sub_shortcode' ) );
        add_action( 'update_option_bwd_userfronted_options', array( $this, 'insert_dashboard_shortcode' ) );
        add_action( 'login_enqueue_scripts', [$this, 'bwdcv_custom_login_logo'] );
    }
}

/*
* Instantiate Plugin Class
*/
ClassBWDCVvilder::instance();
