<?php
/**
 * TalkGenAI Utility Functions
 * Helper functions for the plugin
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit('Direct access not allowed.');
}

/**
 * Get TalkGenAI plugin instance
 */
function talkgenai() {
    return TalkGenAI_Plugin::get_instance();
}

/**
 * Get app by ID with permission check
 */
function talkgenai_get_app($app_id, $check_permission = true) {
    $database = talkgenai()->get_database();
    $app = $database->get_app($app_id);
    
    if (!$app) {
        return false;
    }
    
    // Check if user has permission to view this app
    if ($check_permission) {
        $current_user_id = get_current_user_id();
        if (isset($app['user_id']) && $app['user_id'] !== $current_user_id && !current_user_can('manage_options')) {
            return false;
        }
    }
    
    return $app;
}

/**
 * Get user's apps with pagination
 */
function talkgenai_get_user_apps($user_id = null, $args = array()) {
    if (!$user_id) {
        $user_id = get_current_user_id();
    }
    
    $defaults = array(
        'status' => 'active',
        'limit' => 20,
        'offset' => 0,
        'order_by' => 'created_at',
        'order' => 'DESC'
    );
    
    $args = wp_parse_args($args, $defaults);
    
    $database = talkgenai()->get_database();
    return $database->get_user_apps($user_id, $args['status'], $args['limit'], $args['offset']);
}

/**
 * Format app data for display
 */
function talkgenai_format_app_data($app) {
    if (!$app) {
        return false;
    }
    
    return array(
        'id' => intval($app['id']),
        'title' => esc_html($app['title']),
        'description' => esc_html($app['description']),
        'app_class' => isset($app['app_class']) ? esc_html($app['app_class']) : '',
        'app_type' => isset($app['app_type']) ? esc_html($app['app_type']) : '',
        'status' => isset($app['status']) ? esc_html($app['status']) : 'active',
        'created_at' => isset($app['created_at']) ? mysql2date('F j, Y g:i A', $app['created_at']) : '',
        'updated_at' => isset($app['updated_at']) ? mysql2date('F j, Y g:i A', $app['updated_at']) : '',
        'generation_time' => isset($app['generation_time']) && $app['generation_time'] ? round($app['generation_time'], 2) . 's' : 'N/A',
        'shortcode' => '[talkgenai_app id="' . intval($app['id']) . '"]'
    );
}

/**
 * Generate app title from description
 */
function talkgenai_generate_title($description, $max_length = 50) {
    // Clean and truncate description
    $title = sanitize_text_field($description);
    $title = wp_trim_words($title, 8, '...');
    
    if (strlen($title) > $max_length) {
        $title = substr($title, 0, $max_length - 3) . '...';
    }
    
    // Capitalize first letter
    $title = ucfirst($title);
    
    return $title;
}

/**
 * Check if user can create apps
 */
function talkgenai_user_can_create_apps($user_id = null) {
    if (!$user_id) {
        $user_id = get_current_user_id();
    }
    
    $user = get_user_by('ID', $user_id);
    if (!$user) {
        return false;
    }
    
    return user_can($user, TALKGENAI_MIN_CAPABILITY);
}

/**
 * Get app type display name
 */
function talkgenai_get_app_type_name($app_class, $app_type) {
    $type_names = array(
        'calculator' => array(
            'calculator_form' => __('Calculator', 'talkgenai')
        ),
        'timer' => array(
            'countdown' => __('Countdown Timer', 'talkgenai'),
            'pomodoro' => __('Pomodoro Timer', 'talkgenai'),
            'stopwatch' => __('Stopwatch', 'talkgenai')
        ),
        'todo' => array(
            'simple' => __('Todo List', 'talkgenai')
        ),
        'form' => array(
            'survey' => __('Survey Form', 'talkgenai'),
            'application' => __('Application Form', 'talkgenai')
        ),
        'game' => array(
            'puzzle' => __('Puzzle Game', 'talkgenai'),
            'memory' => __('Memory Game', 'talkgenai'),
            'trivia' => __('Trivia Game', 'talkgenai')
        )
    );
    
    if (isset($type_names[$app_class][$app_type])) {
        return $type_names[$app_class][$app_type];
    }
    
    // Fallback to formatted app type
    return ucwords(str_replace('_', ' ', $app_type));
}

/**
 * Get app class icon
 */
