<?php
require_once 'config.php';
$currentPage = 'intermediate';

// Initialize variables to prevent undefined notices
$userProgress = isset($userProgress) ? $userProgress : ['intermediate_score' => 0];
$intermediateLessons = isset($intermediateLessons) ? $intermediateLessons : [];
$navItems = isset($navItems) ? $navItems : [];
$socialLinks = isset($socialLinks) ? $socialLinks : [
    'github' => '#',
    'linkedin' => '#',
    'twitter' => '#',
    'youtube' => '#'
];

// 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;
    
    $correct = false;
    if (function_exists('checkQuizAnswer')) {
        $correct = checkQuizAnswer('intermediate', $questionIndex, $answer);
    }
    
    if ($correct && isset($db) && method_exists($db, 'saveQuizResult')) {
        $db->saveQuizResult('intermediate', 100);
        $db->updateScore('intermediate', 100);
    }
    
    header('Content-Type: application/json');
    echo json_encode(['correct' => $correct]);
    exit;
}

// Handle form submission playground
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['playground_submit'])) {
    $playgroundData = [
        'name' => isset($_POST['playground_name']) ? htmlspecialchars($_POST['playground_name']) : '',
        'email' => isset($_POST['playground_email']) ? htmlspecialchars($_POST['playground_email']) : '',
        'message' => isset($_POST['playground_message']) ? htmlspecialchars($_POST['playground_message']) : '',
        'topic' => isset($_POST['playground_topic']) ? htmlspecialchars($_POST['playground_topic']) : '',
        'timestamp' => date('Y-m-d H:i:s')
    ];
    
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
    $_SESSION['playground_result'] = $playgroundData;
    header('Location: intermediate.php#playground');
    exit;
}

// Handle reset session
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['reset_session'])) {
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
    session_destroy();
    exit;
}

