<?php

namespace Devnet\PPH\Admin;

use Devnet\PPH\Modules\Chart\Chart_Admin;
use Devnet\PPH\Includes\Helper;
use Devnet\PPH\Includes\Activator;
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
class PPH_Admin {
    private $plugin_name;

    private $version;

    public function __construct( $plugin_name, $version ) {
        $this->plugin_name = $plugin_name;
        $this->version = $version;
        $page = ( isset( $_GET['page'] ) ? sanitize_text_field( $_GET['page'] ) : null );
        if ( $page === 'product-price-history' ) {
            add_filter( 'admin_footer_text', [$this, 'admin_credits'] );
        }
        add_action( 'admin_enqueue_scripts', [$this, 'enqueue_styles'] );
        add_action( 'admin_enqueue_scripts', [$this, 'enqueue_scripts'] );
        add_action( 'admin_menu', [$this, 'admin_menu'], 100 );
        add_filter( 'plugin_action_links_' . DEVNET_PPH_SLUG, [$this, 'plugin_action_links'] );
        add_action( 'before_woocommerce_init', [$this, 'cot_compatible'] );
        add_action( 'wp_ajax_pph_delete_old_data', [$this, 'delete_old_data'] );
        add_action( 'wp_ajax_pph_repair_tables', [$this, 'pph_repair_tables'] );
    }

    /**
     * Register the stylesheets for the admin area.
     *
     * @since    1.0.0
     */
    public function enqueue_styles( $hook ) {
        $allowed_pages = ['toplevel_page_product-price-history', 'post.php', 'post-new.php'];
        if ( !in_array( $hook, $allowed_pages ) ) {
            return;
        }
        wp_enqueue_style( 'wp-color-picker' );
        wp_enqueue_style(
            $this->plugin_name,
            plugin_dir_url( __DIR__ ) . 'assets/build/admin.css',
            [],
            $this->version,
            'all'
        );
    }

    /**
     * Register the JavaScript for the admin area.
     *
     * @since    1.0.0
     */
    public function enqueue_scripts( $hook ) {
        $allowed_pages = ['toplevel_page_product-price-history', 'post.php', 'post-new.php'];
        if ( !in_array( $hook, $allowed_pages ) ) {
            return;
        }
        wp_enqueue_media();
        wp_enqueue_script(
            'wp-color-picker-alpha',
            plugin_dir_url( __DIR__ ) . 'assets/color-picker/wp-color-picker-alpha.min.js',
            ['wp-color-picker'],
            $this->version,
            true
        );
        $script_asset_path = plugin_dir_url( __DIR__ ) . 'assets/build/admin.asset.php';
        $script_info = ( file_exists( $script_asset_path ) ? include $script_asset_path : [
            'dependencies' => ['jquery'],
            'version'      => $this->version,
        ] );
        wp_enqueue_script(
            $this->plugin_name,
            plugin_dir_url( __DIR__ ) . 'assets/build/admin.js',
            $script_info['dependencies'],
            $script_info['version'],
            true
        );
        /* translators: %1$s: number of deleted entries */
        $text_delete_success = __( '%1$s old entries have been successfully deleted.', 'product-price-history' );
        $script_data = [
            'ajaxurl' => admin_url( 'admin-ajax.php' ),
            'nonce'   => wp_create_nonce( 'pph-nonce' ),
            'text'    => [
                '30_days'                  => esc_html__( '30 days', 'product-price-history' ),
                '3_months'                 => esc_html__( '3 months', 'product-price-history' ),
                '6_months'                 => esc_html__( '6 months', 'product-price-history' ),
                '12_months'                => esc_html__( '12 months', 'product-price-history' ),
                'delete_confirm'           => esc_html__( 'Are you sure you want to proceed? This action will irreversibly delete old data.', 'product-price-history' ),
                'delete_success'           => esc_html( $text_delete_success ),
                'delete_none'              => esc_html__( 'No old data was found or deleted.', 'product-price-history' ),
                'delete_confirm_2'         => esc_html__( 'Continuing will permanently erase all entries associated with this product, and this action cannot be undone.', 'product-price-history' ),
                'delete_confirm_3'         => esc_html__( 'Are you sure you want to proceed? This action will irreversibly delete this data.', 'product-price-history' ),
                'prompt_lowest_price_bulk' => esc_html__( 'Set the lowest price for all variations:', 'product-price-history' ),
            ],
            'plan'    => Helper::plan( 'all' ),
        ];
        wp_localize_script( $this->plugin_name, 'devnet_pph_script', $script_data );
    }

