<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

/**
 * Scheduled Blog Widgets Class for Blogibot AI
 * Handles all scheduled blog data and functionality
 */
class Blog82AI_ScheduledBlog_Widgets {
    
    /**
     * Get schedule statistics data
     */
    public static function get_schedule_stats() {
        $scheduled = get_option('blog82ai_scheduled_blogs', []);
        
        $total_schedules = count($scheduled);
        $active_schedules = 0;
        $paused_schedules = 0;
        
        foreach ($scheduled as $schedule) {
            $status = $schedule['status'] ?? 'active';
            if ($status === 'active') {
                $active_schedules++;
            } elseif ($status === 'paused') {
                $paused_schedules++;
            }
        }
        
        // Get blogs generated this week from schedules
        global $wpdb;
        $week_start = date('Y-m-d H:i:s', strtotime('-7 days'));
        $blogs_this_week = $wpdb->get_var($wpdb->prepare("
            SELECT COUNT(DISTINCT p.ID) 
            FROM {$wpdb->posts} p 
            LEFT JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id 
            WHERE p.post_type = 'post' 
            AND p.post_status = 'publish' 
            AND p.post_date >= %s
            AND (pm.meta_key = '_blog82ai_generated' OR pm.meta_key = '_blogibot_generated')
        ", $week_start));
        
        return [
            'total_schedules' => $total_schedules,
            'active_schedules' => $active_schedules,
            'paused_schedules' => $paused_schedules,
            'blogs_this_week' => intval($blogs_this_week) ?: 0
        ];
    }
    
    /**
     * Get all WordPress categories for scheduler dropdown (only leaf categories, excluding scheduled ones)
     */
    public static function get_categories_for_dropdown() {
        // Get existing scheduled categories
        $scheduled_categories = self::get_scheduled_categories();
        
        // Get all WordPress categories
        $categories = get_categories([
            'hide_empty' => false,
            'orderby' => 'name',
            'order' => 'ASC'
        ]);
        
        $dropdown_options = [];
        
        foreach ($categories as $category) {
            // Skip if already scheduled
            if (in_array($category->name, $scheduled_categories)) {
                continue;
            }
            
            // Check if this category has children
            $has_children = false;
            foreach ($categories as $potential_child) {
                if ($potential_child->parent == $category->term_id) {
                    $has_children = true;
                    break;
                }
            }
            
            // Only include if:
            // 1. It has no children (leaf category), OR
            // 2. It's a child category (parent != 0)
            if (!$has_children || $category->parent != 0) {
                // Build the full hierarchy path for display
                $hierarchy_path = self::get_category_hierarchy($category->name);
                
                $dropdown_options[] = [
                    'value' => $category->name,
                    'label' => $hierarchy_path,
                    'id' => $category->term_id,
                    'slug' => $category->slug
                ];
            }
        }
        
        return $dropdown_options;
    }
    
    /**
     * Get all scheduled blogs with enhanced data
     */
    public static function get_all_schedules() {
        $scheduled = get_option('blog82ai_scheduled_blogs', []);
        $enhanced_schedules = [];
        
        foreach ($scheduled as $schedule) {
            $schedule_id = $schedule['id'] ?? 'legacy_' . ($schedule['time'] ?? time());
            $category = $schedule['category'] ?? '';
            $status = $schedule['status'] ?? 'active';
            $run_time = $schedule['run_time'] ?? '00:00';
            $start_date = $schedule['time'] ?? date('Y-m-d');
            $timestamp = $schedule['timestamp'] ?? strtotime($start_date . ' ' . $run_time);
            
            // Calculate next run time
            $next_run = self::calculate_next_run($timestamp, $run_time, $status);
            
            // Get category hierarchy
            $category_hierarchy = self::get_category_hierarchy($category);
            
            $enhanced_schedules[] = [
                'id' => $schedule_id,
                'category' => $category,
                'category_hierarchy' => $category_hierarchy,
                'start_date' => date('Y-m-d', strtotime($start_date)),
                'run_time' => date('h:i A', strtotime($run_time)),
                'run_time_24' => $run_time,
                'frequency' => 'Daily', // Default to daily for now
                'next_run' => $next_run,
                'status' => $status,
                'timestamp' => $timestamp
            ];
        }
        
        return $enhanced_schedules;
    }
    
    /**
     * Calculate next run time for a schedule
     */
    private static function calculate_next_run($timestamp, $run_time, $status) {
        if ($status === 'paused') {
            return ''; // Return empty string for paused schedules
        }
        
        $now = current_time('timestamp');
        $today_date = date('Y-m-d', $now);
        $next_run = strtotime($today_date . ' ' . $run_time);
        
        // If today's time has passed, schedule for tomorrow
        if ($next_run <= $now) {
            $next_run = strtotime('+1 day', $next_run);
        }
        
        return date('Y-m-d h:i A', $next_run);
    }
    
    /**
     * Get category hierarchy string
     */
    private static function get_category_hierarchy($category_name) {
        if (empty($category_name)) return '';
        
        $category = get_term_by('name', $category_name, 'category');
        if (!$category) return $category_name;
        
        $names = [$category->name];
        $current_category = $category;
        
        while ($current_category->parent != 0) {
            $current_category = get_term($current_category->parent, 'category');
            if ($current_category && !is_wp_error($current_category)) {
                array_unshift($names, $current_category->name);
            } else {
                break;
            }
        }
        
        return implode(' — ', $names);
    }
    
    /**
     * Get unique categories from existing schedules for filter dropdown
     */
    public static function get_scheduled_categories() {
        $scheduled = get_option('blog82ai_scheduled_blogs', []);
        $categories = [];
        
        foreach ($scheduled as $schedule) {
            if (!empty($schedule['category']) && !in_array($schedule['category'], $categories)) {
                $categories[] = $schedule['category'];
            }
        }
        
        sort($categories);
        return $categories;
    }
    
    /**
     * Format schedule data for AJAX responses
     */
    public static function format_schedule_for_response($schedule) {
        return [
            'id' => $schedule['id'],
            'category' => $schedule['category_hierarchy'],
            'start_date' => $schedule['start_date'],
            'run_time' => $schedule['run_time'],
            'frequency' => $schedule['frequency'],
            'next_run' => $schedule['next_run'],
            'status' => $schedule['status']
        ];
    }
    
    /**
     * Get schedule by ID with enhanced data
     */
    public static function get_schedule_by_id($schedule_id) {
        $scheduled = get_option('blog82ai_scheduled_blogs', []);
        
        foreach ($scheduled as $schedule) {
            $id = $schedule['id'] ?? 'legacy_' . ($schedule['time'] ?? time());
            if ($id === $schedule_id) {
                // Enhance with calculated fields
                $enhanced_schedule = [
                    'id' => $id,
                    'category' => $schedule['category'] ?? '',
                    'category_hierarchy' => self::get_category_hierarchy($schedule['category'] ?? ''),
                    'start_date' => $schedule['start_date'] ?? $schedule['time'] ?? '',
                    'run_time' => $schedule['run_time'] ?? '00:00',
                    'run_time_24' => $schedule['run_time'] ?? '00:00',
                    'frequency' => $schedule['frequency'] ?? 'Daily',
                    'status' => $schedule['status'] ?? 'active',
                    'next_run' => self::calculate_next_run(
                        $schedule['timestamp'] ?? time(),
                        $schedule['run_time'] ?? '00:00',
                        $schedule['status'] ?? 'active'
                    ),
                    'created_at' => $schedule['created_at'] ?? current_time('mysql'),
                    'timestamp' => $schedule['timestamp'] ?? time()
                ];
                
                // Format times properly
                if (isset($schedule['run_time']) && $schedule['run_time'] !== '00:00') {
                    $enhanced_schedule['run_time'] = date('h:i A', strtotime($schedule['run_time']));
                }
                
                return $enhanced_schedule;
            }
        }
        
        return null;
    }
    
    /**
     * Update schedule status
     */
    public static function update_schedule_status($schedule_id, $new_status) {
        $scheduled = get_option('blog82ai_scheduled_blogs', []);
        $updated = false;
        
        foreach ($scheduled as $index => $schedule) {
            $id = $schedule['id'] ?? 'legacy_' . ($schedule['time'] ?? time());
            if ($id === $schedule_id) {
                $scheduled[$index]['status'] = $new_status;
                $updated = true;
                break;
            }
        }
        
        if ($updated) {
            update_option('blog82ai_scheduled_blogs', $scheduled);
        }
        
        return $updated;
    }
    
    /**
     * Delete schedule by ID
     */
    public static function delete_schedule($schedule_id) {
        $scheduled = get_option('blog82ai_scheduled_blogs', []);
        $schedule_index = -1;
        
        foreach ($scheduled as $index => $schedule) {
            $id = $schedule['id'] ?? 'legacy_' . ($schedule['time'] ?? time());
            if ($id === $schedule_id) {
                $schedule_index = $index;
                break;
            }
        }
        
        if ($schedule_index !== -1) {
            array_splice($scheduled, $schedule_index, 1);
            update_option('blog82ai_scheduled_blogs', $scheduled);
            return true;
        }
        
        return false;
    }
    
    /**
     * Check if category already has a schedule
     */
    public static function category_has_schedule($category) {
        $scheduled = get_option('blog82ai_scheduled_blogs', []);
        
        foreach ($scheduled as $schedule) {
            if ($schedule['category'] === $category) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * Update a schedule
     */
    public static function update_schedule($schedule_id, $data) {
        $scheduled = get_option('blog82ai_scheduled_blogs', []);
        $schedule_index = -1;
        
        foreach ($scheduled as $index => $schedule) {
            $id = $schedule['id'] ?? 'legacy_' . ($schedule['time'] ?? time());
            if ($id === $schedule_id) {
                $schedule_index = $index;
                break;
            }
        }
        
        if ($schedule_index !== -1) {
            // Update the fields
            if (isset($data['category'])) {
                $scheduled[$schedule_index]['category'] = $data['category'];
            }
            if (isset($data['start_date'])) {
                $scheduled[$schedule_index]['start_date'] = $data['start_date'];
                $scheduled[$schedule_index]['time'] = $data['start_date']; // For legacy compatibility
            }
            if (isset($data['run_time'])) {
                $scheduled[$schedule_index]['run_time'] = $data['run_time'];
            }
            if (isset($data['frequency'])) {
                $scheduled[$schedule_index]['frequency'] = $data['frequency'];
            }
            
            // Recalculate timestamp and next run
            $start_date = $scheduled[$schedule_index]['start_date'] ?? $scheduled[$schedule_index]['time'] ?? date('Y-m-d');
            $run_time = $scheduled[$schedule_index]['run_time'] ?? '00:00';
            $scheduled[$schedule_index]['timestamp'] = strtotime($start_date . ' ' . $run_time);
            
            return update_option('blog82ai_scheduled_blogs', $scheduled);
        }
        
        return false;
    }
}
