<?php
/**
 * Admin Settings
 *
 * @package AIContentGenerator
 */

namespace AICG;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Admin interface and settings management
 */
class Admin_Settings
{

    /**
     * AI Client instance
     */
    private $ai_client;

    /**
     * Pexels API instance
     */
    private $pexels;

    /**
     * Keyword Manager instance
     */
    private $keyword_manager;

    /**
     * Scheduler instance
     */
    private $scheduler;

    /**
     * Constructor
     */
    public function __construct($ai_client, $pexels, $keyword_manager, $scheduler)
    {
        $this->ai_client = $ai_client;
        $this->pexels = $pexels;
        $this->keyword_manager = $keyword_manager;
        $this->scheduler = $scheduler;

        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_assets'));
        add_action('admin_init', array($this, 'register_settings'));
    }

    /**
     * Add admin menu
     */
    public function add_admin_menu()
    {
        $is_registered = true;
        if ( function_exists( 'roidaico_fs' ) ) {
            $is_registered = roidaico_fs()->is_registered() || roidaico_fs()->is_anonymous();
        }

        // Main menu
        add_menu_page(
            __('AI Content Generator', 'roidnet-ai-content-generator'),
            __('AI Content', 'roidnet-ai-content-generator'),
            'edit_posts',
            'roidnet-ai-content-generator',
            array($this, 'render_dashboard_page'),
            'dashicons-edit-page',
            30
        );

        if ( $is_registered ) {
            // Dashboard (same as main)
            add_submenu_page(
                'roidnet-ai-content-generator',
                __('Dashboard', 'roidnet-ai-content-generator'),
                __('Dashboard', 'roidnet-ai-content-generator'),
                'edit_posts',
                'roidnet-ai-content-generator',
                array($this, 'render_dashboard_page')
            );
        }

        // Keywords
        add_submenu_page(
            'roidnet-ai-content-generator',
            __('Keywords Queue', 'roidnet-ai-content-generator'),
            __('Keywords', 'roidnet-ai-content-generator'),
            'edit_posts',
            'roidaico-keywords',
            array($this, 'render_keywords_page')
        );

        // Schedules
        add_submenu_page(
            'roidnet-ai-content-generator',
            __('Publishing Schedules', 'roidnet-ai-content-generator'),
            __('Schedules', 'roidnet-ai-content-generator'),
            'manage_options',
            'roidaico-schedules',
            array($this, 'render_schedules_page')
        );

        // Settings
        add_submenu_page(
            'roidnet-ai-content-generator',
            __('Settings', 'roidnet-ai-content-generator'),
            __('Settings', 'roidnet-ai-content-generator'),
            'manage_options',
            'roidaico-settings',
            array($this, 'render_settings_page')
        );

        // System Log (Pro only)
        if ( function_exists( 'roidaico_fs' ) && roidaico_fs()->can_use_premium_code() ) {
            add_submenu_page(
                'roidnet-ai-content-generator',
                __('System Log', 'roidnet-ai-content-generator'),
                __('System Log', 'roidnet-ai-content-generator'),
                'manage_options',
                'roidaico-logs',
                array($this, 'render_logs_page')
            );
        }
    }