function talkgenai_get_app_class_icon($app_class) {
    $icons = array(
        'calculator' => 'dashicons-calculator',
        'timer' => 'dashicons-clock',
        'todo' => 'dashicons-list-view',
        'form' => 'dashicons-feedback',
        'game' => 'dashicons-games'
    );
    
    return $icons[$app_class] ?? 'dashicons-admin-generic';
}

/**
 * Format file size
 */
function talkgenai_format_file_size($bytes) {
    if ($bytes >= 1073741824) {
        return number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        return number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        return number_format($bytes / 1024, 2) . ' KB';
    } else {
        return $bytes . ' bytes';
    }
}

/**
 * Get server status indicator
 */
function talkgenai_get_server_status_indicator($status) {
    if (!$status || !$status['success']) {
        return '<span class="talkgenai-status talkgenai-status-error">' . esc_html__('Offline', 'talkgenai') . '</span>';
    }
    
    $response_time = $status['response_time'] ?? 0;
    
    if ($response_time < 1) {
        $class = 'talkgenai-status-excellent';
        $text = esc_html__('Excellent', 'talkgenai');
    } elseif ($response_time < 3) {
        $class = 'talkgenai-status-good';
        $text = esc_html__('Good', 'talkgenai');
    } elseif ($response_time < 5) {
        $class = 'talkgenai-status-fair';
        $text = esc_html__('Fair', 'talkgenai');
    } else {
        $class = 'talkgenai-status-slow';
        $text = esc_html__('Slow', 'talkgenai');
    }
    
    return sprintf(
        '<span class="talkgenai-status %s">%s (%.2fs)</span>',
        esc_attr($class),
        $text,
        $response_time
    );
}

/**
 * Sanitize app description for API
 */
function talkgenai_sanitize_description($description) {
    // Remove HTML tags
    $description = wp_strip_all_tags($description);
    
    // Limit length
    $max_length = 1000;
    if (strlen($description) > $max_length) {
        $description = substr($description, 0, $max_length);
    }
    
    // Remove excessive whitespace
    $description = preg_replace('/\s+/', ' ', $description);
    $description = trim($description);
    
    return $description;
}

/**
 * Validate shortcode attributes
 */
function talkgenai_validate_shortcode_atts($atts) {
    $defaults = array(
        'id' => 0,
        'container_class' => 'talkgenai-app-container'
    );
    
    $atts = shortcode_atts($defaults, $atts, 'talkgenai_app');
    
    // Validate ID
    $atts['id'] = intval($atts['id']);
    
    // Sanitize container class
    $atts['container_class'] = sanitize_html_class($atts['container_class']);
    
    return $atts;
}

/**
 * Build internal link candidates (WordPress posts/pages only) for AI enrichment.
 *
 * Returns an array of items:
 * - title: string
 * - url: string
 * - type: 'post'|'page'
 * - excerpt: string
 */
