#!/usr/bin/env php
<?php
/**
 * Fix ALL Missing Titles - Target the main courseData array specifically
 */

function generateTitle($filename) {
    $name = str_replace('.php', '', $filename);
    $name = str_replace('-', ' ', $name);
    
    // Special acronyms - uppercase them
    $acronyms = ['csm', 'csp', 'csd', 'cspo', 'itil', 'pmp', 'capm', 'safe', 'aws', 'azure', 'gcp', 'ccna'];
    foreach ($acronyms as $acro) {
        $name = str_replace($acro, strtoupper($acro), $name);
    }
    
    return ucwords($name);
}

function hasMainTitle($content) {
    // Look for 'title' => 'something' that comes before 'category' (main level, not nested)
    if (preg_match('/\$courseData\s*=\s*array\s*\([^)]*?\'title\'\s*=>\s*\'[^\']{3,}\'/', $content)) {
        return true;
    }
    return false;
}

echo "=== FIXING ALL MISSING TITLES ===\n\n";

$fixed = 0;
$skipped = 0;
$failed = 0;

// Process course directories
$courseDirs = [
    'agile-management', 'devops', 'project-management', 'it-service-management',
    'cloud-computing', 'cyber-security', 'data-science', 'programming',
    'web-development', 'mobile-development', 'business-analysis',
    'quality-management', 'six-sigma', 'soft-skills', 'leadership'
];

foreach ($courseDirs as $dir) {
    $path = __DIR__ . '/' . $dir;
    if (!is_dir($path)) continue;
    
    $files = glob($path . '/*.php');
    
    foreach ($files as $file) {
        $filename = basename($file);
        if ($filename === 'index.php') continue;
        
        $content = file_get_contents($file);
        
        // Check if already has main title
        if (hasMainTitle($content)) {
            $skipped++;
            continue;
        }
        
        // Generate title from filename
        $title = generateTitle($filename);
        
        echo "[$dir/$filename] Adding: '$title' ... ";
        
        // Insert title right after array opening
        $pattern = '/(\$courseData\s*=\s*array\s*\()/s';
        $replacement = "$1\n  'title' => '$title',";
        
        $newContent = preg_replace($pattern, $replacement, $content, 1);
        
        if ($newContent !== null && $newContent !== $content) {
            if (file_put_contents($file, $newContent) !== false) {
                echo "OK\n";
                $fixed++;
            } else {
                echo "WRITE FAILED\n";
                $failed++;
            }
        } else {
            echo "PREG REPLACE FAILED\n";
            $failed++;
        }
    }
}

echo "\n=== COMPLETE ===\n";
echo "Fixed: $fixed\n";
echo "Skipped: $skipped\n";
echo "Failed: $failed\n";
