<?php
defined( 'ABSPATH' ) || exit;

class ChainPay_Admin {

    public function __construct() {
        add_action( 'admin_menu',              array( $this, 'add_menu' ) );
        add_action( 'admin_enqueue_scripts',   array( $this, 'enqueue' ) );
        add_action( 'wp_ajax_chainpay_admin_save',          array( $this, 'ajax_save' ) );
        add_action( 'wp_ajax_chainpay_admin_verify_license',array( $this, 'ajax_verify_license' ) );
        add_action( 'wp_ajax_chainpay_admin_revoke_license',array( $this, 'ajax_revoke_license' ) );
        add_action( 'wp_ajax_chainpay_admin_test_xpub',     array( $this, 'ajax_test_xpub' ) );
        add_action( 'wp_ajax_chainpay_admin_refresh_prices',array( $this, 'ajax_refresh_prices' ) );
        add_filter( 'plugin_action_links_' . plugin_basename( CHAINPAY_FILE ), array( $this, 'plugin_links' ) );
    }

    public function plugin_links( $links ) {
        $settings_url = admin_url( 'admin.php?page=chainpay' );
        array_unshift( $links, '<a href="' . esc_url( $settings_url ) . '">Settings</a>' );
        return $links;
    }

    public function add_menu() {
        add_menu_page(
            'ChainPay',
            'ChainPay',
            'manage_woocommerce',
            'chainpay',
            array( $this, 'render_page' ),
            'data:image/svg+xml;base64,' . base64_encode( '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white"><path d="M13 10V3L4 14h7v7l9-11h-7z"/></svg>' ),
            56
        );
        add_submenu_page( 'chainpay', 'Settings',     'Settings',     'manage_woocommerce', 'chainpay',               array( $this, 'render_page' ) );
        add_submenu_page( 'chainpay', 'License',      'License',      'manage_woocommerce', 'chainpay&tab=license',   array( $this, 'render_page' ) );
        add_submenu_page( 'chainpay', 'Wallets/xPub', 'Wallets/xPub', 'manage_woocommerce', 'chainpay&tab=wallets',   array( $this, 'render_page' ) );
        add_submenu_page( 'chainpay', 'Invoices',     'Invoices',     'manage_woocommerce', 'chainpay&tab=invoices',  array( $this, 'render_page' ) );
        add_submenu_page( 'chainpay', 'Logs',         'Logs',         'manage_woocommerce', 'chainpay&tab=logs',      array( $this, 'render_page' ) );
    }

    public function enqueue( $hook ) {
        if ( false === strpos( $hook, 'chainpay' ) ) return;
        wp_enqueue_style(  'chainpay-admin', CHAINPAY_URL . 'admin/css/admin.css', array(), CHAINPAY_VERSION );
        wp_enqueue_script( 'chainpay-admin', CHAINPAY_URL . 'admin/js/admin.js',  array( 'jquery' ), CHAINPAY_VERSION, true );
        wp_localize_script( 'chainpay-admin', 'cpAdmin', array(
            'ajax'  => admin_url( 'admin-ajax.php' ),
            'nonce' => wp_create_nonce( 'chainpay_admin' ),
        ) );
    }

    public function render_page() {
        include CHAINPAY_DIR . 'admin/views/layout.php';
    }