function talkgenai_get_internal_link_candidates($app_title, $app_description = '', $limit = 60) {
    $limit = intval($limit);
    if ($limit <= 0) {
        $limit = 60;
    }
    if ($limit > 80) {
        $limit = 80; // safety cap
    }

    $title = is_string($app_title) ? trim(wp_strip_all_tags($app_title)) : '';
    $desc = is_string($app_description) ? trim(wp_strip_all_tags($app_description)) : '';
    if ($title === '' && $desc === '') {
        return array();
    }

    // Simple keyword extraction from title/description (best-effort).
    $text = strtolower($title . ' ' . $desc);
    $words = preg_split('/[^a-z0-9]+/i', $text);
    $stop = array('the','and','for','with','from','that','this','your','you','are','was','were','will','have','has','can','app','web','site','website','page','pages','post','posts','tool','tools','use','using','how','what','why','when','where','about','into','over','under','more','most','less','than','then','them','they','their','ours','ourselves','it','its','a','an','to','of','in','on','at','by','as','is','be','or');
    $freq = array();
    foreach ($words as $w) {
        $w = trim($w);
        if ($w === '' || strlen($w) < 4) { continue; }
        if (in_array($w, $stop, true)) { continue; }
        $freq[$w] = isset($freq[$w]) ? $freq[$w] + 1 : 1;
    }
    arsort($freq);
    $top = array_slice(array_keys($freq), 0, 8);
    $keyword_query = implode(' ', $top);

    $search_queries = array();
    if ($title !== '') { $search_queries[] = $title; }
    if ($keyword_query !== '' && $keyword_query !== $title) { $search_queries[] = $keyword_query; }

    $seen = array();
    $out = array();

    foreach ($search_queries as $q) {
        if (count($out) >= $limit) { break; }
        $q = trim($q);
        if ($q === '') { continue; }

        $wpq = new WP_Query(array(
            's' => $q,
            'post_type' => array('post', 'page'),
            'post_status' => 'publish',
            'posts_per_page' => min(40, $limit),
            'fields' => 'ids',
            'no_found_rows' => true,
            'ignore_sticky_posts' => true,
        ));

        if (empty($wpq->posts) || !is_array($wpq->posts)) {
            continue;
        }

        foreach ($wpq->posts as $post_id) {
            if (count($out) >= $limit) { break; }
            $post_id = intval($post_id);
            if ($post_id <= 0) { continue; }
            if (isset($seen[$post_id])) { continue; }
            $seen[$post_id] = true;

            $post = get_post($post_id);
            if (!$post) { continue; }
            if ($post->post_status !== 'publish') { continue; }

            $permalink = get_permalink($post_id);
            if (!$permalink) { continue; }

            $ptype = get_post_type($post_id);
            $excerpt = '';
            if (!empty($post->post_excerpt)) {
                $excerpt = $post->post_excerpt;
            } else {
                $excerpt = $post->post_content;
            }
            $excerpt = wp_trim_words(wp_strip_all_tags($excerpt), 24, '…');

            $out[] = array(
                'title' => get_the_title($post_id),
                'url' => $permalink,
                'type' => $ptype === 'page' ? 'page' : 'post',
                'excerpt' => $excerpt,
            );
        }
    }

    // Fallback: if we found too few via search, expand candidate pool with recent posts/pages.
    // This helps the LLM find 3–6 relevant internal links even when WP search is sparse.
    $min_pool = 30;
    if (count($out) < $min_pool && count($out) < $limit) {
        $remaining_needed = $min_pool - count($out);
        $fetch = min($limit - count($out), max(0, $remaining_needed));
        if ($fetch > 0) {
            $wpq_recent = new WP_Query(array(
                'post_type' => array('post', 'page'),
                'post_status' => 'publish',
                'posts_per_page' => min(80, $fetch),
                'fields' => 'ids',
                'no_found_rows' => true,
                'ignore_sticky_posts' => true,
                'orderby' => 'date',
                'order' => 'DESC',
            ));

            if (!empty($wpq_recent->posts) && is_array($wpq_recent->posts)) {
                foreach ($wpq_recent->posts as $post_id) {
                    if (count($out) >= $limit) { break; }
                    $post_id = intval($post_id);
                    if ($post_id <= 0) { continue; }
                    if (isset($seen[$post_id])) { continue; }
                    $seen[$post_id] = true;

                    $post = get_post($post_id);
                    if (!$post) { continue; }
                    if ($post->post_status !== 'publish') { continue; }

                    $permalink = get_permalink($post_id);
                    if (!$permalink) { continue; }

                    $ptype = get_post_type($post_id);
                    $excerpt = '';
                    if (!empty($post->post_excerpt)) {
                        $excerpt = $post->post_excerpt;
                    } else {
                        $excerpt = $post->post_content;
                    }
                    $excerpt = wp_trim_words(wp_strip_all_tags($excerpt), 24, '…');

                    $out[] = array(
                        'title' => get_the_title($post_id),
                        'url' => $permalink,
                        'type' => $ptype === 'page' ? 'page' : 'post',
                        'excerpt' => $excerpt,
                    );
                }
            }
        }
    }

    return $out;
}

/**
 * Get plugin settings with defaults
 */
function talkgenai_get_settings($key = null) {
    $defaults = array(
        'server_mode' => 'local',
        'local_server_url' => 'http://localhost:8000',
        'remote_server_url' => '',
        'remote_api_key' => '',
        'max_requests_per_hour' => TALKGENAI_MAX_REQUESTS_PER_HOUR,
        'enable_debug_logging' => false,
        'last_server_health_check' => '',
        'plugin_version' => TALKGENAI_VERSION
    );
    
    $settings = get_option('talkgenai_settings', array());
    $settings = wp_parse_args($settings, $defaults);
    
    if ($key) {
        return $settings[$key] ?? null;
    }
    
    return $settings;
}

/**
 * Log debug message
 */
