<?php
/**
 * unpack.php
 * Run once to extract index.php, config.php, and import.php
 * into the current directory.
 */

$files = [

'config.php' => <<<'PHP'
<?php
// config.php

$DB_HOST = 'localhost';
$DB_NAME = 'your_database';
$DB_USER = 'your_user';
$DB_PASS = 'your_password';

try {
    $pdo = new PDO(
        "mysql:host=$DB_HOST;dbname=$DB_NAME;charset=utf8mb4",
        $DB_USER,
        $DB_PASS,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]
    );
} catch (PDOException $e) {
    die('Database connection failed: ' . $e->getMessage());
}
PHP
,

'index.php' => <<<'PHP'
<?php
// index.php
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JSON → MySQL Importer</title>
<style>
body {
    font-family: Arial, sans-serif;
    background: #f4f6f8;
    padding: 40px;
}
.container {
    background: #fff;
    padding: 30px;
    max-width: 600px;
    margin: auto;
    border-radius: 6px;
}
h1 { margin-top: 0; }
input[type=file] {
    width: 100%;
    margin: 15px 0;
}
button {
    padding: 10px 20px;
    background: #0078d4;
    border: none;
    color: #fff;
    cursor: pointer;
}
.result {
    margin-top: 20px;
    background: #eef6ff;
    padding: 15px;
    border-radius: 4px;
}
</style>
</head>
<body>

<div class="container">
    <h1>Upload JSON Files</h1>

    <form id="uploadForm" enctype="multipart/form-data">
        <input type="file" name="json_files[]" accept=".json" multiple required>
        <button type="submit">Import</button>
    </form>

    <div id="result" class="result" style="display:none;"></div>
</div>

<script>
document.getElementById('uploadForm').addEventListener('submit', function(e) {
    e.preventDefault();

    const formData = new FormData(this);

    fetch('import.php', {
        method: 'POST',
        body: formData
    })
    .then(res => res.text())
    .then(data => {
        const result = document.getElementById('result');
        result.style.display = 'block';
        result.innerHTML = data;
    })
    .catch(err => alert('Import failed'));
});
</script>

</body>
</html>
PHP
,

'import.php' => <<<'PHP'
<?php
// import.php

require 'config.php';

if (empty($_FILES['json_files'])) {
    exit('No files uploaded.');
}

foreach ($_FILES['json_files']['tmp_name'] as $index => $tmpName) {

    $fileName = $_FILES['json_files']['name'][$index];
    $tableName = preg_replace('/[^a-zA-Z0-9_]/', '_', pathinfo($fileName, PATHINFO_FILENAME));

    $json = file_get_contents($tmpName);
    $data = json_decode($json, true);

    if (!is_array($data) || empty($data)) {
        echo "<p>❌ {$fileName}: Invalid or empty JSON</p>";
        continue;
    }

    if (!is_array($data[0])) {
        echo "<p>❌ {$fileName}: JSON must be an array of objects</p>";
        continue;
    }

    $columns = array_keys($data[0]);

    $colsSql = [];
    foreach ($columns as $col) {
        $colSafe = preg_replace('/[^a-zA-Z0-9_]/', '_', $col);
        $colsSql[] = "`$colSafe` TEXT";
    }

    $pdo->exec("CREATE TABLE IF NOT EXISTS `$tableName` (
        id INT AUTO_INCREMENT PRIMARY KEY,
        " . implode(',', $colsSql) . "
    )");

    $placeholders = implode(',', array_fill(0, count($columns), '?'));
    $colNames = '`' . implode('`,`', $columns) . '`';

    $stmt = $pdo->prepare("INSERT INTO `$tableName` ($colNames) VALUES ($placeholders)");

    foreach ($data as $row) {
        $stmt->execute(array_values($row));
    }

    echo "<p>✅ {$fileName}: Imported into table <strong>{$tableName}</strong></p>";
}
PHP
];

foreach ($files as $filename => $content) {
    if (file_exists($filename)) {
        echo "⚠️ {$filename} already exists — skipped<br>";
        continue;
    }
    file_put_contents($filename, $content);
    echo "✅ {$filename} created<br>";
}

echo "<br>Done. You can now delete unpack.php.";