<?php
require_once 'config/database.php';
require_once 'includes/functions.php';

$db = getDB();

$stmt = $db->query('SELECT id, course_id, title FROM course_modules WHERE slug = "" OR slug IS NULL');
$modules = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($modules as $module) {
    $baseSlug = createSlug($module['title']);
    $slug = $module['course_id'] . '-' . $baseSlug;
    $originalSlug = $slug;
    $counter = 1;
    while (true) {
        $checkStmt = $db->prepare('SELECT id FROM course_modules WHERE slug = ? AND id != ?');
        $checkStmt->execute([$slug, $module['id']]);
        if (!$checkStmt->fetch()) break;
        $slug = $originalSlug . '-' . $counter;
        $counter++;
    }
    $updateStmt = $db->prepare('UPDATE course_modules SET slug = ? WHERE id = ?');
    $updateStmt->execute([$slug, $module['id']]);
    echo 'Updated module ' . $module['id'] . ' with slug ' . $slug . PHP_EOL;
}

echo 'Done.' . PHP_EOL;
?>