exec("CREATE TABLE IF NOT EXISTS `migrations` ( `id` INT AUTO_INCREMENT PRIMARY KEY, `migration_file` VARCHAR(255) NOT NULL UNIQUE, `applied_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;"); // 2. Get applied migrations $appliedMigrations = $pdo->query("SELECT `migration_file` FROM `migrations`")->fetchAll(PDO::FETCH_COLUMN); // 3. Find migration files $migrationFiles = glob(__DIR__ . '/migrations/*.sql'); if (empty($migrationFiles)) { echo "No migration files found.\n"; } // 4. Apply pending migrations $migrationsApplied = 0; foreach ($migrationFiles as $file) { $basename = basename($file); if (!in_array($basename, $appliedMigrations)) { echo "Applying migration: {$basename}...\n"; $sql = file_get_contents($file); $pdo->exec($sql); $stmt = $pdo->prepare("INSERT INTO `migrations` (`migration_file`) VALUES (?)"); $stmt->execute([$basename]); echo " -> Applied successfully.\n"; $migrationsApplied++; } else { echo "Skipping already applied migration: {$basename}\n"; } } if ($migrationsApplied > 0) { echo "\nMigration complete. Applied {$migrationsApplied} new migration(s).\n"; } else { echo "\nDatabase is already up to date.\n"; } // 5. Synchronize inventory table echo "\nSynchronizing inventory...\n"; $stmt = $pdo->query("INSERT INTO inventory (product_id, quantity) SELECT p.id, 0 FROM products p LEFT JOIN inventory i ON p.id = i.product_id WHERE i.product_id IS NULL"); $newInventoryCount = $stmt->rowCount(); if ($newInventoryCount > 0) { echo "Added {$newInventoryCount} new products to the inventory with a default stock of 0.\n"; } else { echo "Inventory is already in sync with products.\n"; } } catch (PDOException $e) { die("Database migration failed: " . $e->getMessage() . "\n"); } ?>