    /* ── AJAX: save settings ─────────────────────────────────── */
    public function ajax_save() {
        check_ajax_referer( 'chainpay_admin', 'nonce' );
        if ( ! current_user_can( 'manage_woocommerce' ) ) wp_send_json_error( 'Unauthorised.' );

        $tab     = isset( $_POST['tab'] ) ? sanitize_text_field( wp_unslash( $_POST['tab'] ) ) : 'general';
        $updated = array();

        $allowed = array(
            'chainpay_api_key', 'chainpay_api_mode', 'chainpay_invoice_timeout',
            'chainpay_underpayment_pct', 'chainpay_eth_fee_threshold',
            'chainpay_confirmed_status', 'chainpay_pending_status', 'chainpay_expired_status',
            'chainpay_smart_routing', 'chainpay_show_qr', 'chainpay_show_timer',
            'chainpay_show_rate', 'chainpay_show_fee', 'chainpay_underpayment_email',
            'chainpay_email_on_confirmed', 'chainpay_email_on_detected', 'chainpay_email_on_expired',
            'chainpay_admin_email_on_confirmed', 'chainpay_webhook_secret', 'chainpay_coingecko_key',
        );

        foreach ( $allowed as $key ) {
            if ( ! isset( $_POST[ $key ] ) ) continue;
            $val = sanitize_text_field( wp_unslash( $_POST[ $key ] ) );
            update_option( $key, $val );
            $updated[] = $key;
        }

        // Enabled coins (array)
        if ( isset( $_POST['chainpay_enabled_coins'] ) && is_array( $_POST['chainpay_enabled_coins'] ) ) {
            $coins = array_map( 'sanitize_text_field', wp_unslash( $_POST['chainpay_enabled_coins'] ) );
            $valid = array_keys( ChainPay_Coin_Registry::all() );
            update_option( 'chainpay_enabled_coins', array_intersect( $coins, $valid ) );
            $updated[] = 'chainpay_enabled_coins';
        }

        // xPub keys
        if ( isset( $_POST['xpub'] ) && is_array( $_POST['xpub'] ) ) {
            foreach ( wp_unslash( $_POST['xpub'] ) as $coin => $val ) {
                $coin = sanitize_key( $coin );
                $val  = sanitize_text_field( $val );
                if ( '' !== $val ) {
                    update_option( 'chainpay_xpub_' . $coin, $val );
                    update_option( 'chainpay_xpub_idx_' . $coin, 0 ); // Reset index on new xpub
                }
            }
        }

        wp_send_json_success( array( 'message' => 'Settings saved.', 'updated' => $updated ) );
    }

    /* ── AJAX: verify license ────────────────────────────────── */
    public function ajax_verify_license() {
        check_ajax_referer( 'chainpay_admin', 'nonce' );
        if ( ! current_user_can( 'manage_woocommerce' ) ) wp_send_json_error( 'Unauthorised.' );

        $key = isset( $_POST['license_key'] ) ? sanitize_text_field( wp_unslash( $_POST['license_key'] ) ) : '';
        if ( '' === $key ) wp_send_json_error( 'No license key provided.' );

        update_option( 'chainpay_license_key', $key );
        $result = ChainPay_License::verify( $key );

        if ( $result['success'] ) {
            wp_send_json_success( array(
                'message' => 'License activated! Plan: ' . ( isset( $result['plan'] ) ? $result['plan'] : 'Pro' ),
                'plan'    => isset( $result['plan'] ) ? $result['plan'] : 'pro',
                'expires' => isset( $result['expires'] ) ? $result['expires'] : '',
            ) );
        } else {
            wp_send_json_error( $result['message'] );
        }
    }

    /* ── AJAX: revoke license ────────────────────────────────── */
    public function ajax_revoke_license() {
        check_ajax_referer( 'chainpay_admin', 'nonce' );
        if ( ! current_user_can( 'manage_woocommerce' ) ) wp_send_json_error( 'Unauthorised.' );
        ChainPay_License::deactivate();
        wp_send_json_success( array( 'message' => 'License revoked.' ) );
    }

    /* ── AJAX: test xPub derivation ──────────────────────────── */
    public function ajax_test_xpub() {
        check_ajax_referer( 'chainpay_admin', 'nonce' );
        if ( ! current_user_can( 'manage_woocommerce' ) ) wp_send_json_error( 'Unauthorised.' );

        $coin = isset( $_POST['coin'] ) ? sanitize_key( wp_unslash( $_POST['coin'] ) )             : '';
        $xpub = isset( $_POST['xpub'] ) ? sanitize_text_field( wp_unslash( $_POST['xpub'] ) ) : '';

        $result = ChainPay_xPub::test_derivation( $coin, $xpub );
        if ( ! empty( $result['valid'] ) ) {
            wp_send_json_success( $result );
        } else {
            wp_send_json_error( isset( $result['error'] ) ? $result['error'] : 'Derivation failed.' );
        }
    }

    /* ── AJAX: refresh prices ────────────────────────────────── */
    public function ajax_refresh_prices() {
        check_ajax_referer( 'chainpay_admin', 'nonce' );
        if ( ! current_user_can( 'manage_woocommerce' ) ) wp_send_json_error( 'Unauthorised.' );
        delete_transient( 'chainpay_prices_usd' );
        $prices = ChainPay_Price_Feed::refresh_all( 'USD' );
        wp_send_json_success( array( 'message' => 'Prices refreshed.', 'count' => count( $prices ), 'prices' => $prices ) );
    }
}
