<?php
/**
 * EONSR AEO Agent - Helper Functions & Utilities
 *
 * Includes post caching, metadata extraction, CSS scoping,
 * and image processing (GD Library).
 *
 * @package EONSR_AEO_Agent
 */

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

// Updated Constant Name
define('EONSR_AEO_AGENT_POSTS_TRANSIENT_KEY', 'eonsr_aeo_agent_all_posts_list');

/* ==========================================================================
   SECTION 1: POST CACHING & RETRIEVAL
   ========================================================================== */

/**
 * Lấy danh sách bài viết đã publish, có cache (Transient).
 * Dữ liệu được nhóm theo ngôn ngữ (nếu dùng Polylang) hoặc heuristic.
 *
 * @return array Mảng bài viết được nhóm theo language slug.
 */
function eonsr_aeo_agent_get_posts_for_linking_data()
{
    // 1. Check Cache
    $cached_posts = get_transient(EONSR_AEO_AGENT_POSTS_TRANSIENT_KEY);
    if (false !== $cached_posts) {
        return $cached_posts;
    }

    // 2. Query Database
    $all_posts_query = new WP_Query([
        'post_type'      => 'post',
        'post_status'    => 'publish',
        'posts_per_page' => -1,
    ]);

    $posts_by_lang = [];

    if ($all_posts_query->have_posts()) {
        while ($all_posts_query->have_posts()) {
            $all_posts_query->the_post();
            
            $post_id = get_the_ID();
            $title   = get_the_title();
            $url     = get_permalink($post_id);
            
            $post_data = [
                'title' => $title,
                'url'   => $url
            ];

            // 3. Group by Language
            if (function_exists('pll_get_post_language')) {
                // Polylang Support
                $lang_slug = pll_get_post_language($post_id, 'slug');

                if ($lang_slug) {
                    if (!isset($posts_by_lang[$lang_slug])) {
                        $posts_by_lang[$lang_slug] = [];
                    }
                    $posts_by_lang[$lang_slug][] = $post_data;
                }
            } else {
                // Heuristic Fallback (Detect Vietnamese characters)
                if (!isset($posts_by_lang['vi'])) $posts_by_lang['vi'] = [];
                if (!isset($posts_by_lang['en'])) $posts_by_lang['en'] = [];

                if (preg_match('/[àáạảãâầấậẩẫăằắặẳẵèéẹẻẽêềếệểễìíịỉĩòóọỏõôồốộổỗơờớợởỡùúụủũưừứựửữỳýỵỷỹđ]/iu', $title)) {
                    $posts_by_lang['vi'][] = $post_data;
                } else {
                    $posts_by_lang['en'][] = $post_data;
                }
            }
        }
    }
    wp_reset_postdata();

    // 4. Save Cache (12 Hours)
    set_transient(EONSR_AEO_AGENT_POSTS_TRANSIENT_KEY, $posts_by_lang, 12 * HOUR_IN_SECONDS);

    return $posts_by_lang;
}

/**
 * Xóa cache bài viết khi có thay đổi (Save, Delete, Trash).
 */
function eonsr_aeo_agent_invalidate_posts_cache()
{
    delete_transient(EONSR_AEO_AGENT_POSTS_TRANSIENT_KEY);
}

// Hook into post lifecycle events
add_action('save_post', 'eonsr_aeo_agent_invalidate_posts_cache');
add_action('delete_post', 'eonsr_aeo_agent_invalidate_posts_cache');
add_action('wp_untrash_post', 'eonsr_aeo_agent_invalidate_posts_cache');
add_action('trashed_post', 'eonsr_aeo_agent_invalidate_posts_cache');

/* ==========================================================================
   SECTION 2: CONTENT PROCESSING
   ========================================================================== */

/**
 * Trích xuất metadata từ HTML comment (nếu có).
 *
 * @param string $html Nội dung HTML chứa comment metadata.
 * @return array Mảng metadata (slug, desc, tags, prompts).
 */
