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

class BWDCV_Admin_Menu {

    private $option_name = 'bwdcv_preview_options';

    public function __construct() {
        add_action( 'admin_menu', array( $this, 'bwdcv_admin_menu' ) );
        add_action( 'admin_init', [$this, 'bwdcv_register_tab_settings'] );
        add_action( 'woocommerce_new_order', [$this, 'bwdcv_order_status_update_settings'], 10, 2 );
        add_filter( 'post_row_actions', [$this, 'remove_cv_post_row_actions'], 10, 2 );
        add_action( 'manage_cv_posts_custom_column', [$this, 'cv_custom_column_content'], 10, 2 );
        add_filter( 'manage_cv_posts_columns', [$this, 'modify_cv_columns'] );
        add_action( 'admin_head', [$this, 'remove_cv_post_add_new_title'] );
        add_action( 'enqueue_block_editor_assets', [$this, 'bwdcv_enqueue_scripts'] );
    }

    public function bwdcv_enqueue_scripts() {
        wp_enqueue_script( 'jquery' );

        // Localize script to pass PHP data to JS
        $options = get_option( $this->option_name );
        if ( !is_array( $options ) ) {
            $options = [];
        }

        wp_register_script( 'bwdcv-custom-js', '' );
        wp_enqueue_script( 'bwdcv-custom-js' );

        wp_localize_script( 'bwdcv-custom-js', 'bwdcv_data', [
            'checkboxes' => $options,
            'plugin_url' => plugin_dir_url( __FILE__ ),
        ] );
    }

    /**
     *
     * Order status auto complete
     *
     */
    public function bwdcv_order_status_update_settings( $order_id, $order ) {

        $enabled = get_option( 'cv_order_status_change', '0' );

        if ( $enabled !== '1' ) {
            return;
        }

        $order->update_status( 'completed', esc_html__( 'Auto Completed by WP CV Builder Plugin', 'cv-builder' ) );
    }

    public function bwdcv_admin_menu() {
        $license_status = 'deactivate';
        if ( class_exists( 'BWDCV_BLOCKS_CLASS_PRO' ) ) {
            $license_status = \BWDCV_BLOCKS_CLASS_PRO::instance()->bwdcv_get_license_status();
        }
        add_menu_page(
            esc_html__( 'WP CV Builder', 'cv-builder' ),
            esc_html__( 'WP CV Builder', 'cv-builder' ),
            'manage_options',
            'wp-cv-builder',
            array( $this, 'bwdcv_main_menu_page_display' ),
            plugin_dir_url( __DIR__ ) . 'assets/admin/img/cviconm.png',
            6
        );
        add_submenu_page(
            'wp-cv-builder',
            esc_html__( 'Dashboard', 'cv-builder' ),
            esc_html__( 'Dashboard', 'cv-builder' ),
            'manage_options',
            'wp-cv-builder'
        );
        add_submenu_page(
            'wp-cv-builder',
            esc_html__( 'Settings', 'cv-builder' ),
            esc_html__( 'Settings', 'cv-builder' ),
            'manage_options',
            'bwdcv-cv-settings',
            array( $this, 'bwdcv_settings_page_display' )
        );
        add_submenu_page(
            'wp-cv-builder',
            esc_html__( 'All CVs', 'cv-builder' ),
            esc_html__( 'All CVs', 'cv-builder' ),
            'manage_options',
            'edit.php?post_type=cv'
        );
        if ( $license_status === 'activate' ) {
            $this->add_cv_templates_menu_item();
        }

    }

    private function add_cv_templates_menu_item() {
        if ( !class_exists( 'BWDCV_BLOCKS_CLASS_PRO' ) ) {
            return;
        }

        add_submenu_page(
            'wp-cv-builder',
            esc_html__( 'CV Templates', 'cv-builder' ),
            esc_html__( 'CV Templates', 'cv-builder' ),
            'manage_options',
            'edit.php?post_type=cv-templates'
        );
    }

    public function remove_cv_post_row_actions( $actions, $post ) {
        if ( $post->post_type === 'cv' ) {
            return [];
        }
        return $actions;
    }
    public function remove_cv_post_add_new_title() {
        $screen = get_current_screen();
        if ( $screen && $screen->post_type === 'cv' ) {
            echo '<style>.page-title-action { display: none !important; }</style>';
        }
    }
    public function modify_cv_columns( $columns ) {
        $new_columns = array(
            'cb'           => $columns['cb'],
            'custom_title' => esc_html__( 'Title', 'cv-builder' ),
            'author'       => esc_html__( 'Author', 'cv-builder' ),
            'date'         => $columns['date'],
        );
        return $new_columns;
    }
    public function cv_custom_column_content( $column, $post_id ) {
        if ( $column == 'custom_title' ) {
            $cv_user_id = get_post_field( 'post_author', $post_id );
            $user_token = bwdcv_get_user_token( $cv_user_id );
            $url = esc_url( add_query_arg( 'token', $user_token, get_permalink( $post_id ) ) );
            echo '<a href="' . $url . '" target="_blank">'
            . esc_html( get_the_title( $post_id ) )
                . '</a>';
        }
    }
    public function bwdcv_main_menu_page_display() {
        if ( class_exists( 'WooCommerce' ) ) {
            include 'dashboard/cv-informations.php';
        } else {
            echo '<h2 style="color:brown;text-align: center;margin: 100px;">WP CV Builder requires <b>WooCommerce</b> plugin to be activated.';
        }
    }

    public function bwdcv_register_tab_settings() {
        include 'dashboard/arrays.php';

        // For template options (array of style toggles)
        register_setting(
            'bwdcv_settings_group',
            $this->option_name,
            [
                'type'              => 'array',
                'sanitize_callback' => [$this, 'bwdcv_sanitize_template_options'],
            ]
        );
    }

    /**
     * Sanitize template options array.
     * Keys: integer (1-28) → value is 0 or 1
     * Keys: 'cv_allow_styleN' → value is 0 or 1
     *
     * @param mixed $input
     * @return array
     */
    public function bwdcv_sanitize_template_options( $input ) {
        if ( !is_array( $input ) ) {
            return [];
        }

        $saved = get_option( $this->option_name, [] ); // Existing saved values

        foreach ( $input as $key => $value ) {
            if ( preg_match( '/^cv_allow_style([1-9]|1\d|2[0-8])$/', $key ) ) {
                // Only update this key
                $saved[sanitize_key( $key )] = absint( $value );
            } elseif ( is_numeric( $key ) && $key >= 1 && $key <= 28 ) {
                // Active template toggle
                $saved[$key] = absint( $value );
            }
        }

        return $saved;
    }

    public function bwdcv_settings_page_display() {
        include 'dashboard/settings.php';
    }

}

new BWDCV_Admin_Menu();