    /**
     * Enqueue admin assets
     */
    public function enqueue_assets($hook)
    {
        // Only load on our pages
        if (strpos($hook, 'roidnet-ai-content-generator') === false && strpos($hook, 'roidaico-') === false) {
            return;
        }

        wp_enqueue_style(
            'roidaico-admin-styles',
            ROIDAICO_PLUGIN_URL . 'admin/css/admin-styles.css',
            array(),
            filemtime(ROIDAICO_PLUGIN_DIR . 'admin/css/admin-styles.css')
        );

        // Enqueue Select2
        wp_enqueue_style('roidaico-select2-css', ROIDAICO_PLUGIN_URL . 'admin/vendor/select2/select2.min.css', array(), '4.1.0');
        wp_enqueue_script('roidaico-select2-js', ROIDAICO_PLUGIN_URL . 'admin/vendor/select2/select2.min.js', array('jquery'), '4.1.0', true);

        wp_enqueue_script(
            'roidaico-admin-scripts',
            ROIDAICO_PLUGIN_URL . 'admin/js/admin-scripts.js',
            array('jquery', 'roidaico-select2-js'),
            filemtime(ROIDAICO_PLUGIN_DIR . 'admin/js/admin-scripts.js'),
            true
        );

        wp_localize_script('roidaico-admin-scripts', 'aicgAdmin', array(
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('roidaico_nonce'),
            'isPro' => ( function_exists( 'roidaico_fs' ) && roidaico_fs()->can_use_premium_code() ) ? 1 : 0,
            'strings' => array(
                'confirmDelete' => __('Are you sure you want to delete this?', 'roidnet-ai-content-generator'),
                'generating' => __('Generating...', 'roidnet-ai-content-generator'),
                'saving' => __('Saving...', 'roidnet-ai-content-generator'),
                'error' => __('An error occurred.', 'roidnet-ai-content-generator'),
                'success' => __('Success!', 'roidnet-ai-content-generator'),
            ),
        ));
    }

    /**
     * Register settings
     */
    public function register_settings()
    {
        // API Settings
        register_setting('roidaico_api_settings', 'roidaico_ai_provider', array(
            'sanitize_callback' => 'sanitize_text_field',
            'default' => 'openrouter',
        ));
        register_setting('roidaico_api_settings', 'roidaico_openrouter_api_key', array(
            'sanitize_callback' => 'sanitize_text_field',
        ));
        register_setting('roidaico_api_settings', 'roidaico_openrouter_model', array(
            'sanitize_callback' => 'sanitize_text_field',
        ));
        register_setting('roidaico_api_settings', 'roidaico_pexels_api_key', array(
            'sanitize_callback' => 'sanitize_text_field',
        ));
        register_setting('roidaico_api_settings', 'roidaico_image_source', array(
            'sanitize_callback' => 'sanitize_text_field',
        ));
        register_setting('roidaico_api_settings', 'roidaico_ai_image_model', array(
            'sanitize_callback' => 'sanitize_text_field',
        ));

        // Content Settings
        register_setting('roidaico_content_settings', 'roidaico_default_tone', array(
            'sanitize_callback' => 'sanitize_text_field',
        ));
        register_setting('roidaico_content_settings', 'roidaico_default_length', array(
            'sanitize_callback' => 'sanitize_text_field',
        ));
        register_setting('roidaico_content_settings', 'roidaico_default_language', array(
            'sanitize_callback' => 'sanitize_text_field',
        ));
        register_setting('roidaico_content_settings', 'roidaico_enable_internal_links', array(
            'sanitize_callback' => 'absint',
        ));
        register_setting('roidaico_content_settings', 'roidaico_max_internal_links', array(
            'sanitize_callback' => 'absint',
        ));
        register_setting('roidaico_content_settings', 'roidaico_custom_instructions', array(
            'sanitize_callback' => 'sanitize_textarea_field',
        ));
        register_setting('roidaico_content_settings', 'roidaico_images_count', array(
            'sanitize_callback' => 'absint',
        ));
        register_setting('roidaico_content_settings', 'roidaico_seo_plugin', array(
            'sanitize_callback' => 'sanitize_text_field',
        ));

        // Queue Settings
        register_setting('roidaico_queue_settings', 'roidaico_max_ready_articles', array(
            'sanitize_callback' => 'absint',
        ));
        register_setting('roidaico_queue_settings', 'roidaico_min_interval_minutes', array(
            'sanitize_callback' => 'absint',
        ));
        register_setting('roidaico_queue_settings', 'roidaico_auto_generate_keywords', array(
            'sanitize_callback' => 'absint',
        ));
        register_setting('roidaico_queue_settings', 'roidaico_auto_translate_keywords', array(
            'sanitize_callback' => 'absint',
            'default' => 0,
        ));
        register_setting('roidaico_queue_settings', 'roidaico_auto_generate_category', array(
            'sanitize_callback' => 'absint',
        ));
        register_setting('roidaico_queue_settings', 'roidaico_auto_generate_instructions', array(
            'sanitize_callback' => 'sanitize_textarea_field',
        ));
    }

