#!/bin/bash
# generate-all.sh
# Master generator for ALL documentation, JS modules, and learning app scaffolding

DOCS_DIR="./docs"
JS_DIR="./js"

echo "📘 Creating directories..."
mkdir -p "$DOCS_DIR"
mkdir -p "$JS_DIR"

###############################################
# DOCUMENTATION GENERATION
###############################################
echo "📘 Generating documentation..."

cat << 'EOF' > "$DOCS_DIR/README.md"
# 📘 Diagnostics & Learning Platform — README
A modular PHP diagnostics + learning system with:
- Debug engine
- Perf engine
- DB connection module
- Bootstrap 5 UI
- DataTables
- Learning app with steps, quizzes, notes, progress, dark mode
EOF

cat << 'EOF' > "$DOCS_DIR/DEVELOPER_GUIDE.md"
# 🧑‍💻 Developer Guide
Coding standards, module responsibilities, error handling rules, architecture flow.
EOF

cat << 'EOF' > "$DOCS_DIR/ARCHITECTURE_GUIDE.md"
# 🏛 Architecture Guide
System layers, module boundaries, error flow, perf/debug integration.
EOF

cat << 'EOF' > "$DOCS_DIR/CODING_STANDARDS.md"
# 🧾 Coding Standards
Strict types, PSR-12, safe SQL, debug groups, perf usage, UI rules.
EOF

cat << 'EOF' > "$DOCS_DIR/MYSQL_GUIDE.md"
# 🗄️ MySQL Schema Guide
Expected schema, indexing strategy, query patterns, profiling interpretation.
EOF

cat << 'EOF' > "$DOCS_DIR/ROADMAP.md"
# 🧭 Project Roadmap
Phases 1–8: learning platform, diagnostics tools, UI/UX, interactive features, maintenance.
EOF

cat << 'EOF' > "$DOCS_DIR/TASKS.md"
# 📋 Task List
All actionable tasks for learning app, diagnostics framework, UI/UX, docs, tools.
EOF

cat << 'EOF' > "$DOCS_DIR/LEARN_DEBUG.md"
# 🧠 Learn Debug System
Debug levels, groups, formatting, logging.
EOF

cat << 'EOF' > "$DOCS_DIR/LEARN_PERF.md"
# ⚡ Learn Performance System
Timers, SQL profiling, function profiling, perf summary.
EOF

cat << 'EOF' > "$DOCS_DIR/LEARN_SQL.md"
# 🧩 Learn SQL Diagnostics
Schema validation, SQL errors, profiling, indexes.
EOF

cat << 'EOF' > "$DOCS_DIR/LEARN_UI.md"
# 🎨 Learn UI System
Bootstrap 5, responsive design, DataTables.
EOF

cat << 'EOF' > "$DOCS_DIR/LEARN_ERRORS.md"
# 🚨 Learn Error Handling
Module-level catching, app-level SQL handling, DB errors.
EOF

cat << 'EOF' > "$DOCS_DIR/AI_GUIDE.md"
# 🤖 AI Integration Guide
AI-assisted docs, code review, SQL optimization, perf tuning.
EOF

cat << 'EOF' > "$DOCS_DIR/TROUBLESHOOTING.md"
# 🛠 Troubleshooting Guide
Common DB, SQL, perf, debug, UI issues.
EOF

cat << 'EOF' > "$DOCS_DIR/SECURITY_GUIDE.md"
# 🔐 Security Guide
SQL injection prevention, safe SELECT builder, error sanitization.
EOF

cat << 'EOF' > "$DOCS_DIR/RELEASE_NOTES.md"
# 📝 Release Notes
v1.0 — Core modules, learning app, documentation generator.
EOF

echo "📘 Documentation generated."

###############################################
# JS MODULE GENERATION
###############################################
echo "📘 Generating JS modules..."

cat << 'EOF' > "$JS_DIR/markdown-viewer.js"
async function loadStepDoc(stepId) {
    const config = await (await fetch('learning-config.json')).json();
    const step = config.steps.find(s => s.id == stepId);
    if (!step) return;

    const response = await fetch('docs/' + step.doc);
    const text = await response.text();

    document.getElementById('docViewer').textContent = text;
    localStorage.setItem('activeStep', stepId);
    loadNotes(stepId);
    updateProgressUI(stepId);
}
EOF

cat << 'EOF' > "$JS_DIR/progress.js"
function updateProgressUI(activeStepId) {
    const cards = document.querySelectorAll('.step-card');
    let completed = 0;

    cards.forEach(card => {
        const id = card.dataset.step;
        const status = document.getElementById('status-' + id);
        const done = !!localStorage.getItem('completed-' + id);

        if (id == activeStepId) {
            card.classList.add('step-active');
            status.textContent = done ? 'Completed (Active)' : 'Active';
        } else if (done) {
            card.classList.add('step-complete');
            status.textContent = 'Completed';
            completed++;
        } else {
            card.classList.add('step-pending');
            status.textContent = 'Pending';
        }
    });

    const percent = Math.round((completed / cards.length) * 100);
    const bar = document.getElementById('globalProgress');
    bar.style.width = percent + '%';
    bar.textContent = percent + '%';
}
EOF

