<?php
/**
 * Batch Course Conversion Script
 * Converts multiple course pages using the master template
 */

require_once __DIR__ . '/config.php';

$coursesToConvert = [
    // IT Service Management
    'it-service-management/itil-foundation-certification-training.php',
    
    // Agile Management  
    'agile-management/advanced-certified-scrum-product-owner-training.php',
    'agile-management/advanced-certified-scrummaster-training.php',
    
    // DevOps
    'devops/devops-training.php',
    
    // Project Management
    'project-management-certifications.php',
    
    // Cloud
    'cloud-computing/aws-solution-architect-associate-training.php',
    
    // Data Science
    'data-science-courses.php',
];

$backupDir = __DIR__ . '/_backup/';
$results = [];

echo "=== BATCH COURSE CONVERSION ===\n\n";

foreach ($coursesToConvert as $courseFile) {
    $sourcePath = __DIR__ . '/' . $courseFile;
    
    if (!file_exists($sourcePath)) {
        echo "⚠️  SKIP: $courseFile (not found)\n";
        $results[] = ['file' => $courseFile, 'status' => 'not_found'];
        continue;
    }
    
    // Create backup
    $relativePath = dirname($courseFile);
    $backupPath = $backupDir . $relativePath;
    if (!is_dir($backupPath)) {
        mkdir($backupPath, 0755, true);
    }
    
    $backupFile = $backupPath . '/' . basename($courseFile, '.php') . '-original.php';
    copy($sourcePath, $backupFile);
    
    // Run extraction
    echo "Processing: $courseFile\n";
    $outputFile = __DIR__ . '/' . dirname($courseFile) . '/' . basename($courseFile, '.php') . '-new.php';
    
    exec("php " . __DIR__ . "/extract-course.php $sourcePath $outputFile 2>&1", $execOutput, $exitCode);
    
    if ($exitCode === 0 && file_exists($outputFile)) {
        // Replace original with new
        rename($sourcePath, $backupPath . '/' . basename($courseFile, '.php') . '-pre-convert.php');
        rename($outputFile, $sourcePath);
        echo "  ✅ Converted successfully\n";
        $results[] = ['file' => $courseFile, 'status' => 'success'];
    } else {
        echo "  ❌ Failed to convert\n";
        $results[] = ['file' => $courseFile, 'status' => 'failed', 'output' => $execOutput];
    }
}

echo "\n=== RESULTS ===\n";
$success = array_filter($results, fn($r) => $r['status'] === 'success');
$failed = array_filter($results, fn($r) => $r['status'] !== 'success');

echo "Success: " . count($success) . "/" . count($results) . "\n";
if (count($failed) > 0) {
    echo "Failed:\n";
    foreach ($failed as $f) {
        echo "  - " . $f['file'] . " (" . $f['status'] . ")\n";
    }
}

// Show sample of first converted file
if (count($success) > 0) {
    $first = array_values($success)[0]['file'];
    echo "\n=== SAMPLE: $first ===\n";
    $content = file_get_contents(__DIR__ . '/' . $first);
    echo substr($content, 0, 1500) . "...\n";
}

echo "\nBackups stored in: _backup/\n";
