38682-vm/db/init.php
2026-02-23 18:50:55 +00:00

67 lines
2.9 KiB
PHP

<?php
require_once __DIR__ . '/config.php';
try {
$pdo = db();
// 1. Run Consolidated Schema
$schema = file_get_contents(__DIR__ . '/schema.sql');
// Split by ; to handle multiple statements if PDO::exec has issues,
// but schema.sql is designed to be executed as one block or via a loop.
// For simplicity and to handle the large schema:
$queries = array_filter(array_map('trim', explode(';', $schema)));
foreach ($queries as $query) {
if (!empty($query)) {
try {
$pdo->exec($query);
} catch (PDOException $e) {
// Ignore errors like "Duplicate column" if re-running on existing DB
if (strpos($e->getMessage(), 'Duplicate column') === false &&
strpos($e->getMessage(), 'already exists') === false) {
echo "Notice (Schema): " . $e->getMessage() . "\n";
}
}
}
}
// 2. Run Company Settings if table exists
if (file_exists(__DIR__ . '/company_settings.sql')) {
$cs_sql = file_get_contents(__DIR__ . '/company_settings.sql');
$cs_queries = array_filter(array_map('trim', explode(';', $cs_sql)));
foreach ($cs_queries as $query) {
if (!empty($query)) {
try {
$pdo->exec($query);
} catch (PDOException $e) {
// Ignore
}
}
}
}
// 3. Seed initial data if empty
$stmt = $pdo->query("SELECT COUNT(*) FROM outlets");
if ($stmt->fetchColumn() == 0) {
$pdo->exec("INSERT INTO outlets (name, address) VALUES ('Main Downtown', '123 Main St'), ('Westside Hub', '456 West Blvd')");
$pdo->exec("INSERT INTO categories (name, sort_order) VALUES ('Burgers', 1), ('Sides', 2), ('Drinks', 3)");
$pdo->exec("INSERT INTO products (category_id, name, description, price) VALUES
(1, 'Signature Burger', 'Juicy beef patty with special sauce', 12.99),
(1, 'Veggie Delight', 'Plant-based patty with fresh avocado', 11.50),
(2, 'Truffle Fries', 'Crispy fries with truffle oil and parmesan', 5.99),
(3, 'Craft Cola', 'House-made sparkling cola', 3.50)");
// Ensure Admin group and user exist
$pdo->exec("INSERT IGNORE INTO user_groups (id, name, permissions) VALUES (1, 'Administrator', 'all')");
// admin123 hash
$hashed_pass = password_hash('admin123', PASSWORD_DEFAULT);
$pdo->exec("INSERT IGNORE INTO users (group_id, username, password, full_name, is_active)
VALUES (1, 'admin', '$hashed_pass', 'Super Admin', 1)");
echo "Database initialized and seeded successfully.";
} else {
echo "Database structure updated. Data already exists.";
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}