<?php

// File: /Applications/MAMP/htdocs/wordpress/wp-content/plugins/gpt3-ai-content-generator/classes/images/manager/ajax/ajax_delete_generated_image.php
// Status: NEW FILE

namespace WPAICG\Images\Manager\Ajax;

use WP_Error;

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

function ajax_delete_generated_image_logic(): void
{
    check_ajax_referer('aipkit_image_generator_nonce', '_ajax_nonce');
    if (!is_user_logged_in()) {
        wp_send_json_error(['message' => __('You must be logged in to delete media.', 'gpt3-ai-content-generator')], 403);
        return;
    }
    $attachment_id = isset($_POST['attachment_id']) ? absint($_POST['attachment_id']) : 0;
    if (empty($attachment_id)) {
        wp_send_json_error(['message' => __('Invalid media ID.', 'gpt3-ai-content-generator')], 400);
        return;
    }

    $post_author_id = get_post_field('post_author', $attachment_id);
    if (get_current_user_id() != $post_author_id) {
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('You do not have permission to delete this media.', 'gpt3-ai-content-generator')], 403);
            return;
        }
    }

    // Check if this is an AI-generated image or video
    $is_aipkit_image = get_post_meta($attachment_id, '_aipkit_generated_image', true);
    $is_aipkit_video = get_post_meta($attachment_id, '_aipkit_generated_video', true);
    
    if ($is_aipkit_image !== '1' && $is_aipkit_video !== '1') {
        wp_send_json_error(['message' => __('This media was not generated by AI Power.', 'gpt3-ai-content-generator')], 403);
        return;
    }

    $deleted = wp_delete_attachment($attachment_id, true);

    if ($deleted === false) {
        $media_type = ($is_aipkit_video === '1') ? __('video', 'gpt3-ai-content-generator') : __('image', 'gpt3-ai-content-generator');
        /* translators: %s: media type (image or video) */
        wp_send_json_error(['message' => sprintf(__('Failed to delete the %s from the media library.', 'gpt3-ai-content-generator'), $media_type)], 500);
    } else {
        $media_type = ($is_aipkit_video === '1') ? __('Video', 'gpt3-ai-content-generator') : __('Image', 'gpt3-ai-content-generator');
        /* translators: %s: media type (Image or Video) */
        wp_send_json_success(['message' => sprintf(__('%s deleted successfully.', 'gpt3-ai-content-generator'), $media_type)]);
    }
}
