<?php

/**
 * Plugin Name: WooCommerce Coupons Exporter
 * Plugin URI: https://codewp.ai
 * Author: CodeWP Assistant
 * Author URI: https://codewp.ai
 * Description: This plugin exports all WooCommerce coupons as a CSV and saves the file to the media library.
 */

function codewp_export_coupons_to_csv() {
    global $wpdb;

    $coupons = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}posts WHERE post_type = 'shop_coupon'");

    $csv_data = array();
    foreach ($coupons as $coupon) {
        $coupon_meta = get_post_meta($coupon->ID);
        $csv_data[] = array_merge(array('ID' => $coupon->ID, 'post_title' => $coupon->post_title), array_map(function($meta){ return $meta[0]; }, $coupon_meta));
    }

    $file = fopen('php://temp', 'r+');
    fputcsv($file, array_keys($csv_data[0]));
    foreach ($csv_data as $fields) {
        fputcsv($file, $fields);
    }

    rewind($file);
    $csv = stream_get_contents($file);
    fclose($file);

    $upload = wp_upload_bits('coupons.csv', null, $csv);

    if (!$upload['error']) {
        $wp_filetype = wp_check_filetype($upload['file'], null );
        $attachment = array(
            'post_mime_type' => $wp_filetype['type'],
            'post_title' => sanitize_file_name($upload['file']),
            'post_content' => '',
            'post_status' => 'inherit'
        );

        $attach_id = wp_insert_attachment($attachment, $upload['file']);
        require_once(ABSPATH . "wp-admin" . '/includes/image.php');
        $attach_data = wp_generate_attachment_metadata($attach_id, $upload['file']);
        wp_update_attachment_metadata($attach_id, $attach_data);
    }
}
add_action('wp_ajax_codewp_export_coupons_to_csv', 'codewp_export_coupons_to_csv');

add_action('admin_footer-edit.php', 'codewp_export_coupons_button');

function codewp_export_coupons_button() {
    global $post_type;

    if ($post_type == 'shop_coupon') {
        ?>
        <script type="text/javascript">
            jQuery(document).ready(function($) {
                $('#posts-filter').before('<button type="button" id="export-coupons" class="button button-primary">Export Coupons</button><span id="export-coupons-loading" style="display:none;">Loading...</span><span id="export-coupons-success" style="display:none;">Success!</span>');
                $('#export-coupons').click(function() {
                    $('#export-coupons-loading').show();
                    $.post(ajaxurl, { action: 'codewp_export_coupons_to_csv', nonce: '<?php echo wp_create_nonce('codewp_export_coupons_to_csv'); ?>' }, function(response) {
                        $('#export-coupons-loading').hide();
                        $('#export-coupons-success').show().delay(2000).fadeOut();
                    });
                });
            });
        </script>
        <?php
    }
}