    /**
     * Add admin menu page.
     *
     * @since    1.0.0
     */
    public function admin_menu() {
        $plugin_settings = new Settings();
        $menu_slug = 'product-price-history';
        add_menu_page(
            esc_html__( 'Product Price History', 'product-price-history' ),
            esc_html__( 'Price History', 'product-price-history' ),
            'edit_posts',
            $menu_slug,
            [$plugin_settings, 'settings_page'],
            'dashicons-chart-line',
            56
        );
        add_submenu_page(
            $menu_slug,
            esc_html__( 'Settings', 'product-price-history' ),
            esc_html__( 'Settings', 'product-price-history' ),
            'edit_posts',
            $menu_slug
        );
    }

    /**
     * Add plugin action link.
     *
     * @since    1.0.0
     */
    public function plugin_action_links( $links ) {
        $custom_links = [];
        $custom_links[] = '<a href="' . esc_url( get_admin_url( null, 'admin.php?page=product-price-history' ) ) . '">' . esc_html__( 'Settings', 'product-price-history' ) . '</a>';
        return array_merge( $custom_links, $links );
    }

    public function admin_credits( $footer_text ) {
        $footer_text = '';
        $footer_text .= '<div class="devnet-plugin-admin-footer">';
        $footer_text .= '<div class="devnet-plugin-footer-message">';
        $footer_text .= 'Please rate <strong>Product Price History</strong> <a href="https://wordpress.org/support/plugin/product-price-history/reviews/" target="_blank">★★★★★</a> on <a href="https://wordpress.org/support/plugin/product-price-history/reviews/" target="_blank">WordPress.org</a> to help us spread the word. Thank you from the <a href="https://devnet.hr/" target="_blank">Devnet</a> team!';
        $footer_text .= '</div>';
        $footer_text .= '<div class="devnet-plugin-go-pro">';
        $footer_text .= '<a href="https://devnet.hr/plugins/product-price-history/" target="_blank">Go PRO: More Features, More Power!</a>';
        $footer_text .= '</div>';
        $footer_text .= '</div>';
        return $footer_text;
    }

    /**
     * Declare that plugin is COT compatible.
     *
     * @since    1.0.0
     */
    public function cot_compatible() {
        if ( class_exists( '\\Automattic\\WooCommerce\\Utilities\\FeaturesUtil' ) ) {
            $plugin_file = plugin_dir_path( dirname( __FILE__ ) ) . 'product-price-history.php';
            \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', $plugin_file, true );
        }
    }

    /**
     * Ajax action for deleting old price history data.
     *  
     * @since     2.1.3
     */
    public function delete_old_data() {
        check_ajax_referer( 'pph-nonce', 'security' );
        $older_than = ( isset( $_POST['args']['older_than'] ) ? sanitize_text_field( $_POST['args']['older_than'] ) : null );
        $deleted = Helper::delete_old_data( 'price_history', $older_than );
        wp_send_json( $deleted );
        wp_die();
    }

    /**
     * Ajax action for creating missing tables.
     *  
     * @since     2.4.0
     */
    public function pph_repair_tables() {
        check_ajax_referer( 'pph-nonce', 'security' );
        require_once plugin_dir_path( __DIR__ ) . 'includes/activator.php';
        Activator::activate();
        wp_send_json( 'ok' );
        wp_die();
    }

}
