<?php
/**
 * Plugin Name: WP CV Builder
 * Description: WP CV Builder with eye-catching style with 24+ preset design.
 * Plugin URI:  https://wpcvbuilder.com/
 * Version:     1.3.7
 * Author:      Best WP Developer
 * Author URI:  https://bestwpdeveloper.com/
 * Requires at least: 5.7
 * Requires PHP:      7.0
 * Text Domain: cv-builder
 * Domain Path: /languages
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 */

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

/*
* Prevent conflicts if old plugin is still active - IMPROVED VERSION
*/
if ( defined( 'BWDCV_VERSION' ) ) {
    if ( !defined( 'BWDCV_PLUGIN_NAME' ) ) {
        define( 'BWDCV_PLUGIN_NAME', plugin_basename( __DIR__ ) );
    }

    if ( !class_exists( 'BWDCV_Old_Folder_Checker' ) ) {
        require_once plugin_dir_path( __FILE__ ) . 'includes/updater/updates/old_folder_checker.php';

        add_action( 'admin_init', function () {
            BWDCV_Old_Folder_Checker::get_instance();
        }, 1 ); 
    }

    return;
}

define( 'BWDCV_PLUGIN_NAME', plugin_basename( __DIR__ ) );
define( "BWDCV_VERSION", '1.3.7' );
define( 'BWDCV_FILE', __FILE__ );
define( 'BWDCV_DIR', __DIR__ );
define( 'BWDCV_DIR_PATH', plugin_dir_path( __FILE__ ) );
define( 'BWDCV_ADMIN_URL', plugin_dir_url( __FILE__ ) );
define( 'BWDCV_WP_VERSION', (float) get_bloginfo( 'version' ) );
define( 'BWDCV_PHP_VERSION', (float) phpversion() );


require_once plugin_dir_path( __FILE__ ) . '/includes/requires-check.php';
require_once plugin_dir_path( __FILE__ ) . 'includes/registration-form.php';
require_once plugin_dir_path( __FILE__ ) . 'includes/subscription-plans.php';
require_once plugin_dir_path( __FILE__ ) . 'includes/updater/base-updater.php';
require_once plugin_dir_path( __FILE__ ) . 'includes/updater/updater.php';

final class BWDCV_BLOCKS_CLASS {

    private $license_details;

    const VERSION = BWDCV_VERSION;

    const MINIMUM_PHP_VERSION = '7.0';

    private static $instance;

