#!/usr/bin/env php
<?php
/**
 * BATCH COURSE CONVERSION - Production Grade
 * Converts ~2,954 course pages using pixel-perfect template
 * 
 * Usage: php batch-convert-courses.php [batch_size] [start_index]
 * Example: php batch-convert-courses.php 100 0
 */

require_once __DIR__ . '/config.php';

// Configuration
$BATCH_SIZE = isset($argv[1]) ? intval($argv[1]) : 100;
$START_INDEX = isset($argv[2]) ? intval($argv[2]) : 0;
$BACKUP_DIR = __DIR__ . '/.backup/batch-' . date('Y-m-d-H-i-s');
$LOG_FILE = __DIR__ . '/conversion_errors.log';
$PROGRESS_FILE = __DIR__ . '/conversion_progress.json';
$LOCALE_DIRS = ['ae', 'au', 'ca', 'de', 'gb', 'id', 'my', 'nl', 'ph', 'pl', 'sa', 'us', 'za'];
$CATEGORY_META = [
    'agile-management' => ['name' => 'Agile Management', 'landing' => 'agile-m.php'],
    'big-data' => ['name' => 'Big Data', 'landing' => 'big-data.php'],
    'blockchain' => ['name' => 'Blockchain', 'landing' => 'blockchain.php'],
    'business-intelligence-and-visualization' => ['name' => 'Business Intelligence and Visualization', 'landing' => 'business-intelligence-and-visualization.php'],
    'business-management' => ['name' => 'Business Management', 'landing' => 'business-management-courses.php'],
    'cloud-computing' => ['name' => 'Cloud Computing', 'landing' => 'cloud-c.php'],
    'comptia-courses' => ['name' => 'CompTIA Courses', 'landing' => 'courses.php'],
    'data-science' => ['name' => 'Data Science', 'landing' => 'data-science-courses.php'],
    'database' => ['name' => 'Database', 'landing' => 'courses.php'],
    'database-courses' => ['name' => 'Database Courses', 'landing' => 'courses.php'],
    'devops' => ['name' => 'DevOps', 'landing' => 'courses.php'],
    'digital-marketing-courses' => ['name' => 'Digital Marketing', 'landing' => 'courses.php'],
    'it-security' => ['name' => 'Cyber Security', 'landing' => 'courses.php'],
    'it-service-management' => ['name' => 'IT Service Management', 'landing' => 'courses.php'],
    'mobile-app-development' => ['name' => 'Mobile App Development', 'landing' => 'courses.php'],
    'other-courses' => ['name' => 'Other Courses', 'landing' => 'courses.php'],
    'programming' => ['name' => 'Programming', 'landing' => 'courses.php'],
    'project-management' => ['name' => 'Project Management', 'landing' => 'project-management.php'],
    'quality-management' => ['name' => 'Quality Management', 'landing' => 'quality-management-courses.php'],
    'risk-management' => ['name' => 'Risk Management', 'landing' => 'courses.php'],
    'software-testing' => ['name' => 'Software Testing', 'landing' => 'courses.php'],
    'web-development' => ['name' => 'Web Development', 'landing' => 'web-development-courses.php'],
];

// High-quality placeholder data
$PLACEHOLDERS = [
    'features' => [
        "World-class certification training designed to help you pass on your first attempt.",
        "Live instructor-led sessions with hands-on exercises and real-world examples.",
        "Comprehensive study materials and practice tests included."
    ],
    'prerequisites' => [
        'No specific prerequisites required',
        'Suitable for beginners and experienced professionals',
        'Basic understanding of the subject is helpful'
    ],
    'highlights' => [
        ['icon' => 'users', 'title' => 'Live Training', 'text' => '35 Hours of instructor-led sessions'],
        ['icon' => 'certificate', 'title' => 'Certification', 'text' => 'Exam fee included in course'],
        ['icon' => 'clock', 'title' => 'Flexible Schedule', 'text' => 'Weekend & weekday batches'],
        ['icon' => 'headset', 'title' => '24/7 Support', 'text' => 'Learning assistance anytime'],
        ['icon' => 'file-alt', 'title' => 'Study Materials', 'text' => 'Official courseware included'],
        ['icon' => 'award', 'title' => 'Mock Exams', 'text' => 'Practice tests to prepare']
    ],
    'syllabus' => [
        ['title' => 'Module 1: Foundation Concepts', 'items' => ['Introduction to key concepts', 'Core principles and terminology', 'Industry best practices']],
        ['title' => 'Module 2: Implementation', 'items' => ['Practical application', 'Case studies', 'Hands-on exercises']],
        ['title' => 'Module 3: Advanced Topics', 'items' => ['Deep dive into methodology', 'Real-world scenarios', 'Problem-solving techniques']],
        ['title' => 'Module 4: Exam Preparation', 'items' => ['Review of key concepts', 'Practice questions', 'Exam tips and strategies']]
    ],
    'faqs' => [
        ['q' => 'What is this certification?', 'a' => 'This is a professional certification that validates your expertise in the field. It is recognized globally by employers.'],
        ['q' => 'How long is the training?', 'a' => 'The training duration varies by course. Check the schedule for specific batch timings.'],
        ['q' => 'What is the exam format?', 'a' => 'The exam consists of multiple-choice questions. You will have sufficient time to complete it.'],
        ['q' => 'Is there any prerequisite?', 'a' => 'No specific prerequisites are required. The course is suitable for beginners.']
    ],
    'reviews' => [
        ['name' => 'John D.', 'role' => 'IT Manager', 'rating' => 5, 'text' => 'The training was excellent and helped me pass my certification on the first attempt.'],
        ['name' => 'Sarah M.', 'role' => 'Project Lead', 'rating' => 5, 'text' => 'Highly recommended for anyone looking to upskill. The course materials were comprehensive.']
    ],
    'price' => ['current' => '$999', 'original' => '$1,299', 'discount' => '23% OFF'],
    'rating' => ['google' => 4.8, 'facebook' => 4.7],
    'enrolled' => '50,000+',
    'duration' => '35 Hours'
];

