<?php
/**
 * Aysa Cron Job Handler
 * 
 * Handles automated processing of association tasks
 */

if (!defined('ABSPATH')) {
    exit;
}

class Aysa_Cron {
    
    /**
     * Constructor
     */
    public function __construct() {
        add_action('init', array($this, 'schedule_cron_jobs'));
        add_action('aysa_process_association_tasks', array($this, 'process_association_tasks'));
        register_deactivation_hook(AYSA_PLUGIN_FILE, array($this, 'clear_scheduled_hooks'));
    }
    
    /**
     * Schedule cron jobs
     */
    public function schedule_cron_jobs() {
        if (!wp_next_scheduled('aysa_process_association_tasks')) {
            wp_schedule_event(time(), 'hourly', 'aysa_process_association_tasks');
        }
    }
    
    /**
     * Clear scheduled hooks on plugin deactivation
     */
    public function clear_scheduled_hooks() {
        wp_clear_scheduled_hook('aysa_process_association_tasks');
    }
    
    /**
     * Process association tasks automatically
     */
    public function process_association_tasks() {
        aysa_debug_log('[AYSA CRON] Starting association task processing');
        
        $project_id = $this->get_project_id();
        if (!$project_id) {
            aysa_debug_log('[AYSA CRON] No project ID found, skipping processing');
            return;
        }
        
        try {
            $to_associate_count = $this->get_keywords_to_associate_count($project_id);
            
            if ($to_associate_count <= 0) {
                aysa_debug_log('[AYSA CRON] No keywords to associate, skipping processing');
                return;
            }
            
            aysa_debug_log("[AYSA CRON] Found {$to_associate_count} keywords to associate");
            
            $keywords = $this->get_unassociated_keywords($project_id);
            
            if (empty($keywords)) {
                aysa_debug_log('[AYSA CRON] No unassociated keywords found');
                return;
            }
            
            $keywords_to_process = array_slice($keywords, 0, $to_associate_count);
            
            aysa_debug_log("[AYSA CRON] Processing " . count($keywords_to_process) . " keywords");
            
            $result = $this->generate_keyword_associations($keywords_to_process, $project_id);
            
            if ($result) {
                $remaining_count = $this->get_keywords_to_associate_count($project_id);
                aysa_debug_log("[AYSA CRON] Processing completed. Remaining keywords: {$remaining_count}");
                
                $this->update_task_description($project_id, $remaining_count);
            }
            
        } catch (Exception $e) {
            aysa_debug_log('[AYSA CRON] Error processing association tasks: ' . $e->getMessage());
        }
    }
    
    /**
     * Get project ID from WordPress options or cookies
     */
    private function get_project_id() {
        $project_id = get_option('aysa_project_id');
        
        if (!$project_id) {
            $project_id = get_transient('aysa_project_id');
        }
        
        if (!$project_id) {
            $current_user = wp_get_current_user();
            if ($current_user->ID) {
                $project_id = get_user_meta($current_user->ID, 'aysa_project_id', true);
            }
        }
        
        if (!$project_id) {
            aysa_debug_log('[AYSA CRON] Could not determine project ID automatically. Please ensure project ID is set in plugin options.');
        }
        
        return $project_id ? intval($project_id) : null;
    }
    