    /**
     * Singleton Instance
     */
    public static function instance() {
        if ( is_null( self::$instance ) ) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    /**
     * Class Constructor
     */
    public function __construct() {
        add_action( 'init', [$this, 'hide_admin_bar_wp_editor'] );
        register_activation_hook( __FILE__, [$this, 'create_cv_subscription_category'] );
        add_action( 'woocommerce_flush_rewrite_rules', [$this, 'create_cv_subscription_category'] );
        register_activation_hook( __FILE__, [$this, 'create_cv_subscription_page'] );
        register_activation_hook( __FILE__, [$this, 'create_cv_dashboard_page'] );
        register_activation_hook( __FILE__, [$this, 'create_cv_login_page'] );
        register_activation_hook( __FILE__, [$this, 'create_cv_registration_page'] );
        add_action( 'enqueue_block_editor_assets', [$this, 'arabic_heading_block_set_script_translations'] );
        add_filter( 'plugin_action_links', [$this, 'bwdcv_settings_plugin_action_link'], 10, 2 );
        
        register_activation_hook( __FILE__, function () {
            $updater = new BWDCV_Updater();
            $updater->check_version_and_update();
        } );

        add_action( 'init', array( $this, 'create_cv_editor_role' ) );
        add_action( 'init', [$this, 'bwdcv_register_template_post_type'] );
        add_action( 'init', [$this, 'register_custom_post_type'] );
        add_action( 'in_admin_header', [$this, 'bwdcv_admin_header'], 99 );

        add_action( 'init', [$this, 'bwdcv_init'] );
        if ( !did_action( 'woocommerce/loaded' ) ) {
            add_action( 'admin_notices', 'bwdcv_WooCommerce_register_required_plugins' );
        }

        if ( !version_compare( BWDCV_WP_VERSION, '5.8', '>=' ) ) {
            add_action( 'admin_notices', [$this, 'check_wp_version'] );
        } elseif ( !version_compare( BWDCV_PHP_VERSION, '5.7', '>=' ) ) {
            add_action( 'admin_notices', [$this, 'check_php_version'] );
        } elseif ( !function_exists( 'register_block_type' ) ) {
            add_action( 'admin_notices', [$this, 'gutenberg_unavailable_notice'] );
        } else {
            $this->includes();

        }
        register_activation_hook( __FILE__, [$this, 'blocks_activation_hook'] );
        register_deactivation_hook( __FILE__, [$this, 'blocks_deactivation_hook'] );

        /*
        * custom cv builder saas loaded action
        */
        do_action( 'wp_cv_builder_saas_loaded' );
    }

    public function bwdcv_admin_header() {
        $screen = get_current_screen();

        if ( strpos( $screen->id, 'bwdcv-cv-settings' ) !== false ) {
            remove_all_actions( 'admin_notices' );
            remove_all_actions( 'all_admin_notices' );
        }
    }
    public function bwdcv_settings_plugin_action_link( $links, $file ) {
        if ( plugin_basename( __FILE__ ) === $file ) {
            $settings_link = '<a href="' . admin_url( 'admin.php?page=bwdcv-cv-settings' ) . '">'
            . esc_html__( 'Settings', 'cv-builder' ) . '</a>';
            $upgrade_pro_link = !class_exists( 'BWDCV_BLOCKS_CLASS_PRO' )
            ? '<a href="https://wpcvbuilder.com/pricing/" target="_blank" style="color: #cc0000; font-weight: 700;">'
            . esc_html__( 'Upgrade Pro', 'cv-builder' ) . '</a>'
            : '';
            $custom_links = array_filter( [$settings_link, $upgrade_pro_link] );

            $links = array_merge( $links, $custom_links );
        }
        return $links;
    }

    function arabic_heading_block_set_script_translations() {
        wp_enqueue_script(
            'bwdcv-cv-builder-editor-script',
            plugin_dir_url( __FILE__ ) . 'build/blocks/wp-cv-builder/index.js',
            ['wp-hooks', 'wp-element', 'wp-blocks', 'wp-components', 'wp-editor', 'wp-i18n'],
            time(),
            true
        );

        wp_set_script_translations(
            'bwdcv-cv-builder-editor-script',
            'cv-builder',
            plugin_dir_path( __FILE__ ) . 'languages'
        );
    }
    public static function get_cv_editor_capabilities(): array {
        return array(
            'edit_cv',
            'read_cv',
            'delete_cv',
            'edit_cvs',
            'edit_others_cvs',
            'publish_cvs',
            'read_private_cvs',
            'delete_cvs',
            'delete_private_cvs',
            'delete_published_cvs',
            'delete_others_cvs',
            'edit_private_cvs',
            'edit_published_cvs',
            'read',
            'edit_posts',
            'upload_files',
        );
    }
    public function bwdcv_register_template_post_type() {
        
        $labels = [
            'name'               => esc_html__( 'CV Templates', 'cv-builder' ),
            'singular_name'      => esc_html__( 'CV Template', 'cv-builder' ),
            'menu_name'          => esc_html__( 'CV Templates', 'cv-builder' ),
            'name_admin_bar'     => esc_html__( 'CV Template', 'cv-builder' ),
            'add_new'            => esc_html__( 'Add New', 'cv-builder' ),
            'add_new_item'       => esc_html__( 'Add New Template', 'cv-builder' ),
            'edit_item'          => esc_html__( 'Edit CV Template', 'cv-builder' ),
            'new_item'           => esc_html__( 'New CV Template', 'cv-builder' ),
            'view_item'          => esc_html__( 'View CV Template', 'cv-builder' ),
            'search_items'       => esc_html__( 'Search CV Templates', 'cv-builder' ),
            'not_found'          => esc_html__( 'No CV Templates found', 'cv-builder' ),
            'not_found_in_trash' => esc_html__( 'No CV Templates found in Trash', 'cv-builder' ),
        ];

        $args = [
            'labels'              => $labels,
            'public'              => true,
            'exclude_from_search' => true,
            'publicly_queryable'  => true,
            'show_ui'             => true,
            'show_in_nav_menus'   => false,
            'show_in_menu'        => false,
            'show_in_admin_bar'   => true,
            'has_archive'         => false,
            'rewrite'             => ['slug' => 'cv-template'],
            'can_export'          => true,
            'delete_with_user'    => false,
            'template_lock'       => false,
            'show_in_rest'        => true,
            'rest_base'           => 'cv-templates',
        ];
        register_post_type( 'cv-templates', $args );
    }
    /**
     * Static method for plugin activation tasks
     */
    public static function create_cv_editor_role() {
        self::bwd_register_cv_editor_role();
        self::add_cv_capabilities();

        flush_rewrite_rules();
    }

    /**
     * Create the CV Editor role
     */
    private static function bwd_register_cv_editor_role() {
        if ( !get_role( 'cv_editor' ) ) {
            add_role( 'cv_editor', 'CV Editor' );
        }
    }

    /**
     * Add capabilities to roles
     */
    private static function add_cv_capabilities() {
        $role = get_role( 'cv_editor' );

        if ( !$role ) {
            return; 
        }

        $capabilities = self::get_cv_editor_capabilities();

        foreach ( $capabilities as $cap ) {
            $role->add_cap( $cap );
        }

        $admin = get_role( 'administrator' );
        if ( $admin ) {
            foreach ( $capabilities as $cap ) {
                $admin->add_cap( $cap );
            }
        }
    }

    public function register_custom_post_type() {
        $capabilities = [
            'edit_post'              => 'edit_cv',
            'read_post'              => 'read_cv',
            'delete_post'            => 'delete_cv',
            'edit_posts'             => 'edit_cvs',
            'edit_others_posts'      => 'edit_others_cvs',
            'publish_posts'          => 'publish_cvs',
            'read_private_posts'     => 'read_private_cvs',
            'delete_posts'           => 'delete_cvs',
            'delete_private_posts'   => 'delete_private_cvs',
            'delete_published_posts' => 'delete_published_cvs',
            'delete_others_posts'    => 'delete_others_cvs',
            'edit_private_posts'     => 'edit_private_cvs',
            'edit_published_posts'   => 'edit_published_cvs',
        ];

        $labels = [
            'name'               => null,
            'singular_name'      => 'CV',
            'menu_name'          => 'CVs',
            'name_admin_bar'     => 'CV',
            'add_new'            => null,
            'add_new_item'       => null,
            'view_item'          => null,
            'all_items'          => 'All CVs',
            'search_items'       => 'Search CVs',
            'not_found'          => 'No CVs found.',
            'not_found_in_trash' => 'No CVs found in Trash.',
            'archives'           => 'CV Archives',
        ];

        $args = [
            'labels'              => $labels,
            'public'              => false,
            'exclude_from_search' => true,
            'publicly_queryable'  => true,
            'show_ui'             => true,
            'show_in_menu'        => false,
            'show_in_admin_bar'   => false,
            'show_in_nav_menus'   => true,
            'has_archive'         => false,
            'rewrite'             => ['slug' => 'cv'],
            'can_export'          => true,
            'delete_with_user'    => false,
            'template_lock'       => false,
            'show_in_rest'        => true,
            'rest_base'           => 'cv',
            'capability_type'     => 'cv',
            'capabilities'        => $capabilities,
            'map_meta_cap'        => true,
        ];

        register_post_type( 'cv', $args );
    }

    public function create_cv_login_page() {
        $page_content = '[custom_login]';
        $page_slug = 'cv-login';
        if ( !get_page_by_path( $page_slug ) ) {
            $new_page = [
                'post_title'   => esc_html__( 'CV Login', 'cv-builder' ),
                'post_content' => $page_content,
                'post_status'  => 'publish',
                'post_type'    => 'page',
                'post_name'    => $page_slug,
            ];
            $page_id = wp_insert_post( $new_page );
            $existing_options = get_option( 'bwd_userfronted_options', [] );
            $existing_options['login_page'] = $page_id;
            update_option( 'bwd_userfronted_options', $existing_options );
        }
    }

    public function create_cv_registration_page() {
        $page_content = '[custom_registration]';
        $page_slug = 'cv-registration';
        if ( !get_page_by_path( $page_slug ) ) {
            $new_page = [
                'post_title'   => esc_html__( 'CV Registration', 'cv-builder' ),
                'post_content' => $page_content,
                'post_status'  => 'publish',
                'post_type'    => 'page',
                'post_name'    => $page_slug,
            ];
            $page_id = wp_insert_post( $new_page );
            $existing_options = get_option( 'bwd_userfronted_options', [] );
            $existing_options['registration_page'] = $page_id;
            update_option( 'bwd_userfronted_options', $existing_options );
        }
    }

    public function create_cv_subscription_page() {
        $page_content = '[subscription_product]';
        $page_slug = 'cv-subscription';
        if ( !get_page_by_path( $page_slug ) ) {
            $new_page = [
                'post_title'   => esc_html__( 'CV Subscription', 'cv-builder' ),
                'post_content' => $page_content,
                'post_status'  => 'publish',
                'post_type'    => 'page',
                'post_name'    => $page_slug,
            ];
            $page_id = wp_insert_post( $new_page );
            $existing_options = get_option( 'bwd_userfronted_options', [] );
            $existing_options['subscription_page'] = $page_id;
            update_option( 'bwd_userfronted_options', $existing_options );
        }
    }

    public function create_cv_dashboard_page() {
        $page_content = '[cv_dashboard_setting]';
        $page_slug = 'cv-dashboard';
        if ( !get_page_by_path( $page_slug ) ) {
            $new_page = [
                'post_title'   => esc_html__( 'CV Dashboard', 'cv-builder' ),
                'post_content' => $page_content,
                'post_status'  => 'publish',
                'post_type'    => 'page',
                'post_name'    => $page_slug,
            ];
            $page_id = wp_insert_post( $new_page );
            $existing_options = get_option( 'bwd_userfronted_options', [] );
            $existing_options['dashboard_page'] = $page_id;
            update_option( 'bwd_userfronted_options', $existing_options );
        }
    }

    private function reassign_products_to_cv_subscription() {
        $term = get_term_by( 'slug', 'cv-subscription', 'product_cat' );
        if ( $term ) {
            $product_ids = get_option( 'cv_subscription_product_ids', [] );
            foreach ( $product_ids as $product_id ) {
                if ( get_post( $product_id ) && !has_term( $term->term_id, 'product_cat', $product_id ) ) {
                    wp_set_object_terms( $product_id, [$term->term_id], 'product_cat', true );
                }
            }
            delete_option( 'cv_subscription_product_ids' );
        }
    }

    public function create_cv_subscription_category() {
        if ( class_exists( 'WooCommerce' ) && !term_exists( 'cv subscription', 'product_cat' ) ) {
            wp_insert_term(
                'CV Subscription',
                'product_cat',
                [
                    'description' => 'A subscription for CV services',
                    'slug'        => 'cv-subscription',
                ]
            );
        }
        $this->reassign_products_to_cv_subscription();
    }

    public function hide_admin_bar_wp_editor() {
        if ( current_user_can( 'cv_editor' ) ) {
            add_filter( 'show_admin_bar', '__return_false' );
        }
    }

    public function bwdcv_init() {
        if ( version_compare( PHP_VERSION, self::MINIMUM_PHP_VERSION, '<' ) ) {
            add_action( 'admin_notices', [$this, 'bwdcv_admin_notice_minimum_php_version'] );

            return;
        }
        require_once 'bwdcv-boots.php';
        require_once 'includes/admin-menu.php';
        $this->bwdcv_reg_apps_reson_in_class();
    }

    public function bwdcv_reg_apps_reson_in_class() {
        require __DIR__ . '/vendor/autoload.php';
    }

    public function bwdcv_admin_notice_minimum_php_version() {
        if ( isset( $_GET['activate'] ) ) {
            unset( $_GET['activate'] );
        }

        $message = sprintf(
            /* translators: 1: Plugin name, 2: Dependency name, 3: Required version */
            esc_html__( '"%1$s" requires "%2$s" version %3$s or greater.', 'cv-builder' ),
            '<strong>' . esc_html__( 'WP CV Builder', 'cv-builder' ) . '</strong>',
            '<strong>' . esc_html__( 'PHP', 'cv-builder' ) . '</strong>',
            esc_html( self::MINIMUM_PHP_VERSION )
        );

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

    /**
     * PHP Version Related Admin Notice
     */
    public function check_php_version() {
        $message = sprintf(
            /* translators: 1: Required PHP version, 2: Current PHP version */
            esc_html__( 'CV Builder Blocks requires minimum PHP version %1$s where your current PHP version is %2$s. Please update your PHP version to enable BWDTM Blocks features.', 'cv-builder' ),
            '5.6',
            esc_html( (string) BWDCV_PHP_VERSION )
        );
        $html_message = sprintf( '<div class="error">%s</div>', wpautop( $message ) );
        echo wp_kses_post( $html_message );
    }

    /**
     * WordPress Version Related Admin Notice
     */
    public function check_wp_version() {
       
        $message = sprintf(
            /* translators: 1: Required WP version, 2: Current WP version */
            esc_html__( 'CV Builder Blocks requires minimum WordPress version %1$s where your current WordPress version is %2$s. Please update your WordPress version to enable BWDTM Blocks features.', 'cv-builder' ),
            '5.8',
            esc_html( (string) BWDCV_WP_VERSION )
        );
        $html_message = sprintf( '<div class="error">%s</div>', wpautop( $message ) );
        echo wp_kses_post( $html_message );
    }

    /**
     * Gutenberg Plugin Activation Related Admin Notice
     */
    public function gutenberg_unavailable_notice() {
        if ( !current_user_can( 'install_plugins' ) ) {
            return;
        }

        $class = 'notice notice-error';
        /* translators: %s: html tags */
        $message = sprintf(
            /* translators: 1: HTML tag name, 2: Plugin name */
            esc_html__( 'The <%1$s>%2$s</%1$s> plugin requires <%1$s>Gutenberg</%1$s> plugin installed & activated.', 'cv-builder' ),
            'strong',
            'bwdcv-blocks'
        );

        $action_url = wp_nonce_url( self_admin_url( 'update.php?action=install-plugin&plugin=gutenberg' ), 'install-plugin_gutenberg' );
        $button_label = esc_html__( 'Install Gutenberg', 'cv-builder' );

        $button = '<p><a href="' . esc_url( $action_url ) . '" class="button-primary">' . esc_html( $button_label ) . '</a></p>';

        printf( '<div class="%1$s"><p>%2$s</p>%3$s</div>', esc_attr( $class ), wp_kses_post( $message ), wp_kses_post( $button ) );
    }

    /**
     * Activation Hook
     */
    public function blocks_activation_hook() {
        update_option( 'bwdcv_version', BWDCV_VERSION );
        $this->register_custom_post_type();
        flush_rewrite_rules();
    }

    /**
     * Deactivation Hook
     */
    public function blocks_deactivation_hook() {
        flush_rewrite_rules();
    }

    /**
     * Include required files
     */
    public function includes() {
        require_once BWDCV_DIR_PATH . 'includes/blocks-loader.php';
    }

}

/**
 * Kickoff
 */
function bwdcv_initialize_cv() {
    return BWDCV_BLOCKS_CLASS::instance();
}

/*
* start plugin
*/
bwdcv_initialize_cv();