function eonsr_aeo_agent_extract_metadata_from_comment($html)
{
    $metadata = [
        'slug'                    => '',
        'meta_description'        => '',
        'tags'                    => [],
        'featured_image_prompt'   => '',
        'in_content_image_prompt' => ''
    ];

    // Find first HTML comment block
    if (!preg_match('/<!--(.*?)-->/s', $html, $matches)) {
        return $metadata;
    }
    
    $comment_content = $matches[1];

    // Parse Key-Value pairs
    if (preg_match('/meta description:\s*([^\r\n]+)/', $comment_content, $desc_matches)) {
        $metadata['meta_description'] = trim($desc_matches[1]);
    }
    if (preg_match('/slug:\s*([^\r\n]+)/', $comment_content, $slug_matches)) {
        $metadata['slug'] = trim($slug_matches[1]);
    }
    if (preg_match('/tags:\s*([^\r\n]+)/', $comment_content, $tags_matches)) {
        $tags_str = trim($tags_matches[1]);
        if (!empty($tags_str)) {
            $metadata['tags'] = array_filter(array_map('trim', explode(',', $tags_str)));
        }
    }
    if (preg_match('/featured_image_prompt:\s*([^\r\n]+)/', $comment_content, $fip_matches)) {
        $metadata['featured_image_prompt'] = trim($fip_matches[1]);
    }
    if (preg_match('/in_content_image_prompt:\s*([^\r\n]+)/', $comment_content, $icip_matches)) {
        $metadata['in_content_image_prompt'] = trim($icip_matches[1]);
    }

    return $metadata;
}

/**
 * Scope CSS selector để tránh conflict style toàn trang.
 *
 * @param string $css Chuỗi CSS gốc.
 * @param string $scope_selector Selector cha (VD: #my-container).
 * @return string CSS đã được scope.
 */
function eonsr_aeo_agent_scope_css($css, $scope_selector)
{
    // 1. Replace root & body
    $css = str_replace(':root', $scope_selector, $css);
    $css = preg_replace('/\bbody\b/', $scope_selector, $css);

    // 2. Prefix other selectors
    $final_css = preg_replace_callback(
        '/([^{]+)({[^}]+})/s',
        function ($matches) use ($scope_selector) {
            $selectors  = trim($matches[1]);
            $properties = $matches[2];

            // Skip @media and already scoped selectors
            if (strpos($selectors, '@media') !== false || strpos($selectors, $scope_selector) !== false) {
                return $selectors . $properties;
            }

            $scoped_selectors = array_map(function ($selector) use ($scope_selector) {
                return $scope_selector . ' ' . trim($selector);
            }, explode(',', $selectors));

            return implode(', ', $scoped_selectors) . $properties;
        },
        $css
    );

    return $final_css;
}

/**
 * Chuyển đổi Markdown đơn giản sang HTML (Bold).
 */
function eonsr_aeo_agent_simple_markdown_to_html($text)
{
    // Convert **bold** to <strong>bold</strong>
    return preg_replace('/\*\*(.*?)\*\*/s', '<strong>$1</strong>', $text);
}

/* ==========================================================================
   SECTION 3: WORDPRESS FILTERS (KSES ALLOWED HTML)
   ========================================================================== */

/**
 * Mở rộng danh sách thẻ HTML được phép (KSES).
 * Cho phép: style, iframe, script, figure, img với các thuộc tính cần thiết.
 *
 * @param array  $allowed_tags Danh sách thẻ hiện tại.
 * @param string $context Context (post, user, etc.).
 * @return array Danh sách thẻ đã cập nhật.
 */
function eonsr_aeo_agent_allow_style_tags($allowed_tags, $context)
{
    if ($context === 'post') {
        // 1. Style
        $allowed_tags['style'] = [
            'type' => true,
        ];

        // 2. Iframe (YouTube)
        $allowed_tags['iframe'] = [
            'src'             => true,
            'height'          => true,
            'width'           => true,
            'frameborder'     => true,
            'allowfullscreen' => true,
            'title'           => true,
            'allow'           => true,
            'loading'         => true,
            'id'              => true,
            'class'           => true,
            'name'            => true,
            'style'           => true
        ];

        // 3. Script (Video seeking)
        $allowed_tags['script'] = [
            'src'   => true,
            'type'  => true,
            'async' => true,
            'defer' => true,
        ];

        // 4. Figure & Figcaption
        $allowed_tags['figure'] = [
            'id'    => true,
            'class' => true,
            'style' => true
        ];
        $allowed_tags['figcaption'] = [];

        // 5. Image Attributes
        $img_attributes = [
            'src'     => true,
            'alt'     => true,
            'class'   => true,
            'width'   => true,
            'height'  => true,
            'srcset'  => true,
            'sizes'   => true,
            'style'   => true,
            'loading' => true,
            'id'      => true
        ];

        if (isset($allowed_tags['img'])) {
            $allowed_tags['img'] = array_merge($allowed_tags['img'], $img_attributes);
        } else {
            $allowed_tags['img'] = $img_attributes;
        }
    }
    return $allowed_tags;
}
add_filter('wp_kses_allowed_html', 'eonsr_aeo_agent_allow_style_tags', 10, 2);

