<?php
// IV1 WP Tools – Bilder AJAX & Funktionen
defined("ABSPATH") || exit;

// AJAX: Bilder – IDs aller Medien-Attachments holen
// ────────────────────────────────────────────────
add_action('wp_ajax_iv1wpt_images_get_ids', 'iv1wpt_images_get_ids_ajax');
function iv1wpt_images_get_ids_ajax(): void {
    check_ajax_referer('iv1wpt_ajax', '_ajax_nonce');
    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

    global $wpdb;
    $ids = $wpdb->get_col(
        "SELECT ID FROM {$wpdb->posts} WHERE post_type = 'attachment' AND post_mime_type LIKE 'image/%' ORDER BY ID ASC"
    );

    wp_send_json_success(['ids' => array_map('intval', $ids)]);
}

// ────────────────────────────────────────────────
// AJAX: Bilder – Batch scannen
// ────────────────────────────────────────────────
add_action('wp_ajax_iv1wpt_images_scan_batch', 'iv1wpt_images_scan_batch_ajax');
function iv1wpt_images_scan_batch_ajax(): void {
    check_ajax_referer('iv1wpt_ajax', '_ajax_nonce');
    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

    $ids = array_map('intval', explode(',', sanitize_text_field($_POST['ids'] ?? '')));
    $ids = array_filter($ids);
    if (empty($ids)) {
        wp_send_json_success(['results' => []]);
    }

    global $wpdb;

    // Verwendungs-Daten einmalig laden (gecacht für den Batch)
    static $usage_cache = null;
    if ($usage_cache === null) {
        $usage_cache = iv1wpt_build_image_usage_index();
    }

    $results = [];
    foreach ($ids as $id) {
        $attachment = get_post($id);
        if (!$attachment) continue;

        $file = get_attached_file($id);
        $filename = $file ? basename($file) : ($attachment->post_title ?: __('unknown', 'iv1-wp-tools'));
        $filesize = $file && file_exists($file) ? filesize($file) : 0;

        // Alle Thumbnail-Größen addieren
        $meta = wp_get_attachment_metadata($id);
        if (!empty($meta['sizes']) && $file) {
            $dir = dirname($file) . '/';
            foreach ($meta['sizes'] as $size_info) {
                $thumb_file = $dir . $size_info['file'];
                if (file_exists($thumb_file)) {
                    $filesize += filesize($thumb_file);
                }
            }
        }

        $dimensions = '';
        if (!empty($meta['width']) && !empty($meta['height'])) {
            $dimensions = $meta['width'] . '×' . $meta['height'];
        }

        // Thumbnail-URL für Vorschau
        $thumb_url = wp_get_attachment_image_url($id, 'thumbnail');

        // Verwendung prüfen
        $used = false;
        $used_in = '';

        if (isset($usage_cache[$id])) {
            $used = true;
            $used_in = $usage_cache[$id];
        }

        $results[] = [
            'id'         => $id,
            'filename'   => $filename,
            'mime'       => $attachment->post_mime_type,
            'filesize'   => $filesize,
            'dimensions' => $dimensions,
            'thumb'      => $thumb_url ?: '',
            'used'       => $used,
            'used_in'    => $used_in,
        ];
    }

    wp_send_json_success(['results' => $results]);
}

