false, 'error' => 'Unauthorized']); exit; } require_once '../db/config.php'; require_once '../db/backup_helper.php'; try { $db = db(); // 1. Perform database backup before migrations $backup_info = backup_db(); // 2. Ensure migration_history table exists $db->exec("CREATE TABLE IF NOT EXISTS migration_history ( id INT AUTO_INCREMENT PRIMARY KEY, filename VARCHAR(255) NOT NULL UNIQUE, executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;"); // 3. Scan migrations directory $migrations_dir = __DIR__ . '/../db/migrations/'; $migration_files = glob($migrations_dir . '*.sql'); sort($migration_files); // 4. Get list of already executed migrations $stmt = $db->query("SELECT filename FROM migration_history"); $executed_migrations = $stmt->fetchAll(PDO::FETCH_COLUMN); $executed_count = 0; $skipped_count = 0; $new_migrations = []; foreach ($migration_files as $file_path) { $filename = basename($file_path); if (in_array($filename, $executed_migrations)) { $skipped_count++; continue; } $sql = file_get_contents($file_path); if ($sql) { // Execute migration $db->exec($sql); // Record migration in history $stmt = $db->prepare("INSERT INTO migration_history (filename) VALUES (?)"); $stmt->execute([$filename]); $executed_count++; $new_migrations[] = $filename; } } echo json_encode([ 'success' => true, 'message' => "Backup and migration process complete.", 'backup' => $backup_info['filename'], 'executed' => $executed_count, 'skipped' => $skipped_count, 'new_migrations' => $new_migrations ]); } catch (Exception $e) { echo json_encode([ 'success' => false, 'error' => 'Migration/Backup failed: ' . $e->getMessage() ]); }