/* ==========================================================================
   SECTION 4: IMAGE PROCESSING (GD LIBRARY)
   ========================================================================== */

/**
 * Lưu ảnh Base64 vào WordPress Media Library.
 *
 * @param string $base64_img Chuỗi ảnh Base64.
 * @param string $title Tiêu đề ảnh (dùng làm filename).
 * @return int|null ID của attachment hoặc null nếu lỗi.
 */
function eonsr_aeo_agent_save_base64_image_to_media($base64_img, $title)
{
    if (empty($base64_img)) {
        return null;
    }

    require_once(ABSPATH . 'wp-admin/includes/image.php');
    require_once(ABSPATH . 'wp-admin/includes/file.php');
    require_once(ABSPATH . 'wp-admin/includes/media.php');

    // Decode & Upload
    $image_data = base64_decode($base64_img);
    $filename   = sanitize_title($title) . '.png';
    $upload     = wp_upload_bits($filename, null, $image_data);

    if (!empty($upload['error'])) {
        return null;
    }

    // Insert Attachment
    $file_path = $upload['file'];
    $file_name = basename($file_path);
    $file_type = wp_check_filetype($file_name, null);

    $attachment_data = [
        'post_mime_type' => $file_type['type'],
        'post_title'     => sanitize_text_field($title),
        'post_content'   => '',
        'post_status'    => 'inherit'
    ];

    $attach_id = wp_insert_attachment($attachment_data, $file_path);
    
    // Generate Metadata
    $attach_metadata = wp_generate_attachment_metadata($attach_id, $file_path);
    wp_update_attachment_metadata($attach_id, $attach_metadata);

    return $attach_id;
}

/**
 * Thêm Logo và Text Watermark vào ảnh Base64.
 * Hỗ trợ Custom Logo từ user option.
 *
 * @param string $base64_img Chuỗi ảnh gốc Base64.
 * @param string $default_logo_path Đường dẫn logo mặc định.
 * @param string $language Ngôn ngữ để hiển thị text watermark.
 * @return string Ảnh Base64 đã xử lý.
 */