// ────────────────────────────────────────────────
// Bilder-Verwendungs-Index aufbauen
// ────────────────────────────────────────────────
function iv1wpt_build_image_usage_index(): array {
    global $wpdb;
    $usage = [];

    // 1. Beitragsbilder (Featured Images / Thumbnails)
    $thumbs = $wpdb->get_results(
        "SELECT meta_value AS img_id, post_id FROM {$wpdb->postmeta} WHERE meta_key = '_thumbnail_id' AND meta_value != ''",
        ARRAY_A
    );
    foreach ($thumbs as $row) {
        $img_id = (int) $row['img_id'];
        if ($img_id > 0) {
            $usage[$img_id] = 'Beitragsbild (Post #' . $row['post_id'] . ')';
        }
    }

    // 2. Bilder im Post-Content (suche nach wp-image-ID und attachment URLs)
    $upload_dir = wp_get_upload_dir();
    $upload_baseurl = $upload_dir['baseurl'];

    // Alle Attachment-URLs sammeln
    $attachments = $wpdb->get_results(
        "SELECT ID, guid FROM {$wpdb->posts} WHERE post_type = 'attachment' AND post_mime_type LIKE 'image/%'",
        ARRAY_A
    );
    $url_to_id = [];
    foreach ($attachments as $att) {
        $url = $att['guid'];
        $url_to_id[$url] = (int) $att['ID'];
        // Auch ohne Domain
        $path = wp_parse_url($url, PHP_URL_PATH);
        if ($path) {
            $url_to_id[$path] = (int) $att['ID'];
        }
    }

    // Post-Content scannen
    $posts = $wpdb->get_results(
        "SELECT ID, post_content, post_title FROM {$wpdb->posts} WHERE post_status != 'trash' AND post_content != '' AND post_type NOT IN ('revision', 'attachment')",
        ARRAY_A
    );
    foreach ($posts as $post) {
        $content = $post['post_content'];

        // wp-image-{ID} Klasse
        if (preg_match_all('/wp-image-(\d+)/', $content, $matches)) {
            foreach ($matches[1] as $img_id) {
                $img_id = (int) $img_id;
                if ($img_id > 0 && !isset($usage[$img_id])) {
                    $usage[$img_id] = 'Inhalt: ' . mb_substr($post['post_title'], 0, 40);
                }
            }
        }

        // URL-basierte Erkennung
        foreach ($url_to_id as $url => $img_id) {
            if (strpos($content, $url) !== false && !isset($usage[$img_id])) {
                $usage[$img_id] = 'Inhalt: ' . mb_substr($post['post_title'], 0, 40);
            }
        }
    }

    // 3. Custom Fields / ACF (postmeta mit Attachment-IDs oder URLs)
    $meta_rows = $wpdb->get_results(
        "SELECT post_id, meta_key, meta_value FROM {$wpdb->postmeta}
         WHERE meta_key NOT LIKE '\_%'
         AND meta_value REGEXP '^[0-9]+$'
         AND CAST(meta_value AS UNSIGNED) > 0",
        ARRAY_A
    );
    foreach ($meta_rows as $row) {
        $img_id = (int) $row['meta_value'];
        if ($img_id > 0 && !isset($usage[$img_id])) {
            // Prüfen ob diese ID wirklich ein Bild-Attachment ist
            if (get_post_type($img_id) === 'attachment') {
                $usage[$img_id] = 'Custom Field: ' . $row['meta_key'] . ' (Post #' . $row['post_id'] . ')';
            }
        }
    }

    // ACF Gallery/Repeater (serialisierte Daten)
    $serialized_meta = $wpdb->get_results(
        "SELECT post_id, meta_key, meta_value FROM {$wpdb->postmeta}
         WHERE meta_value LIKE '%\"%" . intval($wpdb->prefix ? 1 : 0) . "%\"%'
         AND meta_value LIKE 'a:%'",
        ARRAY_A
    );
    // Einfachere Methode: schaue in serialisierten Arrays nach Attachment-IDs
    foreach ($serialized_meta as $row) {
        $data = @unserialize($row['meta_value']);
        if (is_array($data)) {
            array_walk_recursive($data, function ($val) use (&$usage, $row) {
                if (is_numeric($val) && (int) $val > 0) {
                    $val = (int) $val;
                    if (!isset($usage[$val]) && get_post_type($val) === 'attachment') {
                        $usage[$val] = 'ACF: ' . $row['meta_key'] . ' (Post #' . $row['post_id'] . ')';
                    }
                }
            });
        }
    }

    // 4. WooCommerce Produktbilder (Gallery)
    $wc_gallery = $wpdb->get_results(
        "SELECT post_id, meta_value FROM {$wpdb->postmeta} WHERE meta_key = '_product_image_gallery' AND meta_value != ''",
        ARRAY_A
    );
    foreach ($wc_gallery as $row) {
        $gallery_ids = explode(',', $row['meta_value']);
        foreach ($gallery_ids as $gid) {
            $gid = (int) trim($gid);
            if ($gid > 0 && !isset($usage[$gid])) {
                $usage[$gid] = 'WooCommerce Galerie (Produkt #' . $row['post_id'] . ')';
            }
        }
    }

    // 5. Elementor (JSON in postmeta _elementor_data)
    $elementor_rows = $wpdb->get_results(
        "SELECT post_id, meta_value FROM {$wpdb->postmeta} WHERE meta_key = '_elementor_data' AND meta_value != '' AND meta_value != '[]'",
        ARRAY_A
    );
    foreach ($elementor_rows as $row) {
        // Suche nach "id" und "url" Referenzen zu Attachments
        $data = $row['meta_value'];
        // wp-content/uploads Pfade
        foreach ($url_to_id as $url => $img_id) {
            if (strpos($data, $url) !== false && !isset($usage[$img_id])) {
                $usage[$img_id] = 'Elementor (Post #' . $row['post_id'] . ')';
            }
        }
        // Direkte ID-Referenzen: "id":"123" oder "id":123
        if (preg_match_all('/"id"\s*:\s*"?(\d+)"?/', $data, $matches)) {
            foreach ($matches[1] as $img_id) {
                $img_id = (int) $img_id;
                if ($img_id > 0 && !isset($usage[$img_id]) && get_post_type($img_id) === 'attachment') {
                    $usage[$img_id] = 'Elementor (Post #' . $row['post_id'] . ')';
                }
            }
        }
    }

    // 6. Widget-Inhalte (options Tabelle)
    $widget_content = get_option('widget_text', []);
    if (is_array($widget_content)) {
        foreach ($widget_content as $widget) {
            if (is_array($widget) && !empty($widget['text'])) {
                foreach ($url_to_id as $url => $img_id) {
                    if (strpos($widget['text'], $url) !== false && !isset($usage[$img_id])) {
                        $usage[$img_id] = 'Widget';
                    }
                }
            }
        }
    }

    // 7. Site Icon / Logo
    $site_icon = (int) get_option('site_icon');
    if ($site_icon > 0) {
        $usage[$site_icon] = 'Site Icon';
    }
    $custom_logo = (int) get_theme_mod('custom_logo');
    if ($custom_logo > 0) {
        $usage[$custom_logo] = 'Site Logo';
    }

    return $usage;
}

