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

class NASEO_Admin {

    public function __construct() {
        add_action( 'admin_menu', [ $this, 'add_menu' ] );
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_assets' ] );

        // AJAX
        add_action( 'wp_ajax_naseo_generate_single', [ $this, 'ajax_generate_single' ] );
        add_action( 'wp_ajax_naseo_publish_now',     [ $this, 'ajax_publish_now' ] );
        add_action( 'wp_ajax_naseo_import_csv',      [ $this, 'ajax_import_csv' ] );
        add_action( 'wp_ajax_naseo_save_settings',   [ $this, 'ajax_save_settings' ] );
        add_action( 'wp_ajax_naseo_clear_logs',      [ $this, 'ajax_clear_logs' ] );
        add_action( 'wp_ajax_naseo_download_csv',     [ $this, 'ajax_download_csv' ] );
        add_action( 'wp_ajax_naseo_delete_queue_item', [ $this, 'ajax_delete_queue_item' ] );
        add_action( 'wp_ajax_naseo_activate_license',   [ $this, 'ajax_activate_license' ] );
        add_action( 'wp_ajax_naseo_deactivate_license', [ $this, 'ajax_deactivate_license' ] );
    }

    public function add_menu(): void {
        add_menu_page(
            'NemynAI SEO Autopilot',
            'NemynAI SEO',
            'manage_options',
            'naseo-dashboard',
            [ $this, 'page_dashboard' ],
            'dashicons-rest-api',
            30
        );

        add_submenu_page( 'naseo-dashboard', __( 'Дашборд', 'nemynai-seo-autopilot' ),   __( 'Дашборд', 'nemynai-seo-autopilot' ),   'manage_options', 'naseo-dashboard',  [ $this, 'page_dashboard' ] );
        add_submenu_page( 'naseo-dashboard', __( 'Генерація', 'nemynai-seo-autopilot' ),  __( 'Генерація', 'nemynai-seo-autopilot' ),  'manage_options', 'naseo-generate',   [ $this, 'page_generate' ] );
        add_submenu_page( 'naseo-dashboard', __( 'Імпорт CSV', 'nemynai-seo-autopilot' ), __( 'Імпорт CSV', 'nemynai-seo-autopilot' ), 'manage_options', 'naseo-import',     [ $this, 'page_import' ] );
        add_submenu_page( 'naseo-dashboard', __( 'Черга', 'nemynai-seo-autopilot' ),      __( 'Черга', 'nemynai-seo-autopilot' ),      'manage_options', 'naseo-queue',      [ $this, 'page_queue' ] );
        add_submenu_page( 'naseo-dashboard', __( 'Налаштування', 'nemynai-seo-autopilot' ), __( 'Налаштування', 'nemynai-seo-autopilot' ), 'manage_options', 'naseo-settings', [ $this, 'page_settings' ] );
        add_submenu_page( 'naseo-dashboard', __( 'Логи', 'nemynai-seo-autopilot' ),         __( 'Логи', 'nemynai-seo-autopilot' ),         'manage_options', 'naseo-logs',       [ $this, 'page_logs' ] );
        add_submenu_page( 'naseo-dashboard', __( 'Інструкція', 'nemynai-seo-autopilot' ),   __( '📖 Інструкція', 'nemynai-seo-autopilot' ), 'manage_options', 'naseo-help',       [ $this, 'page_help' ] );
    }