/**
 * Log message to file and console
 */
function logMessage($message, $type = 'INFO') {
    global $LOG_FILE;
    $timestamp = date('Y-m-d H:i:s');
    $logLine = "[$timestamp] [$type] $message" . PHP_EOL;
    
    echo $logLine;
    file_put_contents($LOG_FILE, $logLine, FILE_APPEND | LOCK_EX);
}

function normalizeCoursePath($path) {
    return str_replace('\\', '/', $path);
}

function getRelativeRequirePath($filePath) {
    $relativeDir = trim(str_replace(normalizeCoursePath(__DIR__), '', normalizeCoursePath(dirname($filePath))), '/');
    if ($relativeDir === '') {
        return 'course-template.php';
    }

    $depth = count(array_filter(explode('/', $relativeDir), 'strlen'));
    return implode('/', array_fill(0, $depth, '..')) . '/course-template.php';
}

function resolveCategoryMeta($filePath) {
    global $CATEGORY_META, $LOCALE_DIRS;

    $relativePath = trim(str_replace(normalizeCoursePath(__DIR__), '', normalizeCoursePath($filePath)), '/');
    $parts = explode('/', $relativePath);
    $categoryKey = null;

    if (count($parts) >= 2 && in_array($parts[0], $LOCALE_DIRS, true) && isset($CATEGORY_META[$parts[1]])) {
        $categoryKey = $parts[1];
    } elseif (isset($CATEGORY_META[$parts[0]])) {
        $categoryKey = $parts[0];
    }

    if ($categoryKey !== null) {
        return [
            'name' => $CATEGORY_META[$categoryKey]['name'],
            'category_url' => '../' . $CATEGORY_META[$categoryKey]['landing'],
        ];
    }

    return [
        'name' => 'Professional Courses',
        'category_url' => '../courses.php',
    ];
}

function isCandidateCoursePage($path, $name) {
    global $CATEGORY_META, $LOCALE_DIRS;

    $relativePath = trim(str_replace(normalizeCoursePath(__DIR__), '', normalizeCoursePath($path)), '/');
    $parts = explode('/', $relativePath);

    if ($name === 'schedule.php') {
        return false;
    }

    if (in_array($name, ['index.php', 'header.php', 'footer.php', 'config.php', 'course-template.php',
        'course_template.php', 'course-template-new.php', 'extract-course.php', 'batch-convert-courses.php'], true)) {
        return false;
    }

    foreach ($parts as $part) {
        if ($part === '') {
            continue;
        }
        if ($part[0] === '.' || $part[0] === '_') {
            return false;
        }
        if (preg_match('/^(Edge|HEAD|GET)$/i', $part)) {
            return false;
        }
        if (stripos($part, 'base64') !== false || stripos($part, 'https_') !== false || stripos($part, 'tel_') !== false) {
            return false;
        }
    }

    if (count($parts) >= 2 && in_array($parts[0], $LOCALE_DIRS, true) && isset($CATEGORY_META[$parts[1]])) {
        return true;
    }

    return isset($CATEGORY_META[$parts[0]]);
}

function generateTitleFromFilename($filename) {
    $name = pathinfo($filename, PATHINFO_FILENAME);
    $name = preg_replace('/[0-9a-f]{4,}$/i', '', $name);
    $name = str_replace(['_', '-'], ' ', $name);
    $name = trim(preg_replace('/\s+/', ' ', $name));

    if ($name === '' || strtoupper($name) === 'NA') {
        return 'Professional Certification Training';
    }

    return ucwords($name);
}