    /**
     * Render dashboard page
     */
    public function render_dashboard_page()
    {
        include ROIDAICO_PLUGIN_DIR . 'admin/views/dashboard-page.php';
    }

    /**
     * Render keywords page
     */
    public function render_keywords_page()
    {
        include ROIDAICO_PLUGIN_DIR . 'admin/views/keywords-page.php';
    }

    /**
     * Render schedules page
     */
    public function render_schedules_page()
    {
        include ROIDAICO_PLUGIN_DIR . 'admin/views/schedule-page.php';
    }

    /**
     * Render settings page
     */
    public function render_settings_page()
    {
        include ROIDAICO_PLUGIN_DIR . 'admin/views/settings-page.php';
    }

    /**
     * Render logs page
     */
    public function render_logs_page()
    {
        include ROIDAICO_PLUGIN_DIR . 'admin/views/logs-page.php';
    }

    /**
     * Get available post types
     */
    public function get_post_types()
    {
        $post_types = get_post_types(array('public' => true), 'objects');
        $options = array();

        foreach ($post_types as $post_type) {
            if ($post_type->name === 'attachment') {
                continue;
            }
            $options[$post_type->name] = $post_type->labels->singular_name;
        }

        return $options;
    }

    /**
     * Get authors with edit capability
     */
    public function get_authors()
    {
        $users = get_users(array(
            'capability' => 'edit_posts',
            'fields' => array('ID', 'display_name'),
        ));

        $options = array();
        foreach ($users as $user) {
            $options[$user->ID] = $user->display_name;
        }

        return $options;
    }

    /**
     * Get categories
     */
    public function get_categories()
    {
        $categories = get_categories(array(
            'hide_empty' => false,
        ));

        $options = array(0 => __('Uncategorized', 'roidnet-ai-content-generator'));
        foreach ($categories as $category) {
            $options[$category->term_id] = $category->name;
        }

        return $options;
    }

    /**
     * Get tone options
     */
    public function get_tones()
    {
        return array(
            'professional' => __('Professional', 'roidnet-ai-content-generator'),
            'casual' => __('Casual', 'roidnet-ai-content-generator'),
            'friendly' => __('Friendly', 'roidnet-ai-content-generator'),
            'formal' => __('Formal', 'roidnet-ai-content-generator'),
            'humorous' => __('Humorous', 'roidnet-ai-content-generator'),
            'informative' => __('Informative', 'roidnet-ai-content-generator'),
        );
    }

    /**
     * Get length options
     */
    public function get_lengths()
    {
        return array(
            'short' => __('Short (~500 words)', 'roidnet-ai-content-generator'),
            'medium' => __('Medium (~1000 words)', 'roidnet-ai-content-generator'),
            'long' => __('Long (~2000+ words)', 'roidnet-ai-content-generator'),
        );
    }

    /**
     * Get language options
     */
    public function get_languages()
    {
        return array(
            'en' => __('English', 'roidnet-ai-content-generator'),
            'ar' => __('Arabic', 'roidnet-ai-content-generator'),
            'es' => __('Spanish', 'roidnet-ai-content-generator'),
            'fr' => __('French', 'roidnet-ai-content-generator'),
            'de' => __('German', 'roidnet-ai-content-generator'),
            'it' => __('Italian', 'roidnet-ai-content-generator'),
            'pt' => __('Portuguese', 'roidnet-ai-content-generator'),
            'ru' => __('Russian', 'roidnet-ai-content-generator'),
            'zh' => __('Chinese', 'roidnet-ai-content-generator'),
            'ja' => __('Japanese', 'roidnet-ai-content-generator'),
            'ko' => __('Korean', 'roidnet-ai-content-generator'),
            'tr' => __('Turkish', 'roidnet-ai-content-generator'),
        );
    }
}
