<?php
if (!defined('ABSPATH')) exit;

class AIIO_Etch {

    public static function init() {
        add_filter('admin_body_class', [__CLASS__, 'admin_body_class']);
    }

    public static function is_active() {
        if (defined('ETCH_VERSION') || defined('ETCH_PLUGIN_FILE')) {
            return true;
        }
        if (!function_exists('is_plugin_active')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }
        foreach (['etch/etch.php', 'etch-wp/etch.php', 'etch-for-wordpress/etch.php'] as $slug) {
            if (is_plugin_active($slug)) {
                return true;
            }
        }
        return (bool) apply_filters('aiio_etch_is_active', false);
    }

    public static function version() {
        if (!self::is_active()) {
            return '';
        }
        if (!function_exists('get_plugin_data')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }
        foreach (['etch/etch.php', 'etch-wp/etch.php'] as $slug) {
            $file = WP_PLUGIN_DIR . '/' . $slug;
            if (file_exists($file)) {
                $data = get_plugin_data($file, false, false);
                return $data['Version'] ?? '';
            }
        }
        return defined('ETCH_VERSION') ? ETCH_VERSION : '';
    }

    public static function use_native_admin_ui() {
        if (!self::is_active()) {
            return false;
        }
        $s = aiio_get_settings();
        return !isset($s['etch_native_ui']) || !empty($s['etch_native_ui']);
    }

    public static function admin_body_class($classes) {
        if (!self::use_native_admin_ui() || !is_admin()) {
            return $classes;
        }
        $screen = function_exists('get_current_screen') ? get_current_screen() : null;
        if ($screen && strpos($screen->id ?? '', 'pewit-ai-image-optimizer') !== false) {
            $classes .= ' aiio-etch-ui';
        }
        return $classes;
    }

    public static function status_line() {
        if (!self::is_active()) {
            return __('EtchWP not detected', 'pewit-ai-image-optimizer');
        }
        $ver = self::version();
        return $ver
            ? sprintf(/* translators: %s are replaced with dynamic values */ __('EtchWP %s — optimize images used in Etch Media props', 'pewit-ai-image-optimizer'), $ver)
            : __('EtchWP detected — scans Etch-referenced images', 'pewit-ai-image-optimizer');
    }

    public static function get_used_attachment_ids() {
        $map = self::build_usage_map();
        return array_map('intval', array_keys($map));
    }

    public static function build_usage_map() {
        $map = [];
        $posts = get_posts([
            'post_type'      => 'any',
            'post_status'    => ['publish', 'draft', 'private'],
            'posts_per_page' => -1,
            'fields'         => 'ids',
        ]);
        foreach ($posts as $post_id) {
            $thumb = get_post_thumbnail_id($post_id);
            if ($thumb) {
                self::add_usage($map, $thumb, $post_id, 'featured_image');
            }
            $content = (string) get_post_field('post_content', $post_id);
            foreach (self::ids_from_text($content) as $id) {
                self::add_usage($map, $id, $post_id, 'content');
            }
            foreach (get_post_meta($post_id) as $key => $values) {
                $source = self::source_from_meta_key($key);
                if ($source === 'post_meta') {
                    continue;
                }
                foreach ((array) $values as $v) {
                    $raw = is_serialized($v) ? maybe_unserialize($v) : $v;
                    foreach (self::ids_from_mixed($raw) as $id) {
                        self::add_usage($map, $id, $post_id, $source);
                    }
                }
            }
        }
        return $map;
    }

    private static function add_usage(&$map, $attachment_id, $post_id, $source) {
        $attachment_id = (int) $attachment_id;
        if (!$attachment_id || get_post_type($attachment_id) !== 'attachment') {
            return;
        }
        if (!isset($map[$attachment_id])) {
            $map[$attachment_id] = [];
        }
        $map[$attachment_id][] = [
            'post_id'   => (int) $post_id,
            'source'    => $source,
            'title'     => get_the_title($post_id),
            'post_type' => get_post_type($post_id),
        ];
    }

    private static function source_from_meta_key($key) {
        $lower = strtolower((string) $key);
        if (strpos($lower, 'etch') !== false) {
            return 'etch_meta';
        }
        if (strpos($lower, 'bricks') !== false) {
            return 'bricks_meta';
        }
        if (strpos($lower, 'image') !== false || strpos($lower, 'media') !== false || strpos($lower, 'gallery') !== false) {
            return 'image_meta';
        }
        return 'post_meta';
    }

    public static function ids_from_text($text) {
        $ids = [];
        if (!$text || !is_string($text)) {
            return $ids;
        }
        if (preg_match_all('/wp-image-(\d+)/', $text, $m)) {
            $ids = array_merge($ids, array_map('intval', $m[1]));
        }
        if (preg_match_all('/"(?:id|imageId|mediaId|attachmentId|mediaProp)"\s*:\s*(\d+)/i', $text, $m)) {
            $ids = array_merge($ids, array_map('intval', $m[1]));
        }
        return array_values(array_unique(array_filter($ids)));
    }

    public static function ids_from_mixed($value) {
        if (is_numeric($value) && get_post_type((int) $value) === 'attachment') {
            return [(int) $value];
        }
        if (is_string($value)) {
            return self::ids_from_text($value);
        }
        if (is_array($value) || is_object($value)) {
            $ids = [];
            foreach ((array) $value as $v) {
                $ids = array_merge($ids, self::ids_from_mixed($v));
            }
            return $ids;
        }
        return [];
    }
}
