<?php

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly....
}

function nele_export_data(): void
{
    global $table_prefix, $nele_countries_table, $nele_offices_table, $nele_places_table, $nele_streets_table, $wpdb;

    $tables = [$table_prefix . $nele_countries_table, $table_prefix . $nele_offices_table, $table_prefix . $nele_places_table, $table_prefix . $nele_streets_table];
    $data = [];

    foreach ($tables as $table) {
        $result = $wpdb->get_results("SELECT * FROM `$table`", ARRAY_A);
        if ($result !== null) { // Check if the result is not null
            $data[$table] = $result;
        } else {
            // Log the error if fetching fails
            error_log("Failed to fetch data from table: $table. Error: " . $wpdb->last_error);
        }
    }

    $logFile = 'data_debug.log';
    file_put_contents($logFile, print_r($data, true));

    if (empty($data)) {
        die("No data fetched from tables. Exiting.");
    }

    $jsonData = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

    if (json_last_error() !== JSON_ERROR_NONE) {
        echo "JSON encoding error: " . json_last_error_msg();
        die("Failed to encode data to JSON.");
    }

    $fileName =  __DIR__ . '/exported_data.json';
    if (file_put_contents($fileName, $jsonData) === false) {
        die("Failed to write data to $fileName.");
    }

    echo "Data exported successfully to $fileName.";
}