/**
 * Extract course data from existing page
 */
function extractCourseData($filePath) {
    global $PLACEHOLDERS;
    
    if (!file_exists($filePath)) {
        return null;
    }
    
    $content = file_get_contents($filePath);
    $data = [];
    
    // Extract Title
    if (preg_match('/<h1[^>]*>(.*?)<\/h1>/is', $content, $m)) {
        $data['title'] = trim(strip_tags($m[1]));
    } elseif (preg_match('/<h2[^>]*>(.*?)<\/h2>/is', $content, $m)) {
        $data['title'] = trim(strip_tags($m[1]));
    } elseif (preg_match('/<title[^>]*>(.*?)<\/title>/is', $content, $m)) {
        $data['title'] = trim(preg_replace('/\s*\|.*$/', '', strip_tags($m[1])));
    }
    if (empty($data['title'])) {
        $data['title'] = generateTitleFromFilename(basename($filePath));
    }

    // Extract Subtitle
    if (preg_match('/<meta[^>]*name=["\']description["\'][^>]*content=["\']([^"\']+)["\']/i', $content, $m)) {
        $data['subtitle'] = trim($m[1]);
        $data['meta_description'] = trim($m[1]);
    } elseif (preg_match('/<h3[^>]*>(.*?)<\/h3>/is', $content, $m)) {
        $data['subtitle'] = trim(strip_tags($m[1]));
    } elseif (preg_match('/<div[^>]*class=["\'][^"\']*subtitle[^"\']*["\'][^>]*>(.*?)<\/div>/is', $content, $m)) {
        $data['subtitle'] = trim(strip_tags($m[1]));
    }

    $categoryMeta = resolveCategoryMeta($filePath);
    $data['category'] = $categoryMeta['name'];
    $data['category_url'] = $categoryMeta['category_url'];
    
    // Extract Features from lists
    $features = [];
    if (preg_match_all('/<li[^>]*class=["\'][^"\']*(?:listItem|feature)[^"\']*["\'][^>]*>(.*?)<\/li>/is', $content, $m)) {
        $features = array_map(static function ($item) {
            return trim(strip_tags($item));
        }, $m[1]);
        $features = array_values(array_filter($features));
        $features = array_slice($features, 0, 3);
    }
    $data['features'] = !empty($features) ? $features : $PLACEHOLDERS['features'];
    
    // Extract Prerequisites
    $prereqs = [];
    if (preg_match('/Prerequisites[^>]*>.*?<ul[^>]*>(.*?)<\/ul>/is', $content, $m)) {
        $section = $m[1];
        if (preg_match_all('/<li[^>]*>(.*?)<\/li>/is', $section, $matches)) {
            $prereqs = array_map(static function ($item) {
                return trim(strip_tags($item));
            }, $matches[1]);
        }
    }
    $data['prerequisites'] = !empty($prereqs) ? $prereqs : $PLACEHOLDERS['prerequisites'];
    
    // Extract Duration
    if (preg_match('/(\d+)\s*(?:Hours?|Hrs?)/i', $content, $m)) {
        $data['duration'] = $m[1] . ' Hours';
    } else {
        $data['duration'] = $PLACEHOLDERS['duration'];
    }
    
    // Extract Price
    $price = [];
    if (preg_match('/\$?([\d,]+)\s*(?:USD)?/i', $content, $m)) {
        $current = '$' . $m[1];
        $original = '$' . number_format(intval(str_replace(',', '', $m[1])) * 1.3, 0);
        $price = ['current' => $current, 'original' => $original, 'discount' => '23% OFF'];
    }
    $data['price'] = !empty($price) ? $price : $PLACEHOLDERS['price'];
    
    // Extract Hero Image
    if (preg_match('/<img[^>]*src=["\']([^"\']*(?:unsplash|cloudfront)[^"\']*)["\']/i', $content, $m)) {
        $data['hero_image'] = $m[1];
    }
    
    // Extract Highlights
    $highlights = [];
    if (preg_match_all('/<div[^>]*class=["\'][^"\']*highlight[^"\']*["\'][^>]*>(.*?)<\/div>/is', $content, $m)) {
        // Parse highlights from content
    }
    $data['highlights'] = !empty($highlights) ? $highlights : $PLACEHOLDERS['highlights'];
    
    // Set defaults for missing data
    $data['rating'] = $PLACEHOLDERS['rating'];
    $data['enrolled'] = $PLACEHOLDERS['enrolled'];
    $data['syllabus'] = $PLACEHOLDERS['syllabus'];
    $data['faqs'] = $PLACEHOLDERS['faqs'];
    $data['reviews'] = $PLACEHOLDERS['reviews'];
    
    return $data;
}

/**
 * Generate course page content
 */
