<?php
/**
 * AI Auto Tool Utilities
 * Helper functions for image handling, sanitization, and text processing
 * 
 * @package AIAutoTool
 * @since 2.3.0
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Thoát nếu truy cập trực tiếp

if (!class_exists('AIAutoTool_Utilities')) {
    class AIAutoTool_Utilities {
        
        /**
         * Sanitize Vietnamese text to URL-friendly slug
         * 
         * @param string $title Title to sanitize
         * @return string Sanitized title
         */
        public static function sanitize_title($title) {
            $replacement = '-';
            $map = array();
            $quotedReplacement = preg_quote($replacement, '/');
            $default = array(
                '/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ|À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ|å/' => 'a',
                '/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ|È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ|ë/' => 'e',
                '/ì|í|ị|ỉ|ĩ|Ì|Í|Ị|Ỉ|Ĩ|î/' => 'i',
                '/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ|Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ|ø/' => 'o',
                '/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ|Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ|ů|û/' => 'u',
                '/ỳ|ý|ỵ|ỷ|ỹ|Ỳ|Ý|Ỵ|Ỷ|Ỹ/' => 'y',
                '/đ|Đ/' => 'd',
                '/ç/' => 'c',
                '/ñ/' => 'n',
                '/ä|æ/' => 'ae',
                '/ö/' => 'oe',
                '/ü/' => 'ue',
                '/Ä/' => 'Ae',
                '/Ü/' => 'Ue',
                '/Ö/' => 'Oe',
                '/ß/' => 'ss',
                '/[^\s\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]/mu' => ' ',
                '/\\s+/' => $replacement,
                sprintf('/^[%s]+|[%s]+$/', $quotedReplacement, $quotedReplacement) => '',
            );
            //Some URL was encode, decode first
            $title = urldecode($title);
            $map = array_merge($map, $default);
            return strtolower(preg_replace(array_keys($map), array_values($map), $title));
        }
        
        /**
         * URL encode string to lowercase with replacement
         * 
         * @param string $string String to encode
         * @return string Encoded string
         */
        public static function url_encode($string) {
            return strtolower(trim(preg_replace('~[^0-9a-z]+~i', '-', html_entity_decode(preg_replace('~&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', htmlentities($string, ENT_QUOTES, 'UTF-8')), ENT_QUOTES, 'UTF-8')), '-'));
        }
        
        /**
         * Extract all image URLs from HTML content
         * 
         * @param string $html HTML content
         * @return array Array of image URLs
         */
        public static function get_all_images($html) {
            $html = stripslashes($html);
            preg_match_all('/<img[^>]+src\s*=\s*["\']([^"\']+)["\']/i', $html, $matches);
            return $matches[1];
        }
        
        /**
         * Download and save image from URL to WordPress media library
         * 
         * @param string $imgURL Image URL to download
         * @param string $post_title Post title for naming
         * @return array|null Image data or null on failure
         */
        public static function save_image($imgURL, $post_title) {
            $imgURL = esc_url_raw($imgURL);
            if (empty($imgURL)) {
                return null;
            }

            $path = parse_url($imgURL, PHP_URL_PATH);
            $image_name = $path ? basename($path) : 'ai-generated-image.jpg';
            $filetype = wp_check_filetype($image_name);
            $upload_dir = wp_upload_dir();
            
            $extension = $filetype['ext'] ? $filetype['ext'] : "jpg";
            if (empty($extension)) $extension = "jpg";
            $unique_file_name = self::sanitize_title($post_title) . "-" . uniqid() . "." . $extension;
            $filename = $upload_dir['path'] . '/' . $unique_file_name;
            $baseurl = $upload_dir['baseurl'] . $upload_dir['subdir'] . '/' . $unique_file_name;
            
            $fp = fopen($filename, 'wb');
            if (!$fp) {
                return null;
            }

            $ch = curl_init($imgURL);
            if (!$ch) {
                fclose($fp);
                return null;
            }

            curl_setopt($ch, CURLOPT_FILE, $fp);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (WordPress; AI Auto Tool Image Downloader)');
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_exec($ch);
            $rescode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
            $curl_error = curl_error($ch);
            curl_close($ch);
            fclose($fp);
            
            if ($rescode == 200 && file_exists($filename) && filesize($filename) > 100) {
                if (!empty($content_type) && stripos($content_type, 'image/') !== false) {
                    $detected_extension = '';
                    if (stripos($content_type, 'png') !== false) {
                        $detected_extension = 'png';
                    } elseif (stripos($content_type, 'webp') !== false) {
                        $detected_extension = 'webp';
                    } elseif (stripos($content_type, 'jpeg') !== false || stripos($content_type, 'jpg') !== false) {
                        $detected_extension = 'jpg';
                    }

                    if ($detected_extension && $detected_extension !== $extension) {
                        $new_filename = preg_replace('/\.[^.]+$/', '.' . $detected_extension, $filename);
                        if ($new_filename && @rename($filename, $new_filename)) {
                            $filename = $new_filename;
                            $unique_file_name = basename($filename);
                            $baseurl = $upload_dir['baseurl'] . $upload_dir['subdir'] . '/' . $unique_file_name;
                        }
                    }
                }

                $wp_filetype = wp_check_filetype(basename($filename), null);
                if (empty($wp_filetype['type'])) {
                    $wp_filetype['type'] = 'image/jpeg';
                }
                
                $attachment = array(
                    'post_mime_type' => $wp_filetype['type'],
                    'post_title' => sanitize_file_name($post_title),
                    'post_content' => '',
                    'post_status' => 'inherit'
                );
                
                $attach_id = wp_insert_attachment($attachment, $filename);
                $imagenew = get_post($attach_id);
                $fullsizepath = get_attached_file($imagenew->ID);
                
                require_once(ABSPATH . 'wp-admin/includes/image.php');
                $attach_data = wp_generate_attachment_metadata($attach_id, $fullsizepath);
                wp_update_attachment_metadata($attach_id, $attach_data);
                
                $output['url'] = $imgURL;
                $output['file_name'] = $unique_file_name;
                $output['path'] = $filename;
                $output['baseurl'] = $baseurl;
                $output['attach_id'] = $attach_id;
                $output['url_out'] = $baseurl;
                return $output;
            } else {
                if (file_exists($filename)) {
                    @unlink($filename);
                }
                return null;
            }
        }
    }
}
