<?php
/**
 * Cron functionality for LLMS.txt Generator
 */
if (!defined('ABSPATH')) {
    exit;
}
class CCSPLLMS_Cron {
    
    public function __construct() {
        add_action('ccspllms_generate_file', array($this, 'scheduled_generation'));
        add_action('wp_insert_post', array($this, 'post_published'), 10, 3);
        add_action('post_updated', array($this, 'post_updated'), 10, 3);
        add_filter('cron_schedules', array($this, 'add_custom_schedules'));
    }
    
    public function add_custom_schedules($schedules) {
        $schedules['ccspllms_hourly'] = array(
            'interval' => HOUR_IN_SECONDS,
            'display' => 'Every Hour'
        );
        
        $schedules['ccspllms_twice_daily'] = array(
            'interval' => 12 * HOUR_IN_SECONDS,
            'display' => 'Twice Daily'
        );
        
        $schedules['ccspllms_weekly'] = array(
            'interval' => WEEK_IN_SECONDS,
            'display' => 'Weekly'
        );
        
        return $schedules;
    }
    
    public function scheduled_generation() {

        $generator = new CCSPLLMS_Generator();
        $result = $generator->generate_file();
        
        // Log the generation
        $this->log_cron_generation($result);
        
        // Send notification if enabled
        if (get_option('ccspllms_email_notifications')) {
            $this->send_generation_notification($result);
        }
        
        // Clean up old data
        $database = new CCSPLLMS_Database();
        $database->cleanup_old_data();
    }
    
    public function post_published($post_id, $post, $update) {
        if ($update) {
            return; // This is an update, not a new post
        }
        
        if (!get_option('ccspllms_auto_regenerate_new', 1)) {
            return;
        }
        
        $post_types = get_option('ccspllms_post_types', array('post', 'page'));
        if (!in_array($post->post_type, $post_types)) {
            return;
        }
        
        if ($post->post_status !== 'publish') {
            return;
        }
        
        // Schedule generation with a small delay to avoid conflicts
        wp_schedule_single_event(time() + 60, 'ccspllms_generate_file');
    }
    
    public function post_updated($post_id, $post_after, $post_before) {
        if (!get_option('ccspllms_auto_regenerate_update', 0)) {
            return;
        }
        
        $post_types = get_option('ccspllms_post_types', array('post', 'page'));
        if (!in_array($post_after->post_type, $post_types)) {
            return;
        }
        
        // Only regenerate if the post is published and content changed
        if ($post_after->post_status !== 'publish') {
            return;
        }
        
        if ($post_after->post_content === $post_before->post_content && 
            $post_after->post_title === $post_before->post_title &&
            $post_after->post_excerpt === $post_before->post_excerpt) {
            return;
        }
        
        // Schedule generation with a small delay
        wp_schedule_single_event(time() + 60, 'ccspllms_generate_file');
    }
    
    public function update_schedule($frequency, $time = '02:00') {
        // Clear existing schedule
        wp_clear_scheduled_hook('ccspllms_generate_file');
        
        if ($frequency === 'disabled') {
            return true;
        }
        
        // Calculate next run time
        $next_run = $this->calculate_next_run($frequency, $time);
        
        // Schedule new event
        $result = wp_schedule_event($next_run, $frequency, 'ccspllms_generate_file');
        
        // Update options
        update_option('ccspllms_cron_frequency', $frequency);
        update_option('ccspllms_cron_time', $time);
        
        return $result !== false;
    }
    
    private function calculate_next_run($frequency, $time) {
        $time_parts = explode(':', $time);
        $hour = intval($time_parts[0]);
        $minute = intval($time_parts[1] ?? 0);
        
        $now = current_time('timestamp');
        $today = strtotime('today', $now);
        $scheduled_today = $today + ($hour * HOUR_IN_SECONDS) + ($minute * MINUTE_IN_SECONDS);
        
        if ($scheduled_today > $now) {
            return $scheduled_today;
        } else {
            // Schedule for tomorrow
            return $scheduled_today + DAY_IN_SECONDS;
        }
    }
    
    private function log_cron_generation($success) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'ccspllms_generation_log';
        
        $wpdb->insert(
            $table_name,
            array(
                'generated_at' => current_time('mysql'),
                'trigger_type' => 'cron',
                'success' => $success ? 1 : 0,
                'error_message' => $success ? null : 'Generation failed'
            ),
            array('%s', '%s', '%d', '%s')
        );
    }
    
    private function send_generation_notification($success) {
        $email = get_option('ccspllms_notification_email') ?: get_option('admin_email');
        
        if ($success) {
            $subject = 'LLMS.txt File Generated Successfully';
            $message = "Your LLMS.txt file has been automatically generated.\n\n";
            $message .= "Generation Time: " . current_time('Y-m-d H:i:s') . "\n";
            $message .= "File URL: " . get_site_url() . "/llms.txt\n";
        } else {
            $subject = 'LLMS.txt Generation Failed';
            $message = "There was an error generating your LLMS.txt file.\n\n";
            $message .= "Time: " . current_time('Y-m-d H:i:s') . "\n";
            $message .= "Please check your WordPress admin panel for more details.\n";
        }
        
        $message .= "\nSite: " . get_site_url();
        
        wp_mail($email, $subject, $message);
    }
    
    public function get_next_scheduled() {
        $timestamp = wp_next_scheduled('ccspllms_generate_file');
        return $timestamp ? gmdate('Y-m-d H:i:s', $timestamp) : null;
    }
    
    public function get_generation_history($limit = 20) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'ccspllms_generation_log';
        
        $results = $wpdb->get_results($wpdb->prepare("
            SELECT * FROM $table_name 
            ORDER BY generated_at DESC 
            LIMIT %d
        ", $limit));
        
        return $results;
    }
    
    public function force_regeneration() {
        
        // Clear any existing scheduled generation
        wp_clear_scheduled_hook('ccspllms_generate_file');

        $generator = new CCSPLLMS_Generator();
        $result = $generator->generate_file();

        if ($result) {
            // Log the generation
            $this->log_force_generation($result);
        }
        
        
        // Clean up old data
        $database = new CCSPLLMS_Database();
        $database->cleanup_old_data();

        return true;
    }


    private function log_force_generation($success) {
       
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'ccspllms_generation_log';
        
        $wpdb->insert(
            $table_name,
            array(
                'generated_at' => current_time('mysql'),
                'trigger_type' => 'force',
                'success' => $success ? 1 : 0,
                'error_message' => $success ? null : 'Generation failed'
            ),
            array('%s', '%s', '%d', '%s')
        );
    }
    
}   