    public function enqueue_assets( string $hook ): void {
        if ( strpos( $hook, 'naseo-' ) === false ) return;

        wp_enqueue_style( 'naseo-admin', NASEO_PLUGIN_URL . 'assets/css/admin.css', [], NASEO_VERSION );
        wp_enqueue_script( 'naseo-admin', NASEO_PLUGIN_URL . 'assets/js/admin.js', [ 'jquery' ], NASEO_VERSION, true );

        wp_localize_script( 'naseo-admin', 'naseo', [
            'ajax_url' => admin_url( 'admin-ajax.php' ),
            'nonce'    => wp_create_nonce( 'naseo_nonce' ),
            'is_pro'   => naseo_is_pro() ? '1' : '0',
            'i18n'     => [
                'generating' => __( 'Генерую статтю...', 'nemynai-seo-autopilot' ),
                'publishing' => __( 'Публікую...', 'nemynai-seo-autopilot' ),
                'importing'  => __( 'Імпортую CSV...', 'nemynai-seo-autopilot' ),
                'saved'      => __( 'Збережено!', 'nemynai-seo-autopilot' ),
                'error'      => __( 'Помилка. Спробуйте ще.', 'nemynai-seo-autopilot' ),
            ],
        ] );
    }

    // ─── Сторінки ────────────────────────────────────────────────────────────

    public function page_dashboard(): void {
        $stats = NASEO_Scheduler::get_stats();
        $is_pro = naseo_is_pro();
        include NASEO_PLUGIN_DIR . 'admin/views/dashboard.php';
    }

    public function page_generate(): void {
        include NASEO_PLUGIN_DIR . 'admin/views/generate.php';
    }

    public function page_import(): void {
        $is_pro = naseo_is_pro();
        include NASEO_PLUGIN_DIR . 'admin/views/import.php';
    }

    public function page_queue(): void {
        global $wpdb;
        $table = $wpdb->prefix . 'naseo_queue';
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $items = $wpdb->get_results( "SELECT * FROM `" . esc_sql( $table ) . "` ORDER BY id DESC LIMIT 100" );
        include NASEO_PLUGIN_DIR . 'admin/views/queue.php';
    }

    public function page_settings(): void {
        $is_pro = naseo_is_pro();
        include NASEO_PLUGIN_DIR . 'admin/views/settings.php';
    }

    public function page_logs(): void {
        $logs = NASEO_Logger::get( 100 );
        include NASEO_PLUGIN_DIR . 'admin/views/logs.php';
    }

    public function page_help(): void {
        include NASEO_PLUGIN_DIR . 'admin/views/help.php';
    }

    // ─── AJAX обробники ───────────────────────────────────────────────────────

    public function ajax_generate_single(): void {
        check_ajax_referer( 'naseo_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_die( -1 );

        $title   = sanitize_text_field( wp_unslash( $_POST['title'] ?? '' ) );
        $keyword = sanitize_text_field( wp_unslash( $_POST['keyword'] ?? '' ) );
        $lsi     = sanitize_textarea_field( wp_unslash( $_POST['lsi_keywords'] ?? '' ) );

        if ( ! $title || ! $keyword ) {
            wp_send_json_error( [ 'message' => __( 'Заповніть заголовок і ключове слово.', 'nemynai-seo-autopilot' ) ] );
        }

        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $wpdb->insert( $wpdb->prefix . 'naseo_queue', [
            'title'        => $title,
            'keyword'      => $keyword,
            'lsi_keywords' => $lsi,
            'status'       => 'pending',
        ] );

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $item = $wpdb->get_row( $wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}naseo_queue WHERE id = %d", $wpdb->insert_id
        ) );

        $post_id = NASEO_Publisher::publish_item( $item );