    /**
     * Get the count of keywords that need to be associated
     */
    private function get_keywords_to_associate_count($project_id) {
        $api_url = AYSA_API_BASE_URL . "api/AssociationsTask/ToAssociateCount/{$project_id}";
        
        $response = wp_remote_get($api_url, array(
            'timeout' => 30,
            'headers' => array(
                'Content-Type' => 'application/json'
            )
        ));
        
        if (is_wp_error($response)) {
            aysa_debug_log('[AYSA CRON] Error fetching association count: ' . $response->get_error_message());
            return 0;
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        return isset($data['toAssociateCount']) ? intval($data['toAssociateCount']) : 0;
    }
    
    /**
     * Get unassociated keywords
     */
    private function get_unassociated_keywords($project_id) {
        $api_url = AYSA_API_BASE_URL . "api/Keyword/ByProject/{$project_id}";
        
        $response = wp_remote_get($api_url, array(
            'timeout' => 30,
            'headers' => array(
                'Content-Type' => 'application/json'
            )
        ));
        
        if (is_wp_error($response)) {
            aysa_debug_log('[AYSA CRON] Error fetching keywords: ' . $response->get_error_message());
            return array();
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (!is_array($data)) {
            aysa_debug_log('[AYSA CRON] Invalid keywords response format');
            return array();
        }
        
        $unassociated_keywords = array();
        foreach ($data as $keyword_data) {
            if (isset($keyword_data['keyword'])) {
                $has_associations = false;
                if (isset($keyword_data['associations']) && is_array($keyword_data['associations'])) {
                    $has_associations = count($keyword_data['associations']) > 0;
                }
                
                if (!$has_associations) {
                    $unassociated_keywords[] = $keyword_data['keyword'];
                }
            }
        }
        
        aysa_debug_log('[AYSA CRON] Found ' . count($unassociated_keywords) . ' unassociated keywords out of ' . count($data) . ' total keywords');
        return $unassociated_keywords;
    }
    
    /**
     * Generate keyword associations using the same logic as the frontend
     */
    private function generate_keyword_associations($keywords, $project_id) {
        $categories = $this->get_woocommerce_categories();
        $pages = $this->get_wordpress_pages();
        $products = $this->get_woocommerce_products();
        
        $request_data = array(
            'ProjectId' => $project_id,
            'Keywords' => $keywords,
            'Categories' => $categories,
            'Pages' => $pages,
            'Products' => $products
        );
        
        $api_url = AYSA_API_BASE_URL . 'api/ChatGPT/generate-keyword-associations';
        
        $response = wp_remote_post($api_url, array(
            'timeout' => 120, // Longer timeout for association generation
            'headers' => array(
                'Content-Type' => 'application/json'
            ),
            'body' => json_encode($request_data)
        ));
        
        if (is_wp_error($response)) {
            aysa_debug_log('[AYSA CRON] Error generating associations: ' . $response->get_error_message());
            return false;
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        if ($response_code !== 200) {
            aysa_debug_log('[AYSA CRON] API returned error code: ' . $response_code);
            return false;
        }
        
        $body = wp_remote_retrieve_body($response);
        $result = json_decode($body, true);
        
        if (!$result || !isset($result['createdAssociations'])) {
            aysa_debug_log('[AYSA CRON] Invalid response format from association API');
            return false;
        }
        
        aysa_debug_log('[AYSA CRON] Successfully generated ' . count($result['createdAssociations']) . ' associations');
        return $result;
    }
    
    /**
     * Get WooCommerce categories
     */
    private function get_woocommerce_categories() {
        $terms = get_terms(array(
            'taxonomy' => 'product_cat',
            'hide_empty' => false,
        ));
        
        if (is_wp_error($terms)) {
            return array();
        }
        
        $categories = array();
        foreach ($terms as $term) {
            $categories[] = array(
                'Id' => $term->term_id,
                'Name' => $term->name
            );
        }
        
        return $categories;
    }
    
    /**
     * Get WordPress pages
     */
    private function get_wordpress_pages() {
        $pages = get_posts(array(
            'post_type' => 'page',
            'posts_per_page' => -1,
            'post_status' => 'publish'
        ));
        
        $page_data = array();
        foreach ($pages as $page) {
            $page_data[] = array(
                'Id' => $page->ID,
                'Name' => $page->post_title
            );
        }
        
        return $page_data;
    }
    
    /**
     * Get WooCommerce products
     */
    private function get_woocommerce_products() {
        $products = get_posts(array(
            'post_type' => 'product',
            'posts_per_page' => -1,
            'post_status' => 'publish'
        ));
        
        $product_data = array();
        foreach ($products as $product) {
            $product_data[] = array(
                'Id' => $product->ID,
                'Name' => $product->post_title
            );
        }
        
        return $product_data;
    }
    
    /**
     * Update task description with remaining keyword count
     */
    private function update_task_description($project_id, $remaining_count) {
        aysa_debug_log("[AYSA CRON] Task updated - Remaining keywords to associate: {$remaining_count}");
        
        update_option('aysa_remaining_association_count', $remaining_count);
        update_option('aysa_last_association_processing', current_time('mysql'));
    }
}

new Aysa_Cron();
