<?php

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

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

    $fileName =  __DIR__ . '/exported_data.json';
    if (!file_exists($fileName)) {
        die("File not found: $fileName");
    }

    $jsonData = file_get_contents($fileName);
    $data = json_decode($jsonData, true);
    nele_db_drop_tables();
    nele_db_create_tables();

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

    foreach ($tables as $table) {
        if (isset($data[$table])) {
            foreach ($data[$table] as $row) {
                // Prepare columns and values for the insert statement
                $columns = implode(", ", array_keys($row));
                $values = implode(", ", array_map([$wpdb, 'prepare'], array_fill(0, count($row), '%s'), array_values($row)));

                // Construct and execute the insert query
                $insertQuery = "INSERT INTO `$table` ($columns) VALUES ($values)";
                $result = $wpdb->query($insertQuery);

                // Check for errors
                if ($result === false) {
                    error_log("Error importing data into $table: " . $wpdb->last_error);
                }
            }
        } else {
            error_log("No data found for table: $table");
        }
    }

    echo "Data imported successfully from $fileName.";
}