// ────────────────────────────────────────────────
// AJAX: Einzelnes Bild löschen
// ────────────────────────────────────────────────
add_action('wp_ajax_iv1wpt_images_delete', 'iv1wpt_images_delete_ajax');
function iv1wpt_images_delete_ajax(): void {
    check_ajax_referer('iv1wpt_ajax', '_ajax_nonce');
    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

    // Pro-Check: Bild-Löschen ist ein Pro-Feature
    if (!iv1wpt_has_pro()) {
        wp_send_json_error(__('Deleting images requires IV1 WP Tools Pro with a valid license.', 'iv1-wp-tools'));
    }

    $id = absint($_POST['image_id'] ?? 0);
    if ($id === 0) {
        wp_send_json_error('Ungültige Bild-ID.');
    }

    // Attachment komplett löschen inkl. aller Dateien
    $result = wp_delete_attachment($id, true);
    if ($result) {
		iv1wpt_plugin_log(
			sprintf(
				/* translators: %d: attachment/image ID */
				__('IV1WPT: Image deleted → ID %d', 'iv1-wp-tools'),
				$id
			)
		);		
        /* translators: %d: image ID */
        wp_send_json_success(sprintf(__('Image #%d deleted.', 'iv1-wp-tools'), $id));
    } else {
        /* translators: %d: image ID */
        wp_send_json_error(sprintf(__('Delete failed for image #%d.', 'iv1-wp-tools'), $id));
    }
}