        if ( $post_id ) {
            wp_send_json_success( [
                'message'  => __( 'Статтю опубліковано!', 'nemynai-seo-autopilot' ),
                'edit_url' => get_edit_post_link( $post_id, 'raw' ),
                'view_url' => get_permalink( $post_id ),
            ] );
        } else {
            wp_send_json_error( [ 'message' => __( 'Помилка генерації. Перевірте API ключ і логи.', 'nemynai-seo-autopilot' ) ] );
        }
    }

    public function ajax_publish_now(): void {
        check_ajax_referer( 'naseo_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_die( -1 );

        $limit     = (int) get_option( 'naseo_publish_limit', 1 );
        $scheduler = new NASEO_Scheduler();
        $result    = $scheduler->run_now( $limit );

        if ( $result['success'] ) {
            wp_send_json_success( $result );
        } else {
            wp_send_json_error( $result );
        }
    }

    public function ajax_import_csv(): void {
        check_ajax_referer( 'naseo_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_die( -1 );

        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
        if ( empty( $_FILES['csv_file']['tmp_name'] ) ) {
            wp_send_json_error( [ 'message' => __( 'Файл не завантажено.', 'nemynai-seo-autopilot' ) ] );
        }

        $importer = new NASEO_CSV_Importer();
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
        $result   = $importer->import( $_FILES['csv_file']['tmp_name'] );

        if ( $result['success'] ) {
            wp_send_json_success( $result );
        } else {
            wp_send_json_error( $result );
        }
    }

    public function ajax_save_settings(): void {
        check_ajax_referer( 'naseo_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_die( -1 );

        $fields = [
            'naseo_claude_api_key'  => 'sanitize_text_field',
            'naseo_pexels_api_key'  => 'sanitize_text_field',
            'naseo_language'        => 'sanitize_text_field',
            'naseo_author_id'       => 'intval',
            'naseo_publish_frequency' => 'sanitize_text_field',
            'naseo_custom_prompt'   => 'sanitize_textarea_field',
        ];

        foreach ( $fields as $key => $sanitizer ) {
            if ( isset( $_POST[ $key ] ) ) {
                // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
                update_option( $key, $sanitizer( wp_unslash( $_POST[ $key ] ) ) );
            }
        }

        wp_send_json_success( [ 'message' => __( 'Налаштування збережено!', 'nemynai-seo-autopilot' ) ] );
    }

    public function ajax_clear_logs(): void {
        check_ajax_referer( 'naseo_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_die( -1 );
        NASEO_Logger::clear();
        wp_send_json_success( [ 'message' => __( 'Логи очищено.', 'nemynai-seo-autopilot' ) ] );
    }

    public function ajax_delete_queue_item(): void {
        check_ajax_referer( 'naseo_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_die( -1 );

        $id = absint( wp_unslash( $_POST['id'] ?? 0 ) );
        if ( ! $id ) {
            wp_send_json_error( [ 'message' => 'ID не вказано.' ] );
        }

        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $deleted = $wpdb->delete( $wpdb->prefix . 'naseo_queue', [ 'id' => $id ], [ '%d' ] );

        if ( $deleted ) {
            wp_send_json_success( [ 'message' => 'Видалено.' ] );
        } else {
            wp_send_json_error( [ 'message' => 'Помилка видалення.' ] );
        }
    }

    public function ajax_download_csv(): void {
        check_admin_referer( 'naseo_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_die( -1 );

        $file = NASEO_PLUGIN_DIR . 'assets/example-content-plan.csv';
        if ( ! file_exists( $file ) ) wp_die( 'File not found' );

        global $wp_filesystem;
        if ( empty( $wp_filesystem ) ) {
            require_once ABSPATH . '/wp-admin/includes/file.php';
            WP_Filesystem();
        }

        header( 'Content-Type: text/csv; charset=utf-8' );
        header( 'Content-Disposition: attachment; filename="example-content-plan.csv"' );
        header( 'Pragma: no-cache' );
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo $wp_filesystem->get_contents( $file );
        exit;
    }

    public function ajax_activate_license(): void {
        check_ajax_referer( 'naseo_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_die( -1 );

        $key = sanitize_text_field( wp_unslash( $_POST['license_key'] ?? '' ) );
        if ( ! $key ) {
            wp_send_json_error( [ 'message' => __( 'Введіть ліцензійний ключ.', 'nemynai-seo-autopilot' ) ] );
        }

        $result = NASEO_License::activate( $key );
        if ( $result['success'] ) {
            wp_send_json_success( $result );
        } else {
            wp_send_json_error( $result );
        }
    }

    public function ajax_deactivate_license(): void {
        check_ajax_referer( 'naseo_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_die( -1 );
        $result = NASEO_License::deactivate();
        wp_send_json_success( $result );
    }
}