function talkgenai_log($message, $level = 'info') {
    if (!talkgenai_get_settings('enable_debug_logging') && !WP_DEBUG) {
        return;
    }
    
    $timestamp = current_time('Y-m-d H:i:s');
    $log_message = "[{$timestamp}] TalkGenAI [{$level}]: {$message}";
    
    // Debug logging removed for WordPress.org submission
    // error_log($log_message);
}

/**
 * Check if current page is TalkGenAI admin page
 */
function talkgenai_is_admin_page() {
    // Only available in admin and after screen API is loaded
    if (!is_admin()) {
        return false;
    }
    if (!function_exists('get_current_screen')) {
        return false;
    }
    $screen = get_current_screen();
    if (!$screen || empty($screen->id)) {
        return false;
    }
    return strpos($screen->id, 'talkgenai') !== false;
}

/**
 * Add nonce attribute to TalkGenAI script tags only
 */
add_filter('script_loader_tag', function($tag, $handle, $src) {
    if (strpos($handle, 'talkgenai-app-') === 0 && class_exists('TalkGenAI_Security')) {
        $nonce = TalkGenAI_Security::get_request_nonce();
        // Inject nonce only if not already present
        if (strpos($tag, ' nonce=') === false) {
            $tag = str_replace('<script ', '<script nonce="' . esc_attr($nonce) . '" ', $tag);
        }
    }
    return $tag;
}, 10, 3);

/**
 * Get usage statistics for user
 */
// usage stats removed per user request

/**
 * Format response time
 */
function talkgenai_format_response_time($time) {
    if ($time < 1) {
        return round($time * 1000) . 'ms';
    } else {
        return round($time, 2) . 's';
    }
}

/**
 * Check if server is local
 */
function talkgenai_is_local_server() {
    $settings = talkgenai_get_settings();
    return $settings['server_mode'] === 'local';
}

/**
 * Get app preview URL
 */
function talkgenai_get_app_preview_url($app_id) {
    return add_query_arg(
        array(
            'page' => 'talkgenai',
            'action' => 'preview',
            'app_id' => $app_id
        ),
        admin_url('admin.php')
    );
}

/**
 * Get app edit URL
 */
function talkgenai_get_app_edit_url($app_id) {
    return add_query_arg(
        array(
            'page' => 'talkgenai',
            'action' => 'edit',
            'app_id' => $app_id
        ),
        admin_url('admin.php')
    );
}

/**
 * Render admin notice
 */
function talkgenai_admin_notice($message, $type = 'info', $dismissible = true) {
    $classes = array('notice', 'notice-' . $type, 'talkgenai-notice');
    
    if ($dismissible) {
        $classes[] = 'is-dismissible';
    }
    
    printf(
        '<div class="%s"><p>%s</p></div>',
        esc_attr(implode(' ', $classes)),
        wp_kses_post($message)  // Allow safe HTML (links, etc.)
    );
}

/**
 * Check plugin requirements
 */
function talkgenai_check_requirements() {
    $errors = array();
    
    // Check PHP version
    if (version_compare(PHP_VERSION, '7.3', '<')) {
        $errors[] = sprintf(
            /* translators: %s: current PHP version */
            __('TalkGenAI requires PHP 7.3 or higher. You are running PHP %s.', 'talkgenai'),
            PHP_VERSION
        );
    }
    
    // Check WordPress version
    if (version_compare(get_bloginfo('version'), '5.0', '<')) {
        $errors[] = sprintf(
            /* translators: %s: current WordPress version */
            __('TalkGenAI requires WordPress 5.0 or higher. You are running WordPress %s.', 'talkgenai'),
            get_bloginfo('version')
        );
    }
    
    // Check required PHP extensions
    $required_extensions = array('curl', 'json', 'openssl');
    foreach ($required_extensions as $extension) {
        if (!extension_loaded($extension)) {
            $errors[] = sprintf(
                /* translators: %s: missing PHP extension name */
                __('TalkGenAI requires the %s PHP extension.', 'talkgenai'),
                $extension
            );
        }
    }
    
    return $errors;
}

/**
 * Display requirements check
 */
function talkgenai_display_requirements_check() {
    $errors = talkgenai_check_requirements();
    
    if (!empty($errors)) {
        echo '<div class="notice notice-error"><p><strong>' . esc_html__('TalkGenAI Requirements Check Failed:', 'talkgenai') . '</strong></p><ul>';
        foreach ($errors as $error) {
            echo '<li>' . esc_html($error) . '</li>';
        }
        echo '</ul></div>';
        return false;
    }
    
    return true;
}


