<?php

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

class AIEO_Exchanger_Image_Resolver {

    const SRC_URL_META = '_aieo_exchanger_src_url';

    
    public static function resolve($src, $owner_id = 0, $meta_hint = '') {
        $src = (string) $src;
        if ($src === '' || !preg_match('#^https?://#i', $src)) { return 0; }

        
        $existing = self::find_attachment_by_src($src);
        if ($existing > 0) { return $existing; }

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

        
        $tmp = download_url($src, 30);
        if (is_wp_error($tmp)) {
            return 0;
        }

        
        
        $name = basename(wp_parse_url($src, PHP_URL_PATH));
        if ($name === '' || strpos($name, '.') === false) {
            $name = 'aieo-exchanger-' . substr(sha1($src), 0, 12) . '.jpg';
        }
        $file = array('name' => $name, 'tmp_name' => $tmp);

        $aid = media_handle_sideload($file, 0);
        if (is_wp_error($aid)) {
            @wp_delete_file($tmp);
            return 0;
        }

        update_post_meta((int) $aid, self::SRC_URL_META, esc_url_raw($src));
        if ($meta_hint !== '') {
            $current_alt = (string) get_post_meta((int) $aid, '_wp_attachment_image_alt', true);
            if ($current_alt === '') {
                update_post_meta((int) $aid, '_wp_attachment_image_alt', $meta_hint);
            }
        }
        return (int) $aid;
    }

    
    public static function find_attachment_by_src($src) {
        global $wpdb;
        $aid = (int) $wpdb->get_var($wpdb->prepare(
            "SELECT post_id FROM {$wpdb->postmeta}
             WHERE meta_key = %s AND meta_value = %s LIMIT 1",
            self::SRC_URL_META, esc_url_raw((string) $src)
        ));
        return $aid > 0 ? $aid : 0;
    }
}
