<?php
if (!current_user_can('manage_options')) {
    wp_die(__('Permission denied', 'gift-voucher'));
}

global $wpdb;
ob_clean();
// Table names
$table1 = $wpdb->prefix . 'giftvouchers_list';
$table2 = $wpdb->prefix . 'giftvouchers_activity';

// Retrieve all data from both tables
$data = array(
    'giftvouchers_list' => $wpdb->get_results("SELECT * FROM {$table1}", ARRAY_A),
    'giftvouchers_activity' => $wpdb->get_results("SELECT * FROM {$table2}", ARRAY_A)
);

// Check if data is empty
if (empty($data['giftvouchers_list']) && empty($data['giftvouchers_activity'])) {
    wp_die(__('No data to export.', 'gift-voucher'));
}

// Set headers for JSON file download
header('Content-Type: application/json; charset=utf-8');
header('Content-Disposition: attachment; filename="giftcard-database-' . date('Y-m-d-His') . '.json"');
header('Pragma: no-cache');
header('Expires: 0');

// Output JSON with escaped HTML tags to avoid breaking JSON structure
echo wp_json_encode($data, JSON_PRETTY_PRINT | JSON_HEX_TAG);
exit;
