<?php

namespace XHTheme\AIToolbox;

defined('ABSPATH') || exit;

class XH_AvatarLocal
{
    /**
     * 获取本地上传目录信息（封装 wp_upload_dir）
     */
    private static function get_local_upload_dir()
    {
        $upload_dir = wp_upload_dir();
        $site_url = site_url();
        $site_host = wp_parse_url($site_url, PHP_URL_HOST);

        $basedir = $upload_dir['basedir'];
        $baseurl = $upload_dir['baseurl'];

        $is_local_path = (
            strpos($basedir, ABSPATH) === 0 ||
            strpos($basedir, WP_CONTENT_DIR) === 0
        );

        $baseurl_host = wp_parse_url($baseurl, PHP_URL_HOST);
        $is_local_domain = ($baseurl_host === $site_host);

        if ($is_local_path && $is_local_domain) {
            return $upload_dir;
        }

        if (!$is_local_path) {
            $upload_dir['basedir'] = trailingslashit(WP_CONTENT_DIR) . 'uploads';
        }

        $relative_path = str_replace(trailingslashit(ABSPATH), '', trailingslashit($upload_dir['basedir']));
        $upload_dir['baseurl'] = trailingslashit($site_url) . rtrim($relative_path, '/');

        return $upload_dir;
    }

    /**
     * 下载远程图片并保存到本地
     * 
     * @param string $url 远程图片URL
     * @param string $filename 保存的文件名（不含扩展名）
     * @return string|false 成功返回本地URL，失败返回false
     */
    public static function download_avatar($url)
    {
        // 使用封装的本地上传目录
        $upload_dir = self::get_local_upload_dir();
        $avatar_dir = trailingslashit($upload_dir['basedir']) . 'avatars';

        // 确保avatars目录存在
        if (!file_exists($avatar_dir)) {
            wp_mkdir_p($avatar_dir);
        }

        // 从URL提取文件名
        $url_path = wp_parse_url($url, PHP_URL_PATH);
        $file_name = basename($url_path);
        if (empty($file_name)) {
            return false;
        }

        // 检查文件是否已存在
        $file_path = trailingslashit($avatar_dir) . $file_name;
        if (file_exists($file_path)) {
            return self::get_local_url($file_path, $upload_dir);
        }

        // 获取远程图片
        $response = wp_remote_get($url, ['timeout' => 5]);
        if (is_wp_error($response)) {
            return false;
        }

        // 获取内容类型并验证
        $content_type = wp_remote_retrieve_header($response, 'content-type');
        if (!self::is_valid_image_type($content_type)) {
            return false;
        }

        $image_data = wp_remote_retrieve_body($response);
        $result = file_put_contents($file_path, $image_data);

        return $result !== false ? self::get_local_url($file_path, $upload_dir) : false;
    }

    /**
     * 将本地文件路径转换为URL
     * 
     * @param string $file_path 文件绝对路径
     * @return string 本地URL
     */
    private static function get_local_url($file_path, $upload_dir = [])
    {
        if (empty($upload_dir)) {
            $upload_dir = self::get_local_upload_dir();
        }
        $base_dir = trailingslashit($upload_dir['basedir']);
        $base_url = trailingslashit($upload_dir['baseurl']);
        return str_replace($base_dir, $base_url, $file_path);
    }

    /**
     * 验证是否为有效的图片类型
     * 
     * @param string $mime_type MIME类型
     * @return bool 是否为有效图片
     */
    private static function is_valid_image_type($mime_type)
    {
        $valid_types = [
            'image/jpeg',
            'image/png',
            'image/gif',
            'image/webp',
            'image/svg+xml'
        ];
        return in_array($mime_type, $valid_types);
    }

    /**
     * 上传并处理头像图片
     */
    public static function upload_avatar($file)
    {
        if (empty($file) || empty($file['tmp_name'])) {
            return new \WP_Error('no_file', __('Please select a file to upload', 'xhtheme-ai-toolbox'));
        }

        $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        if (!in_array($file['type'], $allowed_types, true)) {
            return new \WP_Error('invalid_type', __('Please upload an image in JPG, PNG, GIF or WebP format', 'xhtheme-ai-toolbox'));
        }

        if ($file['size'] > 2 * 1024 * 1024) {
            return new \WP_Error('file_too_large', __('Image size cannot exceed 2MB', 'xhtheme-ai-toolbox'));
        }

        $upload_dir = self::get_local_upload_dir();
        $avatar_dir = trailingslashit($upload_dir['basedir']) . 'avatars';

        if (!file_exists($avatar_dir)) {
            wp_mkdir_p($avatar_dir);
        }

        // 生成唯一文件名（使用 uniqid 避免同秒内冲突）
        $unique_id = md5(uniqid((string) wp_rand(), true));
        $editor = wp_get_image_editor($file['tmp_name']);

        if (is_wp_error($editor)) {
            // 图片编辑器不可用，保留原始扩展名
            $ext = pathinfo($file['name'], PATHINFO_EXTENSION) ?: 'jpg';
            $filename = 'custom-' . $unique_id . '.' . $ext;
            if (!function_exists('wp_handle_sideload')) {
                require_once ABSPATH . 'wp-admin/includes/file.php';
            }

            $avatar_upload_dir = static function ($dirs) use ($upload_dir, $avatar_dir) {
                $dirs['path'] = $avatar_dir;
                $dirs['url'] = trailingslashit($upload_dir['baseurl']) . 'avatars';
                $dirs['subdir'] = '/avatars';
                return $dirs;
            };

            $avatar_file = $file;
            $avatar_file['name'] = $filename;

            add_filter('upload_dir', $avatar_upload_dir);
            $uploaded = wp_handle_sideload($avatar_file, [
                'test_form' => false,
                'mimes' => [
                    'jpg|jpeg' => 'image/jpeg',
                    'png' => 'image/png',
                    'gif' => 'image/gif',
                    'webp' => 'image/webp',
                ],
            ]);
            remove_filter('upload_dir', $avatar_upload_dir);

            if (!empty($uploaded['error']) || empty($uploaded['file'])) {
                return new \WP_Error('save_failed', __('Failed to save file, please check directory permissions', 'xhtheme-ai-toolbox'));
            }

            $target_path = $uploaded['file'];
        } else {
            // 统一保存为 jpg 格式以减小体积
            $filename = 'custom-' . $unique_id . '.jpg';
            $target_path = trailingslashit($avatar_dir) . $filename;
            $editor->resize(100, 100, true);
            $editor->set_quality(85);
            $saved = $editor->save($target_path, 'image/jpeg');

            if (is_wp_error($saved)) {
                return new \WP_Error('process_failed', __('Image processing failed', 'xhtheme-ai-toolbox') . ': ' . $saved->get_error_message());
            }
        }
        $avatar_url = self::get_local_url($target_path, $upload_dir);

        return ['url' => $avatar_url];
    }
}