function eonsr_aeo_agent_add_logo_to_image_base64($base64_img, $default_logo_path, $language = 'Vietnamese')
{
    // Override language for global consistency (if needed)
    // $language = 'English'; 

    // 1. Check GD Requirement
    if (!extension_loaded('gd') || !function_exists('imagecreatefromstring')) {
        return $base64_img;
    }

    // 2. Decode Image
    $image_data = base64_decode($base64_img);
    if ($image_data === false) return $base64_img;

    $main_image = @imagecreatefromstring($image_data);
    if (!$main_image) return $base64_img;

    $main_width  = imagesx($main_image);
    $main_height = imagesy($main_image);
    $padding     = 20;

    // --- PART A: ADD LOGO ---
    // Updated Option Name
    $use_logo = get_option('eonsr_aeo_agent_use_custom_logo', false);
    
    if ($use_logo) {
        $user_logo_path  = get_option('eonsr_aeo_agent_custom_logo_path');
        $final_logo_path = ($user_logo_path && file_exists($user_logo_path)) ? $user_logo_path : $default_logo_path;

        if (file_exists($final_logo_path)) {
            $logo_image = @imagecreatefrompng($final_logo_path);
            
            if ($logo_image) {
                // Resize logic (4% width)
                $target_width_ratio   = 0.04;
                $original_logo_width  = imagesx($logo_image);
                $original_logo_height = imagesy($logo_image);
                
                $new_logo_width  = $main_width * $target_width_ratio;
                $new_logo_height = ($original_logo_height / $original_logo_width) * $new_logo_width;

                // Create Transparent Container
                $resized_logo = imagecreatetruecolor($new_logo_width, $new_logo_height);
                imagealphablending($resized_logo, false);
                imagesavealpha($resized_logo, true);
                
                $transparent = imagecolorallocatealpha($resized_logo, 255, 255, 255, 127);
                imagefilledrectangle($resized_logo, 0, 0, $new_logo_width, $new_logo_height, $transparent);

                // Resample & Merge
                imagecopyresampled($resized_logo, $logo_image, 0, 0, 0, 0, $new_logo_width, $new_logo_height, $original_logo_width, $original_logo_height);
                
                // Position: Bottom Left
                imagecopy($main_image, $resized_logo, $padding, $main_height - $new_logo_height - $padding, 0, 0, $new_logo_width, $new_logo_height);
                
                imagedestroy($logo_image);
                imagedestroy($resized_logo);
            }
        }
    }

    // --- PART B: ADD TEXT WATERMARK ---
    
    $translations = [
        'Vietnamese' => 'Ảnh được tạo ra bởi AI',
        'English'    => 'Image created by AI',
        'French'     => 'Image créée par IA',
        'German'     => 'Bild von KI erstellt',
        'Japanese'   => 'AIによって作成された画像',
        'Korean'     => 'AI로 생성된 이미지',
        'Chinese'    => '由人工智能生成的图片',
        'Russian'    => 'Изображение создано ИИ',
        'Spanish'    => 'Imagen creada por IA',
        'Italian'    => 'Immagine creata da AI',
        'Thai'       => 'ภาพที่สร้างโดย AI',
        'Indonesian' => 'Gambar dibuat oleh AI',
        'Portuguese' => 'Imagem criada por IA',
        'Hindi'      => 'AI द्वारा बनाई गई छवि',
        'Arabic'     => 'صورة تم إنشاؤها بواسطة الذكاء الاصطناعي',
        'Turkish'    => 'Yapay zeka tarafından oluşturuldu',
        'Dutch'      => 'Afbeelding gemaakt door AI',
        'Swedish'    => 'Bild skapad av AI',
        'Norwegian'  => 'Bilde laget av AI',
        'Danish'     => 'Billede skabt af AI',
        'Finnish'    => 'Tekoälyn luoma kuva',
        'Polish'     => 'Obraz stworzony przez AI',
        'Ukrainian'  => 'Зображення створено ШІ',
        'Hebrew'     => 'תמונה נוצרה על ידי AI'
    ];

    $watermark_text = isset($translations[$language]) ? $translations[$language] : 'Image created by AI';

    // Colors (Semi-transparent)
    $white_transparent        = imagecolorallocatealpha($main_image, 255, 255, 255, 50);
    $black_shadow_transparent = imagecolorallocatealpha($main_image, 0, 0, 0, 100);

    // Font Config (Updated Path Constant)
    $font_path = EONSR_AEO_AGENT_PATH . 'fonts/tahoma-italic.ttf';

    if (file_exists($font_path)) {
        // TrueType Font
        $font_size  = max(5, $main_width * 0.01);
        $bbox       = imagettfbbox($font_size, 0, $font_path, $watermark_text);
        $text_width = abs($bbox[4] - $bbox[0]);

        $x_text = $main_width - $text_width - $padding;
        $y_text = $main_height - $padding;

        // Draw Shadow then Text
        imagettftext($main_image, $font_size, 0, $x_text + 2, $y_text + 2, $black_shadow_transparent, $font_path, $watermark_text);
        imagettftext($main_image, $font_size, 0, $x_text, $y_text, $white_transparent, $font_path, $watermark_text);
    } else {
        // Fallback (Built-in Font)
        $watermark_text_fallback = 'Image created by AI';
        $font_builtin = 2.5; // Closest to small size
        
        $char_width  = imagefontwidth($font_builtin);
        $char_height = imagefontheight($font_builtin);
        $text_width  = strlen($watermark_text_fallback) * $char_width;

        $x_text = $main_width - $text_width - $padding;
        $y_text = $main_height - $char_height - $padding;

        // Draw Shadow then Text
        imagestring($main_image, $font_builtin, $x_text + 1, $y_text + 1, $watermark_text_fallback, $black_shadow_transparent);
        imagestring($main_image, $font_builtin, $x_text, $y_text, $watermark_text_fallback, $white_transparent);
    }

    // 3. Export Image
    ob_start();
    imagepng($main_image);
    $final_image_data = ob_get_clean();
    imagedestroy($main_image);

    return base64_encode($final_image_data);
}