// Start session if not already started
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Intermediate PHP - <?php echo defined('SITE_NAME') ? SITE_NAME : 'PHP Webdesign Fundamentals'; ?></title>
    <link rel="stylesheet" href="style.css">
    <style>
        /* Additional styles specific to intermediate page */
        .form-playground {
            background: var(--darker-bg);
            border-radius: 20px;
            padding: 30px;
            border: 2px solid var(--primary-color);
            margin: 30px 0;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: var(--primary-color);
            font-weight: 500;
        }
        
        .form-group input,
        .form-group textarea,
        .form-group select {
            width: 100%;
            padding: 12px;
            background: var(--dark-bg);
            border: 1px solid rgba(108, 92, 231, 0.3);
            border-radius: 8px;
            color: var(--text-primary);
            font-size: 1rem;
            transition: all 0.3s ease;
        }
        
        .form-group input:focus,
        .form-group textarea:focus,
        .form-group select:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 15px var(--glow-color);
        }
        
        .session-demo {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin: 30px 0;
        }
        
        .session-card {
            background: var(--card-bg);
            border: 1px solid var(--primary-color);
            border-radius: 15px;
            padding: 20px;
            text-align: center;
        }
        
        .session-value {
            font-size: 2rem;
            color: var(--primary-color);
            margin: 15px 0;
            font-family: 'Courier New', monospace;
        }
        
        .file-upload-area {
            border: 2px dashed var(--primary-color);
            border-radius: 15px;
            padding: 40px;
            text-align: center;
            background: var(--card-bg);
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .file-upload-area:hover {
            background: rgba(108, 92, 231, 0.2);
            transform: scale(1.02);
        }
        
        .file-upload-area.dragover {
            background: rgba(108, 92, 231, 0.3);
            border-color: var(--accent-color);
        }
        
        .database-simulator {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 15px;
            margin: 20px 0;
        }
        
        .db-table {
            background: var(--darker-bg);
            border-radius: 10px;
            padding: 15px;
            border: 1px solid var(--primary-color);
        }
        
        .db-row {
            padding: 8px;
            border-bottom: 1px solid rgba(108, 92, 231, 0.2);
            color: var(--text-secondary);
            font-size: 0.9rem;
        }
        
        .db-row:last-child {
            border-bottom: none;
        }
        
        .db-row:hover {
            background: var(--card-bg);
            color: var(--primary-color);
        }
        
        .cookie-notice {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: var(--darker-bg);
            border: 2px solid var(--primary-color);
            border-radius: 15px;
            padding: 20px;
            max-width: 300px;
            z-index: 1000;
            animation: slideIn 0.5s ease;
        }
        
        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
        
        .code-challenge {
            background: linear-gradient(135deg, var(--dark-bg), var(--darker-bg));
            border: 2px solid var(--accent-color);
            border-radius: 20px;
            padding: 30px;
            position: relative;
            overflow: hidden;
        }
        
        .code-challenge::before {
            content: '⚡ CHALLENGE';
            position: absolute;
            top: 10px;
            right: 10px;
            background: var(--accent-color);
            color: var(--darker-bg);
            padding: 5px 15px;
            border-radius: 20px;
            font-weight: bold;
            font-size: 0.8rem;
        }
        
        .hint-box {
            background: rgba(253, 203, 110, 0.1);
            border-left: 4px solid var(--warning-color);
            padding: 15px;
            margin: 20px 0;
            border-radius: 0 10px 10px 0;
        }
        
        .premium-badge {
            background: linear-gradient(135deg, #f39c12, #e74c3c);
            color: white;
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: bold;
            margin-left: 10px;
        }
    </style>
</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 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>🚀 Intermediate PHP Mastery</h1>
            <p>Level up your PHP skills with forms, sessions, databases, and real-world applications. Get ready for interactive challenges!</p>
            
            <!-- Premium Ad Space -->
            <?php if (function_exists('isPremiumUser') && !isPremiumUser() && function_exists('displayAd')): ?>
            <div style="margin-top: 20px;">
                <?php echo displayAd('header'); ?>
            </div>
            <?php endif; ?>
        </div>
    </header>

    <!-- Main Content -->
    <main class="container">
        <!-- Progress Tracker -->
        <div class="progress-tracker">
            <h3>📊 Intermediate Progress</h3>
            <div class="progress-bar">
                <?php $progressScore = isset($userProgress['intermediate_score']) ? (int)$userProgress['intermediate_score'] : 0; ?>
                <div class="progress-fill" style="width: <?php echo $progressScore; ?>%"></div>
            </div>
            <p>Completed: <?php echo $progressScore; ?>% | Next Level: Advanced PHP</p>
        </div>

        <!-- Lesson 1: Functions and Scope -->
        <?php if (isset($intermediateLessons[0]) && is_array($intermediateLessons[0])): ?>
        <section class="game-section" id="lesson1">
            <h2>1. 📚 Functions and Variable Scope</h2>
            
            <?php if (isset($intermediateLessons[0]['topics']) && is_array($intermediateLessons[0]['topics'])): ?>
            <div style="margin: 20px 0;">
                <h3>🎯 Learning Objectives:</h3>
                <ul style="color: var(--text-secondary); margin-left: 20px;">
                    <?php foreach ($intermediateLessons[0]['topics'] as $topic): ?>
                    <li>✓ <?php echo htmlspecialchars($topic); ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
            <?php endif; ?>
            
            <?php if (isset($intermediateLessons[0]['content'])): ?>
            <div style="margin: 20px 0;">
                <h3>📖 Deep Dive:</h3>
                <p style="color: var(--text-secondary);"><?php echo nl2br(htmlspecialchars($intermediateLessons[0]['content'])); ?></p>
                
                <div class="hint-box">
                    <strong>💡 Pro Tip:</strong> Functions help you write DRY (Don't Repeat Yourself) code. Always consider scope when using variables inside functions!
                </div>
            </div>
            <?php endif; ?>
            
            <div class="code-block">
                <h3>💻 Advanced Function Example:</h3>
                <pre><?php echo htmlspecialchars("<?php
// Global scope
\$counter = 0;

function incrementCounter() {
    // Access global variable
    global \$counter;
    \$counter++;
    
    // Static variable persists between calls
    static \$staticCount = 0;
    \$staticCount++;
    
    return [
        'global' => \$counter,
        'static' => \$staticCount
    ];
}

// Closure with use keyword
\$multiplier = 3;
\$multiply = function(\$num) use (\$multiplier) {
    return \$num * \$multiplier;
};

// Recursive function
function factorial(\$n) {
    if (\$n <= 1) return 1;
    return \$n * factorial(\$n - 1);
}

// Test the functions
echo 'First call: ' . print_r(incrementCounter(), true);
echo 'Second call: ' . print_r(incrementCounter(), true);
echo 'Multiply 5 by 3: ' . \$multiply(5);
echo 'Factorial of 5: ' . factorial(5);
?>"); ?></pre>
            </div>
            
            <div style="display: flex; gap: 10px; margin-top: 20px;">
                <button class="btn" onclick="loadFunctionPlayground()">Try Functions Live</button>
                <a href="?download=functions_examples" class="btn btn-outline">Download Examples</a>
            </div>
        </section>
        <?php endif; ?>

        <!-- Lesson 2: Form Handling Playground -->
        <?php if (isset($intermediateLessons[1]) && is_array($intermediateLessons[1])): ?>
        <section class="game-section" id="lesson2">
            <h2>2. 📝 Form Handling & Validation</h2>
            
            <?php if (isset($intermediateLessons[1]['topics']) && is_array($intermediateLessons[1]['topics'])): ?>
            <div style="margin: 20px 0;">
                <h3>🎯 Learning Objectives:</h3>
                <ul style="color: var(--text-secondary); margin-left: 20px;">
                    <?php foreach ($intermediateLessons[1]['topics'] as $topic): ?>
                    <li>✓ <?php echo htmlspecialchars($topic); ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
            <?php endif; ?>

            <div class="form-playground" id="playground">
                <h3>🎮 Interactive Form Playground</h3>
                <p>Try submitting this form to see PHP form handling in action!</p>
                
                <form method="POST" action="intermediate.php#playground" onsubmit="return validateForm()">
                    <input type="hidden" name="playground_submit" value="1">
                    
                    <div class="form-group">
                        <label for="playground_name">Name *</label>
                        <input type="text" id="playground_name" name="playground_name" required 
                               placeholder="Enter your name" pattern="[A-Za-z ]{2,50}"
                               title="Only letters and spaces, 2-50 characters">
                        <small style="color: var(--text-secondary);">Only letters and spaces allowed</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="playground_email">Email *</label>
                        <input type="email" id="playground_email" name="playground_email" required 
                               placeholder="your@email.com">
                    </div>
                    
                    <div class="form-group">
                        <label for="playground_message">Message *</label>
                        <textarea id="playground_message" name="playground_message" required 
                                  rows="4" placeholder="Type your message here..." 
                                  minlength="10" maxlength="500"></textarea>
                        <small style="color: var(--text-secondary);">10-500 characters</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="playground_topic">Select Topic</label>
                        <select id="playground_topic" name="playground_topic">
                            <option value="general">General Question</option>
                            <option value="functions">Functions</option>
                            <option value="forms">Form Handling</option>
                            <option value="sessions">Sessions</option>
                            <option value="database">Database</option>
                        </select>
                    </div>
                    
                    <div style="display: flex; gap: 10px;">
                        <button type="submit" class="btn">Submit Form</button>
                        <button type="reset" class="btn btn-outline">Reset Form</button>
                    </div>
                </form>
                
                <?php if (isset($_SESSION['playground_result'])): ?>
                <div style="margin-top: 30px; padding: 20px; background: var(--card-bg); border-radius: 10px;">
                    <h4>📨 Last Form Submission:</h4>
                    <pre style="color: var(--text-secondary);"><?php 
                        print_r($_SESSION['playground_result']);
                        unset($_SESSION['playground_result']);
                    ?></pre>
                </div>
                <?php endif; ?>
            </div>
            
            <div class="code-block">
                <h3>💻 Server-side Validation Code:</h3>
                <pre><?php echo htmlspecialchars("<?php
// Secure form handling with validation
if (\$_SERVER['REQUEST_METHOD'] == 'POST') {
    \$errors = [];
    
    // Sanitize and validate inputs
    \$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
    if (!preg_match('/^[A-Za-z ]{2,50}$/', \$name)) {
        \$errors[] = 'Invalid name format';
    }
    
    \$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
    if (!filter_var(\$email, FILTER_VALIDATE_EMAIL)) {
        \$errors[] = 'Invalid email format';
    }
    
    \$message = htmlspecialchars(\$_POST['message'] ?? '');
    if (strlen(\$message) < 10 || strlen(\$message) > 500) {
        \$errors[] = 'Message must be 10-500 characters';
    }
    
    if (empty(\$errors)) {
        // Process valid data
        echo 'Form submitted successfully!';
    } else {
        // Display errors
        foreach (\$errors as \$error) {
            echo '<p class=\"error\">' . \$error . '</p>';
        }
    }
}
?>"); ?></pre>
            </div>
        </section>
        <?php endif; ?>

        <!-- Lesson 3: Sessions & Cookies Demo -->
        <section class="game-section" id="lesson3">
            <h2>3. 🍪 Sessions & Cookies Management</h2>
            
            <div class="session-demo">
                <div class="session-card">
                    <h3>Session Data</h3>
                    <div class="session-value">
                        <?php 
                        if (!isset($_SESSION['visit_count'])) {
                            $_SESSION['visit_count'] = 1;
                        } else {
                            $_SESSION['visit_count']++;
                        }
                        echo isset($_SESSION['visit_count']) ? $_SESSION['visit_count'] : '1';
                        ?>
                    </div>
                    <p>Times you've visited this page</p>
                    <button class="btn btn-outline" onclick="resetSession()">Reset Session</button>
                </div>
                
                <div class="session-card">
                    <h3>Cookie Data</h3>
                    <div class="session-value">
                        <?php
                        if (isset($_COOKIE['user_preference'])) {
                            echo htmlspecialchars($_COOKIE['user_preference']);
                        } else {
                            echo 'Not set';
                        }
                        ?>
                    </div>
                    <p>Your saved preference</p>
                    <select id="cookiePreference" onchange="setCookiePreference()">
                        <option value="light">Light Mode</option>
                        <option value="dark">Dark Mode</option>
                        <option value="auto">Auto</option>
                    </select>
                </div>
                
                <div class="session-card">
                    <h3>Last Activity</h3>
                    <div class="session-value">
                        <?php
                        if (isset($_SESSION['last_active'])) {
                            $lastActive = $_SESSION['last_active'];
                            $minutesAgo = round((time() - $lastActive) / 60);
                            echo $minutesAgo . ' min ago';
                        } else {
                            $_SESSION['last_active'] = time();
                            echo 'Just now';
                        }
                        ?>
                    </div>
                    <p>Update on each page load</p>
                </div>
            </div>
            
            <div class="code-block">
                <h3>💻 Session & Cookie Code:</h3>
                <pre><?php echo htmlspecialchars("<?php
// Start session
session_start();

// Set session variables
\$_SESSION['user_id'] = 123;
\$_SESSION['username'] = 'john_doe';

// Set cookie (expires in 30 days)
setcookie('theme', 'dark', time() + (86400 * 30), '/');

// Check if cookie exists
if (isset(\$_COOKIE['theme'])) {
    \$theme = \$_COOKIE['theme'];
    echo \"Using \$theme theme\";
}

// Session security
session_regenerate_id(true); // Prevent session fixation
?>"); ?></pre>
            </div>
        </section>

        <!-- Interactive Game: Database Query Challenge -->
        <section class="game-section">
            <h2>🎮 Database Query Challenge</h2>
            <p>Write SQL queries to interact with the simulated database!</p>
            
            <div class="database-simulator">
                <div class="db-table">
                    <h4>📋 users</h4>
                    <div class="db-row">1 | John | john@email.com</div>
                    <div class="db-row">2 | Jane | jane@email.com</div>
                    <div class="db-row">3 | Bob | bob@email.com</div>
                    <div class="db-row">4 | Alice | alice@email.com</div>
                    <div class="db-row">5 | Charlie | charlie@email.com</div>
                </div>
                
                <div class="db-table">
                    <h4>📋 products</h4>
                    <div class="db-row">1 | Laptop | 999.99</div>
                    <div class="db-row">2 | Mouse | 29.99</div>
                    <div class="db-row">3 | Keyboard | 79.99</div>
                    <div class="db-row">4 | Monitor | 299.99</div>
                    <div class="db-row">5 | Headphones | 149.99</div>
                </div>
                
                <div class="db-table">
                    <h4>📋 orders</h4>
                    <div class="db-row">1 | 1 | 2024-01-15</div>
                    <div class="db-row">2 | 2 | 2024-01-16</div>
                    <div class="db-row">3 | 3 | 2024-01-17</div>
                    <div class="db-row">4 | 1 | 2024-01-18</div>
                    <div class="db-row">5 | 4 | 2024-01-19</div>
                </div>
            </div>
            
            <div style="margin: 20px 0;">
                <input type="text" id="sqlQuery" placeholder="Enter SQL query (e.g., SELECT * FROM users)" 
                       style="width: 100%; padding: 15px; background: var(--darker-bg); border: 2px solid var(--primary-color); border-radius: 10px; color: var(--text-primary); font-family: 'Courier New', monospace;">
            </div>
            
            <div style="display: flex; gap: 10px; margin-bottom: 20px;">
                <button class="btn" onclick="executeQuery()">Execute Query</button>
                <button class="btn btn-outline" onclick="showHint()">Show Hint</button>
                <button class="btn btn-outline" onclick="resetQuery()">Clear</button>
            </div>
            
            <div id="queryResult" style="background: var(--darker-bg); padding: 20px; border-radius: 10px; min-height: 100px; border: 1px solid var(--primary-color);">
                Query result will appear here...
            </div>
            
            <div id="queryHint" class="hint-box" style="display: none;">
                <strong>🔍 Hint:</strong> Try these queries:<br>
                - SELECT * FROM users<br>
                - SELECT name, email FROM users WHERE id > 2<br>
                - SELECT * FROM products WHERE price < 100
            </div>
        </section>

        <!-- File Upload Simulator -->
        <section class="game-section">
            <h2>📁 File Upload & Handling</h2>
            
            <div class="file-upload-area" id="fileUploadArea" onclick="document.getElementById('fileInput').click()">
                <input type="file" id="fileInput" style="display: none;" onchange="handleFileSelect(this)">
                <span style="font-size: 3rem;">📂</span>
                <h3>Drop files here or click to upload</h3>
                <p style="color: var(--text-secondary);">Supports: .txt, .php, .html, .css, .js (max 2MB)</p>
            </div>
            
            <div id="fileInfo" style="margin-top: 20px; padding: 20px; background: var(--card-bg); border-radius: 10px; display: none;">
                <h4>File Information:</h4>
                <div id="fileDetails"></div>
                <button class="btn" style="margin-top: 10px;" onclick="simulateUpload()">Simulate Upload</button>
            </div>
            
            <div class="code-block">
                <h4>💻 PHP File Upload Code:</h4>
                <pre><?php echo htmlspecialchars("<?php
if (\$_SERVER['REQUEST_METHOD'] == 'POST' && isset(\$_FILES['file'])) {
    \$targetDir = 'uploads/';
    \$fileName = basename(\$_FILES['file']['name']);
    \$targetFile = \$targetDir . \$fileName;
    \$fileType = strtolower(pathinfo(\$targetFile, PATHINFO_EXTENSION));
    
    // Check file size (2MB max)
    if (\$_FILES['file']['size'] > 2000000) {
        echo 'File too large!';
        exit;
    }
    
    // Allow certain file types
    \$allowedTypes = ['txt', 'php', 'html', 'css', 'js'];
    if (!in_array(\$fileType, \$allowedTypes)) {
        echo 'File type not allowed!';
        exit;
    }
    
    // Upload file
    if (move_uploaded_file(\$_FILES['file']['tmp_name'], \$targetFile)) {
        echo 'File uploaded successfully!';
    } else {
        echo 'Upload failed!';
    }
}
?>"); ?></pre>
            </div>
        </section>

        <!-- Intermediate Quiz Game -->
        <section class="quiz-container">
            <h2>📝 Intermediate Level Quiz</h2>
            <p>Test your intermediate PHP knowledge!</p>
            
            <div id="intermediateQuiz">
                <?php
                $questions = [
                    [
                        'question' => 'What is the correct way to declare a static variable inside a function?',
                        'options' => ['static $var;', 'STATIC $var;', '$static var;', 'var static $var;'],
                        'correct' => 0
                    ],
                    [
                        'question' => 'Which superglobal is used to access session variables?',
                        'options' => ['$_SESSION', '$_COOKIE', '$_SERVER', '$_ENV'],
                        'correct' => 0
                    ],
                    [
                        'question' => 'What does PDO stand for?',
                        'options' => ['PHP Data Objects', 'Personal Database Option', 'Primary Data Output', 'PHP Database Operator'],
                        'correct' => 0
                    ],
                    [
                        'question' => 'Which function is used to sanitize user input for database queries?',
                        'options' => ['mysqli_real_escape_string()', 'htmlspecialchars()', 'strip_tags()', 'trim()'],
                        'correct' => 0
                    ],
                    [
                        'question' => 'How do you set a cookie that expires in 1 hour?',
                        'options' => ['setcookie("name", "value", time()+3600)', 'setcookie("name", "value", 3600)', 'cookie("name", "value", time()+3600)', 'create_cookie("name", "value", 3600)'],
                        'correct' => 0
                    ]
                ];
                
                $randomIndex = array_rand($questions);
                $currentQuestion = $questions[$randomIndex];
                ?>
                <div class="question"><?php echo htmlspecialchars($currentQuestion['question']); ?></div>
                <div class="options" id="quizOptions">
                    <?php foreach ($currentQuestion['options'] as $optIndex => $option): ?>
                    <button class="option-btn" onclick="checkIntermediateAnswer(<?php echo (int)$optIndex; ?>, <?php echo (int)$currentQuestion['correct']; ?>, this)">
                        <?php echo htmlspecialchars($option); ?>
                    </button>
                    <?php endforeach; ?>
                </div>
            </div>
            
            <div id="intermediateQuizFeedback" style="text-align: center; margin: 20px 0;"></div>
            
            <div style="display: flex; gap: 10px; justify-content: center;">
                <button class="btn" onclick="loadNewQuestion()">Next Question</button>
                <button class="btn btn-outline" onclick="showQuizScore()">Show Score</button>
            </div>
        </section>

        <!-- Code Challenge: Build a Login System -->
        <section class="code-challenge">
            <h2>⚡ Code Challenge: Build a Login System</h2>
            <p>Using sessions and form handling, create a simple login system!</p>
            
            <div style="margin: 20px 0;">
                <h4>Requirements:</h4>
                <ul style="color: var(--text-secondary);">
                    <li>Create a login form with username and password</li>
                    <li>Validate inputs (username: 3-20 chars, password: min 6 chars)</li>
                    <li>Store login status in session</li>
                    <li>Create a logout button</li>
                    <li>Show different content for logged-in users</li>
                </ul>
            </div>
            
            <div class="hint-box">
                <strong>💡 Starter Code:</strong> Check the example below for hints!
            </div>
            
            <div class="code-block">
                <pre><?php echo htmlspecialchars("<?php
session_start();

// Check if form submitted
if (\$_SERVER['REQUEST_METHOD'] == 'POST') {
    \$username = \$_POST['username'] ?? '';
    \$password = \$_POST['password'] ?? '';
    
    // Validate (in real app, check against database)
    if (\$username === 'admin' && \$password === 'password123') {
        \$_SESSION['logged_in'] = true;
        \$_SESSION['username'] = \$username;
        header('Location: dashboard.php');
        exit;
    } else {
        \$error = 'Invalid credentials';
    }
}

// Check if user is logged in
if (isset(\$_SESSION['logged_in']) && \$_SESSION['logged_in'] === true) {
    echo 'Welcome, ' . \$_SESSION['username'] . '!';
    echo '<br><a href=\"?logout\">Logout</a>';
}

// Handle logout
if (isset(\$_GET['logout'])) {
    session_destroy();
    header('Location: ' . \$_SERVER['PHP_SELF']);
    exit;
}
?>"); ?></pre>
            </div>
            
            <div style="text-align: center; margin-top: 20px;">
                <button class="btn" onclick="showSolution()">Show Solution</button>
                <a href="?download=login_system" class="btn btn-outline">Download Template</a>
            </div>
            
            <div id="solution" style="display: none; margin-top: 20px; background: var(--darker-bg); padding: 20px; border-radius: 10px;">
                <h4>📝 Complete Login System Solution:</h4>
                <pre><?php echo htmlspecialchars("<?php
// login.php - Complete login system
session_start();

// Database connection (simulated)
\$validUsers = [
    'admin' => password_hash('password123', PASSWORD_DEFAULT)
];

// Handle login
if (\$_SERVER['REQUEST_METHOD'] == 'POST' && isset(\$_POST['login'])) {
    \$username = htmlspecialchars(\$_POST['username'] ?? '');
    \$password = \$_POST['password'] ?? '';
    \$errors = [];
    
    // Validation
    if (strlen(\$username) < 3 || strlen(\$username) > 20) {
        \$errors[] = 'Username must be 3-20 characters';
    }
    
    if (strlen(\$password) < 6) {
        \$errors[] = 'Password must be at least 6 characters';
    }
    
    // Check credentials
    if (empty(\$errors)) {
        if (isset(\$validUsers[\$username]) && 
            password_verify(\$password, \$validUsers[\$username])) {
            \$_SESSION['user'] = \$username;
            header('Location: dashboard.php');
            exit;
        } else {
            \$errors[] = 'Invalid username or password';
        }
    }
}

// Handle logout
if (isset(\$_GET['logout'])) {
    session_destroy();
    header('Location: login.php');
    exit;
}
?>"); ?></pre>
            </div>
        </section>

        <!-- Download Resources Section -->
        <section class="downloader-section">
            <h3>📥 Intermediate Resources</h3>
            <p>Download practice files, cheat sheets, and project templates</p>
            
            <div class="download-buttons">
                <a href="?download=intermediate_notes" class="btn btn-outline">📘 Complete Notes</a>
                <a href="?download=form_handling" class="btn btn-outline">📝 Form Examples</a>
                <a href="?download=session_examples" class="btn btn-outline">🍪 Session Code</a>
                <a href="?download=database_queries" class="btn btn-outline">🗄️ SQL Examples</a>
                <a href="?download=intermediate_project" class="btn btn-outline">🚀 Full Project</a>
            </div>
        </section>

        <?php
        // Handle downloads
        if (isset($_GET['download'])) {
            $download = $_GET['download'];
            $files = [
                'functions_examples' => "<?php\n// PHP FUNCTIONS EXAMPLES - Intermediate Level\n\n// 1. Basic Function with Type Hinting\nfunction addNumbers(int \$a, int \$b): int {\n    return \$a + \$b;\n}\n\n// 2. Function with Default Parameters\nfunction greet(string \$name = 'Guest'): string {\n    return \"Hello, \$name!\";\n}\n\n// 3. Variable Functions (Closures)\n\$multiplier = 5;\n\$multiply = function(\$num) use (\$multiplier) {\n    return \$num * \$multiplier;\n};\n\n// 4. Recursive Function\nfunction fibonacci(\$n) {\n    if (\$n <= 1) return \$n;\n    return fibonacci(\$n - 1) + fibonacci(\$n - 2);\n}\n\n// 5. Static Variables\nfunction counter() {\n    static \$count = 0;\n    return ++\$count;\n}\n?>",
                
                'form_handling' => "<?php\n// PHP FORM HANDLING - Complete Examples\n\nclass FormHandler {\n    private \$errors = [];\n    \n    public function validateForm(\$postData) {\n        \$name = filter_var(\$postData['name'] ?? '', FILTER_SANITIZE_STRING);\n        \$email = filter_var(\$postData['email'] ?? '', FILTER_SANITIZE_EMAIL);\n        \n        if (strlen(\$name) < 2) {\n            \$this->errors[] = 'Name must be at least 2 characters';\n        }\n        \n        if (!filter_var(\$email, FILTER_VALIDATE_EMAIL)) {\n            \$this->errors[] = 'Invalid email format';\n        }\n        \n        return empty(\$this->errors);\n    }\n    \n    public function getErrors() {\n        return \$this->errors;\n    }\n}\n?>",
                
                'session_examples' => "<?php\n// PHP SESSION MANAGEMENT\n\nclass SessionManager {\n    public function __construct() {\n        if (session_status() == PHP_SESSION_NONE) {\n            session_start();\n        }\n    }\n    \n    public function set(\$key, \$value) {\n        \$_SESSION[\$key] = \$value;\n    }\n    \n    public function get(\$key, \$default = null) {\n        return \$_SESSION[\$key] ?? \$default;\n    }\n    \n    public function destroy() {\n        session_destroy();\n    }\n}\n\n// Cookie Handling\nclass CookieManager {\n    public function set(\$name, \$value, \$days = 30) {\n        setcookie(\$name, \$value, time() + (\$days * 86400), '/', '', true, true);\n    }\n    \n    public function get(\$name, \$default = null) {\n        return \$_COOKIE[\$name] ?? \$default;\n    }\n}\n?>",
                
                'database_queries' => "<?php\n// PDO Database Examples\n\nclass Database {\n    private \$pdo;\n    \n    public function __construct() {\n        \$dsn = 'mysql:host=localhost;dbname=test;charset=utf8mb4';\n        \$options = [\n            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,\n            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,\n            PDO::ATTR_EMULATE_PREPARES => false\n        ];\n        \n        try {\n            \$this->pdo = new PDO(\$dsn, 'username', 'password', \$options);\n        } catch (PDOException \$e) {\n            die('Connection failed: ' . \$e->getMessage());\n        }\n    }\n    \n    public function query(\$sql, \$params = []) {\n        \$stmt = \$this->pdo->prepare(\$sql);\n        \$stmt->execute(\$params);\n        return \$stmt;\n    }\n}\n?>",
                
                'intermediate_notes' => "INTERMEDIATE PHP NOTES\n\n1. Functions\n- Functions are reusable blocks of code\n- Can have parameters and return values\n- Variable scope: global, local, static\n- Closures and anonymous functions\n\n2. Form Handling\n- GET vs POST methods\n- Form validation and sanitization\n- File uploads\n- CSRF protection\n\n3. Sessions & Cookies\n- Session management\n- Cookie handling\n- Security best practices\n\n4. Databases\n- PDO connections\n- Prepared statements\n- CRUD operations\n- Transactions",
                
                'login_system' => "Complete login system files are available in the full project download."
            ];
            
            if (isset($files[$download])) {
                header('Content-Type: text/plain');
                header('Content-Disposition: attachment; filename="' . $download . '.txt"');
                echo $files[$download];
                exit;
            }
        }
        ?>

        <!-- Premium Content Teaser -->
        <?php if (function_exists('isPremiumUser') && !isPremiumUser()): ?>
        <section class="game-section" style="text-align: center;">
            <h2>💎 Unlock Advanced Features</h2>
            <p>Get access to premium content including video tutorials, source code, and certification!</p>
            <div style="margin-top: 20px;">
                <a href="#" class="btn">Upgrade to Premium</a>
                <a href="#" class="btn btn-outline">Learn More</a>
            </div>
        </section>
        <?php endif; ?>
    </main>

    <!-- Footer -->
    <footer class="footer">
        <div class="container">
            <div class="footer-content">
                <div class="footer-section">
                    <h4>Intermediate Level</h4>
                    <p>Master PHP forms, sessions, databases, and more with our interactive tutorials.</p>
                </div>
                
                <div class="footer-section">
                    <h4>Quick Navigation</h4>
                    <ul>
                        <li><a href="#lesson1">Functions & Scope</a></li>
                        <li><a href="#lesson2">Form Handling</a></li>
                        <li><a href="#lesson3">Sessions & Cookies</a></li>
                    </ul>
                </div>
                
                <div class="footer-section">
                    <h4>Connect With Me</h4>
                    <div class="social-links">
                        <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>
                        <a href="<?php echo htmlspecialchars($socialLinks['twitter']); ?>" 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='M23.953 4.57a10 10 0 01-2.825.775 4.958 4.958 0 002.163-2.723c-.951.555-2.005.959-3.127 1.184a4.92 4.92 0 00-8.384 4.482C7.69 8.095 4.067 6.13 1.64 3.162a4.822 4.822 0 00-.666 2.475c0 1.71.87 3.213 2.188 4.096a4.904 4.904 0 01-2.228-.616v.06a4.923 4.923 0 003.946 4.827 4.996 4.996 0 01-2.212.085 4.937 4.937 0 004.604 3.417 9.868 9.868 0 01-6.102 2.104c-.39 0-.779-.023-1.17-.067a13.995 13.995 0 0021.707-3.645 13.94 13.94 0 001.54-5.872c0-.212-.005-.424-.015-.636.997-.723 1.856-1.616 2.534-2.636z'/%3E%3C/svg%3E" alt="Twitter">
                            <span class="tooltip-text">Twitter</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 echo defined('SITE_NAME') ? SITE_NAME : 'PHP Webdesign Fundamentals'; ?> - Intermediate Level</p>
            </div>
        </div>
    </footer>

    <!-- Cookie Notice -->
    <div class="cookie-notice" id="cookieNotice" style="display: none;">
        <h4>🍪 Cookie Notice</h4>
        <p>We use cookies to enhance your learning experience. By continuing, you agree to our use of cookies.</p>
        <div style="display: flex; gap: 10px; margin-top: 15px;">
            <button class="btn" onclick="acceptCookies()">Accept</button>
            <button class="btn btn-outline" onclick="declineCookies()">Decline</button>
        </div>
    </div>

    <script>
        // Check if cookies were already accepted
        if (!document.cookie.includes('cookies_accepted')) {
            document.getElementById('cookieNotice').style.display = 'block';
        }
        
        function acceptCookies() {
            document.cookie = "cookies_accepted=true; max-age=" + (60*60*24*30) + "; path=/";
            document.getElementById('cookieNotice').style.display = 'none';
        }
        
        function declineCookies() {
            document.getElementById('cookieNotice').style.display = 'none';
        }
        
        // Function to load function playground (FIXED - No PHP code in string)
        function loadFunctionPlayground() {
            const codeArea = document.getElementById('php-code');
            if (!codeArea) {
                // Create a textarea if it doesn't exist
                const playground = document.querySelector('.game-section');
                if (playground) {
                    const newTextarea = document.createElement('textarea');
                    newTextarea.id = 'php-code';
                    newTextarea.rows = 10;
                    newTextarea.style.width = '100%';
                    newTextarea.style.background = 'var(--darker-bg)';
                    newTextarea.style.color = 'var(--text-primary)';
                    newTextarea.style.border = '1px solid var(--primary-color)';
                    newTextarea.style.borderRadius = '10px';
                    newTextarea.style.padding = '15px';
                    newTextarea.style.fontFamily = 'Courier New, monospace';
                    newTextarea.value = '// Select a function example to load';
                    playground.appendChild(newTextarea);
                }
            }
            
            alert('Function examples loaded! Check the code below.');
        }
        
        // Function to handle file upload
        function handleFileSelect(input) {
            const file = input.files[0];
            if (file) {
                const fileInfo = document.getElementById('fileInfo');
                const fileDetails = document.getElementById('fileDetails');
                
                if (fileInfo && fileDetails) {
                    fileDetails.innerHTML = `
                        <p><strong>Name:</strong> ${file.name}</p>
                        <p><strong>Size:</strong> ${(file.size / 1024).toFixed(2)} KB</p>
                        <p><strong>Type:</strong> ${file.type || 'Unknown'}</p>
                        <p><strong>Last Modified:</strong> ${new Date(file.lastModified).toLocaleString()}</p>
                    `;
                    
                    fileInfo.style.display = 'block';
                }
            }
        }
        
        // Drag and drop functionality
        const dropArea = document.getElementById('fileUploadArea');
        if (dropArea) {
            ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                dropArea.addEventListener(eventName, preventDefaults, false);
            });
            
            function preventDefaults(e) {
                e.preventDefault();
                e.stopPropagation();
            }
            
            ['dragenter', 'dragover'].forEach(eventName => {
                dropArea.addEventListener(eventName, function() {
                    dropArea.classList.add('dragover');
                }, false);
            });
            
            ['dragleave', 'drop'].forEach(eventName => {
                dropArea.addEventListener(eventName, function() {
                    dropArea.classList.remove('dragover');
                }, false);
            });
            
            dropArea.addEventListener('drop', function(e) {
                const dt = e.dataTransfer;
                const files = dt.files;
                
                if (files.length > 0) {
                    const fileInput = document.getElementById('fileInput');
                    if (fileInput) {
                        fileInput.files = files;
                        handleFileSelect({ files: files });
                    }
                }
            }, false);
        }
        
        function simulateUpload() {
            alert('📁 File upload simulated! In a real environment, this would upload to the server.');
        }
        
        // Database query simulator
        function executeQuery() {
            const queryInput = document.getElementById('sqlQuery');
            const result = document.getElementById('queryResult');
            
            if (!queryInput || !result) return;
            
            const query = queryInput.value.toLowerCase();
            
            // Simulate query results
            if (query.includes('select * from users')) {
                result.innerHTML = `
                    <table style="width: 100%; border-collapse: collapse;">
                        <tr style="border-bottom: 2px solid var(--primary-color);">
                            <th style="padding: 10px; text-align: left;">id</th>
                            <th style="padding: 10px; text-align: left;">name</th>
                            <th style="padding: 10px; text-align: left;">email</th>
                        </tr>
                        <tr><td>1</td><td>John</td><td>john@email.com</td></tr>
                        <tr><td>2</td><td>Jane</td><td>jane@email.com</td></tr>
                        <tr><td>3</td><td>Bob</td><td>bob@email.com</td></tr>
                        <tr><td>4</td><td>Alice</td><td>alice@email.com</td></tr>
                        <tr><td>5</td><td>Charlie</td><td>charlie@email.com</td></tr>
                    </table>
                `;
            } else if (query.includes('select * from products')) {
                result.innerHTML = `
                    <table style="width: 100%; border-collapse: collapse;">
                        <tr style="border-bottom: 2px solid var(--primary-color);">
                            <th style="padding: 10px; text-align: left;">id</th>
                            <th style="padding: 10px; text-align: left;">name</th>
                            <th style="padding: 10px; text-align: left;">price</th>
                        </tr>
                        <tr><td>1</td><td>Laptop</td><td>$999.99</td></tr>
                        <tr><td>2</td><td>Mouse</td><td>$29.99</td></tr>
                        <tr><td>3</td><td>Keyboard</td><td>$79.99</td></tr>
                        <tr><td>4</td><td>Monitor</td><td>$299.99</td></tr>
                        <tr><td>5</td><td>Headphones</td><td>$149.99</td></tr>
                    </table>
                `;
            } else {
                result.innerHTML = '🔍 Query executed. Try: SELECT * FROM users';
            }
        }
        
        function showHint() {
            const hint = document.getElementById('queryHint');
            if (hint) hint.style.display = 'block';
        }
        
        function resetQuery() {
            const queryInput = document.getElementById('sqlQuery');
            const result = document.getElementById('queryResult');
            const hint = document.getElementById('queryHint');
            
            if (queryInput) queryInput.value = '';
            if (result) result.innerHTML = 'Query result will appear here...';
            if (hint) hint.style.display = 'none';
        }
        
        // Quiz functions
        let quizScore = 0;
        
        function checkIntermediateAnswer(selected, correct, element) {
            const options = document.querySelectorAll('#quizOptions .option-btn');
            const feedback = document.getElementById('intermediateQuizFeedback');
            
            if (!options.length || !feedback) return;
            
            options.forEach(opt => opt.classList.remove('selected', 'correct', 'wrong'));
            
            if (selected === correct) {
                element.classList.add('correct');
                feedback.innerHTML = '✅ Correct! Great job!';
                feedback.style.color = 'var(--success-color)';
                quizScore++;
            } else {
                element.classList.add('wrong');
                if (options[correct]) {
                    options[correct].classList.add('correct');
                }
                feedback.innerHTML = '❌ Not quite. The correct answer is highlighted.';
                feedback.style.color = 'var(--error-color)';
            }
        }
        
        function loadNewQuestion() {
            location.reload();
        }
        
        function showQuizScore() {
            alert(`Your current score: ${quizScore}/5`);
        }
        
        // Session functions
        function resetSession() {
            fetch('intermediate.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: 'reset_session=1'
            }).then(() => location.reload());
        }
        
        function setCookiePreference() {
            const select = document.getElementById('cookiePreference');
            if (!select) return;
            
            const preference = select.value;
            document.cookie = `user_preference=${preference}; max-age=${60*60*24*30}; path=/`;
            alert(`Cookie set! Preference saved as: ${preference}`);
            location.reload();
        }
        
        // Show solution for challenge
        function showSolution() {
            const solution = document.getElementById('solution');
            if (solution) {
                if (solution.style.display === 'none' || solution.style.display === '') {
                    solution.style.display = 'block';
                } else {
                    solution.style.display = 'none';
                }
            }
        }
        
        // Copy code functionality
        function copyCode(button) {
            const pre = button.previousElementSibling;
            if (pre && pre.innerText) {
                navigator.clipboard.writeText(pre.innerText).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>