<?php
require_once 'config.php';
$currentPage = 'beginner';

// Initialize variables to prevent undefined notices
$userProgress = isset($userProgress) ? $userProgress : ['beginner_score' => 0];
$beginnerLessons = isset($beginnerLessons) ? $beginnerLessons : [];

// Handle quiz submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['quiz_answer'])) {
    $questionIndex = isset($_POST['question_index']) ? (int)$_POST['question_index'] : 0;
    $answer = isset($_POST['answer']) ? (int)$_POST['answer'] : 0;
    
    // Safely check answer
    $correct = false;
    if (function_exists('checkQuizAnswer')) {
        $correct = checkQuizAnswer('beginner', $questionIndex, $answer);
    }
    
    if ($correct && isset($db)) {
        $db->saveQuizResult('beginner', 100);
        $db->updateScore('beginner', 100);
    }
    
    header('Content-Type: application/json');
    echo json_encode(['correct' => $correct]);
    exit;
}

// Safely get quiz question
$quizQuestion = null;
if (function_exists('getQuizQuestion')) {
    $quizQuestion = getQuizQuestion('beginner', 0);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Beginner PHP - <?php echo defined('SITE_NAME') ? SITE_NAME : 'PHP Webdesign Fundamentals'; ?></title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar">
        <div class="container nav-container">
            <a href="index.php" class="logo">
                <span>&lt;/&gt;</span>
                PHP Webdesign
            </a>
            <ul class="nav-menu">
                <?php 
                $navItems = isset($navItems) ? $navItems : [];
                foreach ($navItems as $item): 
                    if (!isset($item['url']) || !isset($item['name']) || !isset($item['icon'])) continue;
                ?>
                <li class="nav-item">
                    <a href="<?php echo htmlspecialchars($item['url']); ?>" <?php echo (isset($currentPage) && $currentPage == strtolower($item['name'])) ? 'class="active"' : ''; ?>>
                        <span><?php echo htmlspecialchars($item['icon']); ?></span>
                        <?php echo htmlspecialchars($item['name']); ?>
                    </a>
                </li>
                <?php endforeach; ?>
            </ul>
        </div>
    </nav>

    <!-- Header -->
    <header class="header">
        <div class="container">
            <h1>🌱 Beginner PHP Fundamentals</h1>
            <p>Start your PHP journey here! Learn the basics with simple explanations and interactive examples.</p>
        </div>
    </header>

    <!-- Main Content -->
    <main class="container">
        <!-- Progress Tracker -->
        <div class="progress-tracker">
            <h3>Beginner Progress</h3>
            <div class="progress-bar">
                <?php $progressScore = isset($userProgress['beginner_score']) ? (int)$userProgress['beginner_score'] : 0; ?>
                <div class="progress-fill" style="width: <?php echo $progressScore; ?>%"></div>
            </div>
            <p>Completed: <?php echo $progressScore; ?>%</p>
        </div>

        <!-- Lessons -->
        <?php if (!empty($beginnerLessons) && is_array($beginnerLessons)): ?>
            <?php foreach ($beginnerLessons as $index => $lesson): ?>
                <?php if (!isset($lesson['title']) || !isset($lesson['content'])) continue; ?>
                <section class="game-section" style="margin-bottom: 30px;">
                    <h2><?php echo ((int)$index + 1) . '. ' . htmlspecialchars($lesson['title']); ?></h2>
                    
                    <?php if (isset($lesson['topics']) && is_array($lesson['topics'])): ?>
                    <div style="margin: 20px 0;">
                        <h3>📚 What you'll learn:</h3>
                        <ul style="color: var(--text-secondary); margin-left: 20px;">
                            <?php foreach ($lesson['topics'] as $topic): ?>
                            <li><?php echo htmlspecialchars($topic); ?></li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                    <?php endif; ?>
                    
                    <div style="margin: 20px 0;">
                        <h3>📖 Explanation:</h3>
                        <p style="color: var(--text-secondary);"><?php echo nl2br(htmlspecialchars($lesson['content'])); ?></p>
                    </div>
                    
                    <div class="code-block">
                        <h3>💻 Example Code:</h3>
                        <pre><?php echo isset($lesson['code']) ? htmlspecialchars($lesson['code']) : '// Code example coming soon'; ?></pre>
                    </div>
                    
                    <div style="margin-top: 20px;">
                        <button class="btn" onclick="tryCode(<?php echo (int)$index; ?>)">Try It Yourself</button>
                        <a href="?download=beginner_lesson_<?php echo (int)$index; ?>" class="btn btn-outline">Download Example</a>
                    </div>
                </section>
            <?php endforeach; ?>
        <?php else: ?>
            <section class="game-section">
                <h2>📚 Beginner Lessons Loading...</h2>
                <p>Please check back soon for our beginner PHP tutorials!</p>
            </section>
        <?php endif; ?>

        <!-- Interactive PHP Playground -->
        <section class="game-section">
            <h2>🎮 PHP Playground</h2>
            <p>Type your PHP code below and see the result!</p>
            
            <div style="margin: 20px 0;">
                <textarea id="php-code" rows="10" style="width: 100%; background: var(--darker-bg); color: var(--text-primary); border: 1px solid var(--primary-color); border-radius: 10px; padding: 15px; font-family: 'Courier New', monospace;"><?php echo "<?php\n\$name = 'World';\necho 'Hello, ' . \$name . '!';\n?>"; ?></textarea>
            </div>
            
            <button class="btn" onclick="runCode()">Run Code</button>
            
            <div id="output" style="margin-top: 20px; padding: 15px; background: var(--darker-bg); border-radius: 10px; border: 1px solid var(--primary-color); min-height: 100px;">
                Output will appear here...
            </div>
        </section>

        <!-- Beginner Game: PHP Match Game -->
        <section class="game-section">
            <h2>🎯 PHP Match Game</h2>
            <p>Match the PHP concepts with their descriptions!</p>
            
            <div id="match-game" style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px; margin-top: 30px;">
                <div style="grid-column: 1/2;">
                    <h3>Concepts:</h3>
                    <div id="concepts" style="display: grid; gap: 10px;">
                        <button class="option-btn" onclick="selectConcept(0)">Variable</button>
                        <button class="option-btn" onclick="selectConcept(1)">Array</button>
                        <button class="option-btn" onclick="selectConcept(2)">Function</button>
                        <button class="option-btn" onclick="selectConcept(3)">Loop</button>
                    </div>
                </div>
                <div style="grid-column: 2/2;">
                    <h3>Descriptions:</h3>
                    <div id="descriptions" style="display: grid; gap: 10px;">
                        <button class="option-btn" onclick="selectDescription(0)">Stores multiple values in one variable</button>
                        <button class="option-btn" onclick="selectDescription(1)">Reusable block of code</button>
                        <button class="option-btn" onclick="selectDescription(2)">Container for storing data</button>
                        <button class="option-btn" onclick="selectDescription(3)">Repeats code multiple times</button>
                    </div>
                </div>
            </div>
            
            <div id="match-feedback" style="text-align: center; margin-top: 20px;"></div>
            <div style="text-align: center; margin-top: 20px;">
                <button class="btn" onclick="checkMatch()">Check Match</button>
                <button class="btn btn-outline" onclick="resetMatch()">Reset Game</button>
            </div>
        </section>

        <!-- Beginner Quiz -->
        <section class="quiz-container">
            <h2>📝 Beginner Quiz</h2>
            <p>Test your knowledge with this quick quiz!</p>
            
            <div id="quiz">
                <?php if ($quizQuestion && isset($quizQuestion['question']) && isset($quizQuestion['options'])): ?>
                <div class="question" id="quiz-question"><?php echo htmlspecialchars($quizQuestion['question']); ?></div>
                <div class="options" id="quiz-options">
                    <?php foreach ($quizQuestion['options'] as $optIndex => $option): ?>
                    <button class="option-btn" onclick="submitQuizAnswer(<?php echo (int)$optIndex; ?>, 0)">
                        <?php echo htmlspecialchars($option); ?>
                    </button>
                    <?php endforeach; ?>
                </div>
                <?php else: ?>
                <div class="question">Quiz questions loading...</div>
                <?php endif; ?>
            </div>
            
            <div id="quiz-feedback" style="text-align: center; margin-top: 20px;"></div>
            <div style="display: flex; gap: 10px; justify-content: center; margin-top: 20px;">
                <button class="btn" onclick="nextQuestion()">Next Question</button>
                <button class="btn btn-outline" onclick="resetQuiz()">Reset Quiz</button>
            </div>
        </section>

        <!-- Download Section -->
        <section class="downloader-section">
            <h3>📥 Beginner Resources</h3>
            <p>Download practice files and cheat sheets</p>
            <div class="download-buttons">
                <a href="?download=beginner_notes" class="btn btn-outline">Beginner Notes</a>
                <a href="?download=beginner_exercises" class="btn btn-outline">Practice Exercises</a>
                <a href="?download=beginner_cheatsheet" class="btn btn-outline">PHP Cheatsheet</a>
            </div>
        </section>

        <?php
        // Handle downloads safely
        if (isset($_GET['download'])) {
            $download = $_GET['download'];
            $files = [
                'beginner_notes' => "PHP BEGINNER NOTES\n\n1. PHP Syntax\n- PHP code starts with <?php and ends with ?>\n- Statements end with semicolon\n\n2. Variables\n- Start with $\n- Case-sensitive\n- No declaration needed\n\n3. Data Types\n- String\n- Integer\n- Float\n- Boolean\n- Array\n\n4. Control Structures\n- if...else\n- switch\n- while\n- for\n- foreach",
                
                'beginner_exercises' => "PHP BEGINNER EXERCISES\n\nExercise 1: Variables\nCreate variables for your name, age, and favorite color. Display them in a sentence.\n\nExercise 2: Arrays\nCreate an array of 5 favorite foods. Loop through and display each one.\n\nExercise 3: Functions\nCreate a function that takes two numbers and returns their sum.",
                
                'beginner_cheatsheet' => "PHP BEGINNER CHEATSHEET\n\n<?php ... ?> - PHP tags\n// - Single line comment\n\nVARIABLES:\n\$var = value;\n\nOUTPUT:\necho 'text';\nprint_r(\$array);\n\nSTRINGS:\n'text' - literal\n\"text\" - interprets variables\n\nARRAYS:\n\$arr = [1, 2, 3];\ncount(\$arr);\n\nCONDITIONS:\nif (\$a > \$b) { ... }\nelse { ... }\n\nLOOPS:\nfor (\$i=0; \$i<10; \$i++) { ... }\nforeach (\$arr as \$item) { ... }\n\nFUNCTIONS:\nfunction name(\$param) {\n    return \$value;\n}"
            ];
            
            if (isset($files[$download])) {
                header('Content-Type: text/plain');
                header('Content-Disposition: attachment; filename="' . $download . '.txt"');
                echo $files[$download];
                exit;
            }
            
            // Handle lesson downloads
            if (strpos($download, 'beginner_lesson_') === 0) {
                $lessonIndex = (int)substr($download, -1);
                if (isset($beginnerLessons[$lessonIndex]['code'])) {
                    header('Content-Type: text/plain');
                    header('Content-Disposition: attachment; filename="lesson_' . $lessonIndex . '.php"');
                    echo $beginnerLessons[$lessonIndex]['code'];
                    exit;
                }
            }
        }
        ?>
    </main>

    <!-- Footer -->
    <footer class="footer">
        <div class="container">
            <div class="footer-content">
                <div class="footer-section">
                    <h4>About Us</h4>
                    <p>Master PHP web design with our comprehensive, interactive tutorials. From beginner to advanced, we've got you covered!</p>
                </div>
                
                <div class="footer-section">
                    <h4>Quick Links</h4>
                    <ul>
                        <li><a href="beginner.php">Beginner Lessons</a></li>
                        <li><a href="intermediate.php">Intermediate Lessons</a></li>
                        <li><a href="advanced.php">Advanced Lessons</a></li>
                    </ul>
                </div>
                
                <div class="footer-section">
                    <h4>Connect With Me</h4>
                    <div class="social-links">
                        <?php 
                        $socialLinks = isset($socialLinks) ? $socialLinks : [
                            'github' => '#',
                            'linkedin' => '#',
                            'twitter' => '#',
                            'youtube' => '#'
                        ];
                        ?>
                        <a href="<?php echo htmlspecialchars($socialLinks['github']); ?>" target="_blank" class="social-link tooltip">
                            <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='white'%3E%3Cpath d='M12 2C6.477 2 2 6.477 2 12c0 4.42 2.865 8.166 6.839 9.489.5.092.682-.217.682-.482 0-.237-.008-.866-.013-1.7-2.782.603-3.369-1.34-3.369-1.34-.454-1.156-1.11-1.462-1.11-1.462-.908-.62.069-.608.069-.608 1.003.07 1.531 1.03 1.531 1.03.892 1.529 2.341 1.087 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.11-4.555-4.943 0-1.091.39-1.984 1.03-2.682-.103-.253-.447-1.27.098-2.646 0 0 .84-.269 2.75 1.025.8-.223 1.65-.334 2.5-.334.85 0 1.7.111 2.5.334 1.91-1.294 2.75-1.025 2.75-1.025.545 1.376.201 2.393.099 2.646.64.698 1.03 1.591 1.03 2.682 0 3.841-2.337 4.687-4.565 4.935.359.309.678.919.678 1.852 0 1.336-.012 2.415-.012 2.743 0 .267.18.578.688.48C19.138 20.161 22 16.418 22 12c0-5.523-4.477-10-10-10z'/%3E%3C/svg%3E" alt="GitHub">
                            <span class="tooltip-text">GitHub</span>
                        </a>
                        <a href="<?php echo htmlspecialchars($socialLinks['linkedin']); ?>" target="_blank" class="social-link tooltip">
                            <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='white'%3E%3Cpath d='M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451c.979 0 1.771-.773 1.771-1.729V1.729C24 .774 23.204 0 22.225 0z'/%3E%3C/svg%3E" alt="LinkedIn">
                            <span class="tooltip-text">LinkedIn</span>
                        </a>
                    </div>
                </div>
            </div>
            <div style="text-align: center; margin-top: 30px; padding-top: 20px; border-top: 1px solid rgba(108, 92, 231, 0.3);">
                <p>&copy; <?php echo date('Y'); ?> PHP Webdesign Fundamentals. All rights reserved.</p>
            </div>
        </div>
    </footer>

    <script>
    // Game variables
    let selectedConcept = -1;
    let selectedDescription = -1;
    const matches = [-1, -1, -1, -1];
    const correctMatches = [2, 0, 1, 3]; // Concept index to correct description index
    
    function selectConcept(index) {
        selectedConcept = index;
        document.querySelectorAll('#concepts .option-btn').forEach((btn, i) => {
            if (i === index) {
                btn.classList.add('selected');
            } else {
                btn.classList.remove('selected');
            }
        });
    }
    
    function selectDescription(index) {
        selectedDescription = index;
        document.querySelectorAll('#descriptions .option-btn').forEach((btn, i) => {
            if (i === index) {
                btn.classList.add('selected');
            } else {
                btn.classList.remove('selected');
            }
        });
    }
    
    function checkMatch() {
        const feedback = document.getElementById('match-feedback');
        
        if (selectedConcept !== -1 && selectedDescription !== -1) {
            if (correctMatches[selectedConcept] === selectedDescription) {
                matches[selectedConcept] = selectedDescription;
                document.querySelectorAll('#concepts .option-btn')[selectedConcept].classList.add('correct');
                document.querySelectorAll('#descriptions .option-btn')[selectedDescription].classList.add('correct');
                feedback.innerHTML = '✅ Correct match!';
                feedback.style.color = 'var(--success-color)';
                
                // Check if all matched
                if (matches.every(m => m !== -1)) {
                    feedback.innerHTML = '🎉 Congratulations! You matched them all!';
                }
            } else {
                feedback.innerHTML = '❌ Not a match. Try again!';
                feedback.style.color = 'var(--error-color)';
            }
            
            selectedConcept = -1;
            selectedDescription = -1;
        } else {
            feedback.innerHTML = '⚠️ Please select a concept and a description first.';
            feedback.style.color = 'var(--warning-color)';
        }
    }
    
    function resetMatch() {
        selectedConcept = -1;
        selectedDescription = -1;
        for (let i = 0; i < matches.length; i++) {
            matches[i] = -1;
        }
        
        document.querySelectorAll('#concepts .option-btn, #descriptions .option-btn').forEach(btn => {
            btn.classList.remove('selected', 'correct', 'wrong');
        });
        
        document.getElementById('match-feedback').innerHTML = '';
    }
    
    function submitQuizAnswer(answer, questionIndex) {
        const feedback = document.getElementById('quiz-feedback');
        const options = document.querySelectorAll('#quiz-options .option-btn');
        
        options.forEach(opt => opt.classList.remove('selected', 'correct', 'wrong'));
        
        // Simulate correct answer (first option is correct for demo)
        if (answer === 0) {
            options[answer].classList.add('correct');
            feedback.innerHTML = '✅ Correct! Great job!';
            feedback.style.color = 'var(--success-color)';
        } else {
            options[answer].classList.add('wrong');
            options[0].classList.add('correct');
            feedback.innerHTML = '❌ Not quite. The correct answer is the first option.';
            feedback.style.color = 'var(--error-color)';
        }
    }
    
    function nextQuestion() {
        const questions = [
            'What does PHP stand for?',
            'How do you start a PHP block?',
            'Which symbol is used for variables in PHP?'
        ];
        const currentQuestion = document.getElementById('quiz-question');
        if (currentQuestion) {
            const randomIndex = Math.floor(Math.random() * questions.length);
            currentQuestion.textContent = questions[randomIndex];
            resetQuiz();
        }
    }
    
    function resetQuiz() {
        document.querySelectorAll('#quiz-options .option-btn').forEach(btn => {
            btn.classList.remove('selected', 'correct', 'wrong');
        });
        document.getElementById('quiz-feedback').innerHTML = '';
    }
    
    function tryCode(lessonIndex) {
        const examples = [
            "<?php\n// Try it yourself!\n$message = 'Hello, PHP!';\necho $message;\n?>",
            "<?php\n// Practice variables\n$name = 'Your Name';\n$age = 25;\necho \"My name is $name and I am $age years old\";\n?>",
            "<?php\n// Practice control structures\n$score = 85;\nif ($score >= 60) {\n    echo 'You passed!';\n} else {\n    echo 'Try again!';\n}\n?>"
        ];
        
        const codeArea = document.getElementById('php-code');
        if (codeArea) {
            codeArea.value = examples[lessonIndex] || examples[0];
            codeArea.scrollIntoView({ behavior: 'smooth' });
        }
    }
    
    function runCode() {
        const code = document.getElementById('php-code').value;
        const output = document.getElementById('output');
        
        // Simple simulation
        if (code.includes('echo')) {
            output.innerHTML = 'Simulated Output: Hello, World!';
        } else if (code.includes('$name')) {
            output.innerHTML = 'Simulated Output: My name is Your Name and I am 25 years old';
        } else {
            output.innerHTML = 'Simulated Output: Code executed successfully!';
        }
        
        output.innerHTML += '<br><small>(Note: This is a simulation. In a real environment, this would execute actual PHP code.)</small>';
    }

    // Copy code functionality
    function copyCode(button) {
        const code = button.previousElementSibling.innerText;
        navigator.clipboard.writeText(code).then(() => {
            button.textContent = 'Copied!';
            setTimeout(() => {
                button.textContent = 'Copy Code';
            }, 2000);
        });
    }

    // Add copy buttons to code blocks
    document.addEventListener('DOMContentLoaded', function() {
        const codeBlocks = document.querySelectorAll('.code-block pre');
        codeBlocks.forEach(block => {
            if (!block.parentNode.querySelector('.copy-btn')) {
                const button = document.createElement('button');
                button.className = 'copy-btn';
                button.textContent = 'Copy Code';
                button.onclick = function() { copyCode(this); };
                block.parentNode.insertBefore(button, block.nextSibling);
            }
        });
    });
    </script>
</body>
</html>