cat << 'EOF' > "$JS_DIR/quiz-engine.js"
const QUIZZES = {
    2: {
        question: "What does debug.php handle?",
        options: ["DB connections", "Perf profiling", "Debug formatting/logging", "UI rendering"],
        answerIndex: 2
    }
};
EOF

cat << 'EOF' > "$JS_DIR/theme.js"
document.addEventListener('DOMContentLoaded', () => {
    const body = document.getElementById('body');
    const toggle = document.getElementById('toggleTheme');
    const saved = localStorage.getItem('theme') || 'light';

    if (saved === 'dark') body.classList.add('dark-mode');

    toggle.onclick = () => {
        body.classList.toggle('dark-mode');
        localStorage.setItem('theme', body.classList.contains('dark-mode') ? 'dark' : 'light');
    };
});
EOF

echo "📘 JS modules generated."

###############################################
# LEARNING CONFIG GENERATION
###############################################
echo "📘 Generating learning-config.json..."

cat << 'EOF' > "learning-config.json"
{
  "title": "Diagnostics Framework Learning Path",
  "steps": [
    { "id": 1, "title": "Setup Environment", "description": "Install PHP, configure .env, run test apps.", "doc": "LEARN_SETUP_TASKS.md" },
    { "id": 2, "title": "Learn Debug System", "description": "Debug levels, groups, formatting.", "doc": "LEARN_DEBUG.md" },
    { "id": 3, "title": "Learn Performance System", "description": "SQL profiling, timers.", "doc": "LEARN_PERF.md" },
    { "id": 4, "title": "Learn SQL Diagnostics", "description": "Schema validation, SQL errors.", "doc": "LEARN_SQL.md" },
    { "id": 5, "title": "Learn Architecture", "description": "Module boundaries, error flow.", "doc": "ARCHITECTURE_GUIDE.md" }
  ]
}
EOF

###############################################
# LEARNING APP SCAFFOLDING
###############################################
echo "📘 Generating learning-app.php..."

cat << 'EOF' > "learning-app.php"
<?php
declare(strict_types=1);

$config = json_decode(file_get_contents(__DIR__ . '/learning-config.json'), true);
$steps  = $config['steps'];
$title  = $config['title'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><?= htmlspecialchars($title) ?></title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

    <style>
        body.dark-mode { background-color: #121212; color: #e0e0e0; }
        .step-card { cursor: pointer; transition: 0.3s; }
        .step-complete { border-left: 5px solid #28a745; }
        .step-active { border-left: 5px solid #0d6efd; }
        .step-pending { border-left: 5px solid #6c757d; }
        .arrow { font-size: 1.5rem; }
        #docViewer { white-space: pre-wrap; }
        .badge { font-size: 0.8rem; }
    </style>
</head>
<body class="bg-light" id="body">

<div class="container py-4">

    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1><?= htmlspecialchars($title) ?></h1>
        <button class="btn btn-secondary btn-sm" id="toggleTheme">Toggle Dark Mode</button>
    </div>

    <div class="progress mb-4">
        <div id="globalProgress" class="progress-bar" role="progressbar" style="width: 0%"></div>
    </div>

    <div class="row">
        <div class="col-md-4">
            <?php foreach ($steps as $step): ?>
                <div class="card mb-3 step-card" data-step="<?= $step['id'] ?>">
                    <div class="card-body">
                        <h5 class="card-title">
                            Step <?= $step['id'] ?> — <?= htmlspecialchars($step['title']) ?>
                            <span class="float-end arrow">➜</span>
                        </h5>
                        <p class="card-text"><?= htmlspecialchars($step['description']) ?></p>
                        <span class="badge bg-secondary" id="status-<?= $step['id'] ?>">Pending</span>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <div class="col-md-8">
            <div class="card mb-3">
                <div class="card-header">Documentation</div>
                <div class="card-body">
                    <input type="text" id="searchDocs" class="form-control mb-3" placeholder="Search documentation...">
                    <pre id="docViewer" class="bg-dark text-light p-3 rounded small">Select a step to begin.</pre>
                </div>
            </div>

            <div class="card mb-3">
                <div class="card-header">Your Notes</div>
                <div class="card-body">
                    <textarea id="notes" class="form-control" rows="5" placeholder="Write notes for this step..."></textarea>
                </div>
            </div>

            <div class="card mb-3" id="quizPanel" style="display:none;">
                <div class="card-header">Quiz</div>
                <div class="card-body">
                    <div id="quizContent"></div>
                    <button class="btn btn-primary mt-3" id="submitQuiz">Submit Quiz</button>
                </div>
            </div>

            <button class="btn btn-success w-100 mt-3" id="completeStep" style="display:none;">
                Mark Step Complete ✔
            </button>
        </div>
    </div>

</div>

<script src="js/markdown-viewer.js"></script>
<script src="js/progress.js"></script>
<script src="js/quiz-engine.js"></script>
<script src="js/theme.js"></script>

</body>
</html>
EOF

echo "🎉 ALL FILES GENERATED SUCCESSFULLY!"