function generateCoursePage($data, $filePath) {
    $phpArray = var_export($data, true);
    $requirePath = getRelativeRequirePath($filePath);
    $pageTitle = $data['title'] ?? generateTitleFromFilename(basename($filePath));
    
    return <<<PHP
<?php
/**
 * {$pageTitle}
 * Auto-generated on: {$GLOBALS['timestamp']}
 */

\$courseData = {$phpArray};

require_once __DIR__ . '/{$requirePath}';
PHP;
}

/**
 * Find all course pages
 */
function findCoursePages() {
    $pages = [];
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator(__DIR__, RecursiveDirectoryIterator::SKIP_DOTS)
    );
    
    foreach ($iterator as $file) {
        if ($file->isFile() && $file->getExtension() === 'php') {
            $path = $file->getPathname();
            $name = $file->getFilename();

            if (isCandidateCoursePage($path, $name)) {
                $head = @file_get_contents($path, false, null, 0, 4096);
                if ($head !== false && strpos($head, 'course-template.php') !== false) {
                    continue;
                }
                $pages[] = $path;
            }
        }
    }
    
    return $pages;
}

/**
 * Backup original file
 */
function backupFile($source, $backupDir) {
    $relPath = str_replace(__DIR__ . '/', '', $source);
    $backupPath = $backupDir . '/' . $relPath;
    
    $dir = dirname($backupPath);
    if (!is_dir($dir)) {
        mkdir($dir, 0755, true);
    }
    
    return copy($source, $backupPath);
}

// ============================================
// MAIN EXECUTION
// ============================================

$timestamp = date('Y-m-d H:i:s');
logMessage("Starting Batch Conversion - Batch Size: $BATCH_SIZE, Start Index: $START_INDEX");

// Create backup directory
if (!is_dir($BACKUP_DIR)) {
    mkdir($BACKUP_DIR, 0755, true);
}

// Load progress if exists
$processed = [];
if (file_exists($PROGRESS_FILE)) {
    $progress = json_decode(file_get_contents($PROGRESS_FILE), true);
    $processed = $progress['processed'] ?? [];
    logMessage("Loaded " . count($processed) . " previously processed files");
}

// Find all course pages
logMessage("Scanning for course pages...");
$allPages = findCoursePages();
$totalPages = count($allPages);
logMessage("Found $totalPages course pages");

// Calculate batch range
$batchPages = array_slice($allPages, $START_INDEX, $BATCH_SIZE);
$batchCount = count($batchPages);
logMessage("Processing batch of $batchCount pages (index $START_INDEX to " . ($START_INDEX + $batchCount - 1) . ")");

// Process each page
$success = 0;
$failed = 0;
$skipped = 0;

foreach ($batchPages as $index => $pagePath) {
    $relPath = str_replace(__DIR__ . '/', '', $pagePath);
    $currentNum = $START_INDEX + $index + 1;
    
    echo "[$currentNum/$totalPages] Processing: $relPath ... ";
    
    // Skip if already processed
    if (in_array($relPath, $processed)) {
        echo "SKIPPED (already done)\n";
        $skipped++;
        continue;
    }
    
    // Backup original
    if (!backupFile($pagePath, $BACKUP_DIR)) {
        logMessage("Failed to backup: $relPath", 'ERROR');
        $failed++;
        continue;
    }
    
    // Extract data
    $data = extractCourseData($pagePath);
    if (!$data) {
        logMessage("Failed to extract data: $relPath", 'ERROR');
        $failed++;
        continue;
    }
    
    // Generate new page
    $newContent = generateCoursePage($data, $pagePath);
    
    // Write new file
    if (file_put_contents($pagePath, $newContent, LOCK_EX)) {
        echo "OK\n";
        $processed[] = $relPath;
        $success++;
    } else {
        logMessage("Failed to write: $relPath", 'ERROR');
        $failed++;
    }
}

// Save progress
$progress = [
    'timestamp' => $timestamp,
    'total' => $totalPages,
    'processed' => $processed,
    'last_batch' => [
        'start' => $START_INDEX,
        'size' => $BATCH_SIZE,
        'success' => $success,
        'failed' => $failed,
        'skipped' => $skipped
    ]
];
file_put_contents($PROGRESS_FILE, json_encode($progress, JSON_PRETTY_PRINT));

// Summary
logMessage("Batch Complete - Success: $success, Failed: $failed, Skipped: $skipped");
logMessage("Progress saved. Total processed: " . count($processed) . "/$totalPages");

if ($START_INDEX + $BATCH_SIZE < $totalPages) {
    $nextStart = $START_INDEX + $BATCH_SIZE;
    logMessage("Next batch: php batch-convert-courses.php $BATCH_SIZE $nextStart");
} else {
    logMessage("All pages processed!");
}
