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


// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- Legacy internal class name is retained for the canonical loader and upgrade compatibility; it is not an extension API.
class Keywords_Controller {
    public function __construct() {
        // Register hooks
        $this->register_hook_callbacks();
    }

    /**
     * Register callbacks for actions and filters
     */
    public function register_hook_callbacks() {
        // AJAX actions
        add_action('wp_ajax_update_keyword_category', [$this, 'handle_update_keyword_category']);
        
        // Admin menu
        add_action('admin_menu', [$this, 'add_admin_menu']);
        
        // Enqueue scripts and styles
        add_action('admin_enqueue_scripts', [$this, 'enqueue_scripts']);
    }
    
    /**
     * Add admin menu items
     */
    public function add_admin_menu() {
        add_submenu_page(
            'aysa-dashboard',
            aysa_interface_text('Descoperire cuvinte-cheie', 'Keyword Discovery'),
            aysa_interface_text('Descoperire cuvinte-cheie', 'Keyword Discovery'),
            'manage_options',
            'aysa-keyword-discovery',
            [$this, 'render_keyword_discovery_page']
        );
    }
    
    /**
     * Enqueue necessary scripts and styles
     */
    public function enqueue_scripts($hook) {
        // Only load on our plugin pages
        if (strpos($hook, 'aysa') !== false) {
            wp_enqueue_style('aysa-admin-css', AYSA_PLUGIN_URL . 'assets/css/aysa-admin.css', [], AYSA_VERSION);
            wp_enqueue_script('aysa-keyword-association', AYSA_PLUGIN_URL . 'assets/js/keyword-association.js', ['jquery'], AYSA_VERSION, true);
            
            // Add AJAX object with URL and nonce
            wp_localize_script('aysa-keyword-association', 'aysa_ajax_object', [
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('aysa_keyword_nonce')
            ]);
        }
    }
    
    /**
     * Render the keyword discovery page
     */
    public function render_keyword_discovery_page() {
        include_once AYSA_PLUGIN_DIR . 'admin/partials/aysa-keyword-discovery.php';
    }
    
    /**
     * Handle AJAX request to update keyword category
     */
    public function handle_update_keyword_category() {
        // Check nonce for security
        check_ajax_referer('aysa_keyword_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Insufficient permissions'], 403);
            return;
        }
        
        // Get post data
        $keyword_id = isset($_POST['keyword_id']) ? intval(wp_unslash($_POST['keyword_id'])) : 0;
        $category_id = isset($_POST['category_id']) ? intval(wp_unslash($_POST['category_id'])) : 0;
        
        if (!$keyword_id || !$category_id) {
            wp_send_json_error(['message' => 'Missing required parameters']);
            return;
        }

        if (!current_user_can('edit_term', $category_id)) {
            wp_send_json_error(['message' => 'Term permission denied'], 403);
            return;
        }
        
        // Get the category name
        $category = get_term($category_id, 'product_cat');
        if (is_wp_error($category) || !$category) {
            wp_send_json_error(['message' => 'Invalid category']);
            return;
        }
        
        // Update the keyword-category association in database
        // This is a simplified example - adjust according to your database structure
        update_term_meta($category_id, 'aysa_keyword_id', $keyword_id);
        
        // You might also want to store this in a custom table or as post meta
        update_option('aysa_keyword_' . $keyword_id . '_category', $category_id);
        
        // Return success response
        wp_send_json_success([
            'message' => 'Category updated successfully',
            'category_name' => $category->name,
            'keyword_id' => $keyword_id,
            'category_id' => $category_id
        ]);
    }
    
    /**
     * Get all available keywords
     * 
     * @return array Array of keywords
     */
    public function get_keywords() {
        // This is a placeholder - implement according to your needs
        // You might retrieve from database, API, etc.
        return [
            ['id' => 1, 'keyword' => 'Sample Keyword 1', 'volume' => 1000],
            ['id' => 2, 'keyword' => 'Sample Keyword 2', 'volume' => 750],
            ['id' => 3, 'keyword' => 'Sample Keyword 3', 'volume' => 500],
        ];
    }
    
    /**
     * Get all categories for dropdown
     * 
     * @return array Array of categories
     */
    public function get_categories_for_dropdown() {
        $categories = get_terms([
            'taxonomy' => 'product_cat',
            'hide_empty' => false,
        ]);
        
        $formatted_categories = [];
        if (!is_wp_error($categories)) {
            foreach ($categories as $category) {
                $formatted_categories[] = [
                    'id' => $category->term_id,
                    'name' => $category->name
                ];
            }
        }
        
        return $formatted_categories;
    }
} 
