<?php
// Initialize variables with default values
$advancedLessons = isset($advancedLessons) ? $advancedLessons : [];
$navItems = isset($navItems) ? $navItems : [];
$socialLinks = isset($socialLinks) ? $socialLinks : [
    'github' => '#',
        'twitter' => '#',
    'youtube' => '#'
];

// Check premium access for advanced content
function isPremiumUser() {
    return isset($_SESSION['premium_user']) && $_SESSION['premium_user'] === true;
}

// 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('advanced', $questionIndex, $answer);
    }
    
    if ($correct && isset($db) && method_exists($db, 'saveQuizResult')) {
        $db->saveQuizResult('advanced', 100);
        $db->updateScore('advanced', 100);
    }
    
    header('Content-Type: application/json');
    echo json_encode(['correct' => $correct]);
    exit;
}

// Handle OOP class builder submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['build_class'])) {
    $className = isset($_POST['class_name']) ? preg_replace('/[^a-zA-Z0-9_]/', '', $_POST['class_name']) : 'MyClass';
    $properties = isset($_POST['properties']) ? explode(',', $_POST['properties']) : [];
    $methods = isset($_POST['methods']) ? explode(',', $_POST['methods']) : [];
    
    $_SESSION['built_class'] = [
        'className' => $className,
        'properties' => array_map('trim', $properties),
        'methods' => array_map('trim', $methods)
    ];
    header('Location: advanced.php#oop-builder');
    exit;
}

// Start session if not already started
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Define advanced lessons if not defined in config
if (empty($advancedLessons)) {
    $advancedLessons = [
        [
            'title' => 'Object-Oriented PHP Deep Dive',
            'content' => 'Master OOP concepts including abstract classes, interfaces, traits, dependency injection, and advanced design principles. Learn how to build scalable, maintainable applications using object-oriented architecture.',
            'topics' => ['Classes & Objects', 'Inheritance', 'Polymorphism', 'Encapsulation', 'Abstract Classes', 'Interfaces', 'Traits', 'Dependency Injection', 'Namespaces', 'Magic Methods'],
            'code' => "<?php\n// Advanced OOP Example with Traits, Interfaces, and Abstract Classes\n\ninterface Repository {\n    public function find(\$id);\n    public function save(\$entity);\n}\n\ninterface Cacheable {\n    public function getCacheKey(): string;\n    public function getCacheTTL(): int;\n}\n\nabstract class BaseRepository {\n    protected \$db;\n    \n    public function __construct(PDO \$db) {\n        \$this->db = \$db;\n    }\n    \n    protected function beginTransaction() {\n        \$this->db->beginTransaction();\n    }\n    \n    protected function commit() {\n        \$this->db->commit();\n    }\n    \n    protected function rollback() {\n        \$this->db->rollBack();\n    }\n}\n\ntrait Timestampable {\n    protected \$createdAt;\n    protected \$updatedAt;\n    \n    public function setTimestamps(): void {\n        \$this->createdAt = new DateTime();\n        \$this->updatedAt = new DateTime();\n    }\n}\n\nclass User extends BaseRepository implements Cacheable {\n    use Timestampable;\n    \n    private \$id;\n    private \$name;\n    private \$email;\n    \n    public function __construct(array \$data = []) {\n        \$this->hydrate(\$data);\n        \$this->setTimestamps();\n    }\n    \n    private function hydrate(array \$data): void {\n        foreach (\$data as \$key => \$value) {\n            if (property_exists(\$this, \$key)) {\n                \$this->\$key = \$value;\n            }\n        }\n    }\n    \n    public function getCacheKey(): string {\n        return 'user.' . \$this->id;\n    }\n    \n    public function getCacheTTL(): int {\n        return 3600;\n    }\n    \n    public function find(\$id) {\n        // Implementation\n    }\n    \n    public function save(\$entity) {\n        // Implementation\n    }\n}\n?>"
        ],
        [
            'title' => 'Design Patterns Masterclass',
            'content' => 'Learn 23 essential design patterns including creational, structural, and behavioral patterns. Understand when and how to apply each pattern with real-world examples.',
            'topics' => ['Singleton', 'Factory', 'Abstract Factory', 'Builder', 'Prototype', 'Adapter', 'Bridge', 'Composite', 'Decorator', 'Facade', 'Flyweight', 'Proxy', 'Chain of Responsibility', 'Command', 'Iterator', 'Mediator', 'Memento', 'Observer', 'State', 'Strategy', 'Template Method', 'Visitor'],
            'code' => "<?php\n// Design Patterns Examples\n\n// 1. Singleton Pattern\nclass DatabaseConnection {\n    private static \$instance = null;\n    private \$connection;\n    \n    private function __construct() {\n        \$this->connection = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');\n    }\n    \n    public static function getInstance() {\n        if (self::\$instance === null) {\n            self::\$instance = new self();\n        }\n        return self::\$instance;\n    }\n    \n    public function getConnection() {\n        return \$this->connection;\n    }\n}\n\n// 2. Factory Pattern\ninterface Product {\n    public function getName(): string;\n    public function getPrice(): float;\n}\n\nclass ProductFactory {\n    public function create(string \$type, array \$data): Product {\n        switch(\$type) {\n            case 'book':\n                return new Book(\$data['title'], \$data['price']);\n            case 'electronic':\n                return new Electronic(\$data['name'], \$data['price'], \$data['warranty']);\n            default:\n                throw new InvalidArgumentException('Unknown product type');\n        }\n    }\n}\n\n// 3. Observer Pattern\ninterface Observer {\n    public function update(string \$event, \$data = null): void;\n}\n\nclass User implements Subject {\n    private \$observers = [];\n    private \$name;\n    \n    public function attach(Observer \$observer): void {\n        \$this->observers[] = \$observer;\n    }\n    \n    public function notify(string \$event, \$data = null): void {\n        foreach (\$this->observers as \$observer) {\n            \$observer->update(\$event, \$data);\n        }\n    }\n    \n    public function updateProfile(array \$data): void {\n        if (isset(\$data['name'])) {\n            \$this->name = \$data['name'];\n        }\n        \$this->notify('profile.updated', \$this);\n    }\n}\n?>"
        ],
        [
            'title' => 'Advanced Security Practices',
            'content' => 'Implement enterprise-grade security measures including encryption, authentication, authorization, and protection against common vulnerabilities.',
            'topics' => ['SQL Injection Prevention', 'XSS Protection', 'CSRF Tokens', 'Password Hashing', 'Session Security', 'Input Validation', 'File Upload Security', 'API Security', 'OAuth2', 'JWT', 'Rate Limiting', 'Security Headers', 'Encryption', 'Two-Factor Authentication'],
            'code' => "<?php\n// Advanced Security Implementation\n\nclass SecurityManager {\n    // SQL Injection Prevention\n    public static function safeQuery(PDO \$pdo, string \$sql, array \$params = []): PDOStatement {\n        \$stmt = \$pdo->prepare(\$sql);\n        foreach (\$params as \$key => \$value) {\n            \$type = is_int(\$value) ? PDO::PARAM_INT : PDO::PARAM_STR;\n            \$stmt->bindValue(is_int(\$key) ? \$key + 1 : \$key, \$value, \$type);\n        }\n        \$stmt->execute();\n        return \$stmt;\n    }\n    \n    // Password Handling\n    public static function hashPassword(string \$password): string {\n        return password_hash(\$password, PASSWORD_BCRYPT, ['cost' => 12]);\n    }\n    \n    public static function verifyPassword(string \$password, string \$hash): bool {\n        return password_verify(\$password, \$hash);\n    }\n    \n    // Input Validation\n    public static function validateEmail(string \$email): bool {\n        return filter_var(\$email, FILTER_VALIDATE_EMAIL) !== false;\n    }\n    \n    public static function sanitizeFilename(string \$filename): string {\n        \$filename = str_replace(['../', '..\\\\', './', '.\\\\'], '', \$filename);\n        return preg_replace('/[^a-zA-Z0-9_\\-\\.]/', '', \$filename);\n    }\n    \n    // Security Headers\n    public static function setSecurityHeaders(): void {\n        header('X-Frame-Options: DENY');\n        header('X-XSS-Protection: 1; mode=block');\n        header('X-Content-Type-Options: nosniff');\n        header('Referrer-Policy: strict-origin-when-cross-origin');\n        header('Content-Security-Policy: default-src \\'self\\'; script-src \\'self\\' \\'unsafe-inline\\'; style-src \\'self\\' \\'unsafe-inline\\';');\n        header('Strict-Transport-Security: max-age=31536000; includeSubDomains');\n    }\n}\n?>"
        ]
    ];
}

// Handle file downloads
if (isset($_GET['download'])) {
    $download = $_GET['download'];
    
    $advancedFiles = [
        'oop_masterclass' => "<?php\n// Complete OOP Masterclass Code\n// This file contains advanced OOP examples\n\n" . $advancedLessons[0]['code'],
        'design_patterns' => "<?php\n// Design Patterns Implementation\n// Complete design patterns examples\n\n" . $advancedLessons[1]['code'],
        'security_guide' => "<?php\n// Advanced Security Guide\n// Complete security implementation\n\n" . $advancedLessons[2]['code']
    ];
    
    if (isset($advancedFiles[$download])) {
        $content = $advancedFiles[$download];
        $filename = $download . '.php';
        
        header('Content-Type: text/plain');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Content-Length: ' . strlen($content));
        echo $content;
        exit;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Advanced PHP - PHP Web Fundamentals</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 30px;
            text-align: center;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        }

        .header h1 {
            color: #2c3e50;
            font-size: 2.5em;
            margin-bottom: 10px;
        }

        .header p {
            color: #7f8c8d;
            font-size: 1.2em;
        }

        .premium-banner {
            background: linear-gradient(45deg, #f39c12, #e74c3c);
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 30px;
            text-align: center;
        }

        .lesson-card {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s ease;
        }

        .lesson-card:hover {
            transform: translateY(-5px);
        }

        .lesson-title {
            color: #2c3e50;
            font-size: 1.8em;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .lesson-content {
            color: #555;
            margin-bottom: 20px;
            line-height: 1.8;
        }

        .topics-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 10px;
            margin-bottom: 20px;
        }

        .topic-tag {
            background: #3498db;
            color: white;
            padding: 8px 15px;
            border-radius: 20px;
            font-size: 0.9em;
            text-align: center;
        }

        .code-block {
            background: #2c3e50;
            color: #ecf0f1;
            padding: 20px;
            border-radius: 10px;
            overflow-x: auto;
            font-family: 'Courier New', monospace;
            margin: 20px 0;
        }

        .btn {
            display: inline-block;
            padding: 12px 25px;
            background: #3498db;
            color: white;
            text-decoration: none;
            border-radius: 25px;
            transition: all 0.3s ease;
            border: none;
            cursor: pointer;
            font-size: 1em;
        }

        .btn:hover {
            background: #2980b9;
            transform: translateY(-2px);
        }

        .btn-premium {
            background: linear-gradient(45deg, #f39c12, #e74c3c);
        }

        .btn-premium:hover {
            background: linear-gradient(45deg, #e67e22, #c0392b);
        }

        .quiz-section {
            background: #ecf0f1;
            padding: 20px;
            border-radius: 10px;
            margin: 20px 0;
        }

        .quiz-question {
            font-weight: bold;
            margin-bottom: 15px;
        }

        .quiz-options {
            display: grid;
            gap: 10px;
        }

        .quiz-option {
            padding: 10px;
            background: white;
            border: 2px solid #bdc3c7;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .quiz-option:hover {
            border-color: #3498db;
            background: #ebf3fd;
        }

        .footer {
            background: rgba(44, 62, 80, 0.95);
            color: white;
            text-align: center;
            padding: 30px;
            border-radius: 15px;
            margin-top: 50px;
        }

        .social-links {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-top: 20px;
        }

        .social-links a {
            color: white;
            font-size: 1.5em;
            transition: color 0.3s ease;
        }

        .social-links a:hover {
            color: #3498db;
        }

        @media (max-width: 768px) {
            .container {
                padding: 10px;
            }
            
            .header h1 {
                font-size: 2em;
            }
            
            .lesson-card {
                padding: 20px;
            }
            
            .topics-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1><i class="fas fa-rocket"></i> Advanced PHP Architecture</h1>
            <p>Master object-oriented programming, design patterns, security, and high-performance PHP applications.</p>
        </div>

        <?php if (!isPremiumUser()): ?>
        <div class="premium-banner">
            <h2><i class="fas fa-star"></i> Unlock Full Advanced Content</h2>
            <p>One-time payment of ₦1,500 only!</p>
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; margin: 20px 0;">
                <div>
                    <i class="fas fa-book" style="font-size: 2em; margin-bottom: 10px;"></i>
                    <h3>20+ Advanced Lessons</h3>
                    <p>OOP, Design Patterns, Security, MVC, API, Performance</p>
                </div>
                <div>
                    <i class="fas fa-gamepad" style="font-size: 2em; margin-bottom: 10px;"></i>
                    <h3>15+ Interactive Games</h3>
                    <p>Learn through play with pattern matching, security challenges</p>
                </div>
                <div>
                    <i class="fas fa-code" style="font-size: 2em; margin-bottom: 10px;"></i>
                    <h3>100+ Exercises</h3>
                    <p>Practice with real-world coding challenges</p>
                </div>
                <div>
                    <i class="fas fa-certificate" style="font-size: 2em; margin-bottom: 10px;"></i>
                    <h3>Certificate</h3>
                    <p>Industry-recognized certification upon completion</p>
                </div>
            </div>
            <a href="#" class="btn btn-premium">Get Premium Access Now</a>
            <div style="margin-top: 20px; font-size: 0.9em;">
                <p><strong>Bank Transfer Option:</strong></p>
                <p>Bank: Access Bank | Account Number: 0022692883</p>
                <p>Account Name: Udoinyang, Mfon Clement</p>
                <p>Send payment receipt to WhatsApp for activation</p>
            </div>
        </div>
        <?php else: ?>
        <div class="premium-banner" style="background: linear-gradient(45deg, #27ae60, #2ecc71);">
            <h2><i class="fas fa-check-circle"></i> Premium Active - Thank You for Your Support!</h2>
            <p>All advanced features are now unlocked. Enjoy your learning journey!</p>
        </div>
        <?php endif; ?>

        <?php foreach ($advancedLessons as $index => $lesson): ?>
        <div class="lesson-card">
            <h2 class="lesson-title">
                <span><?= ($index + 1) . '. ' . htmlspecialchars($lesson['title']) ?></span>
                <?php if (!isPremiumUser() && $index > 0): ?>
                <span style="background: #e74c3c; color: white; padding: 5px 10px; border-radius: 15px; font-size: 0.7em;">Premium</span>
                <?php endif; ?>
            </h2>
            
            <div class="lesson-content">
                <?= htmlspecialchars($lesson['content']) ?>
            </div>

            <div class="topics-grid">
                <?php foreach ($lesson['topics'] as $topic): ?>
                <div class="topic-tag"><?= htmlspecialchars($topic) ?></div>
                <?php endforeach; ?>
            </div>

            <?php if (isPremiumUser() || $index === 0): ?>
            <div class="code-block">
                <pre><code><?= htmlspecialchars($lesson['code']) ?></code></pre>
            </div>
            
            <a href="?download=<?= strtolower(str_replace(' ', '_', $lesson['title'])) ?>" class="btn">
                <i class="fas fa-download"></i> Download Code
            </a>
            <?php else: ?>
            <div style="background: #f8f9fa; padding: 20px; border-radius: 10px; text-align: center; border: 2px dashed #dee2e6;">
                <i class="fas fa-lock" style="font-size: 2em; color: #6c757d; margin-bottom: 10px;"></i>
                <h3>Premium Content</h3>
                <p>Upgrade to access full lesson with 50+ examples</p>
                <a href="#" class="btn btn-premium">Upgrade Now</a>
            </div>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>

        <!-- Quiz Section -->
        <div class="lesson-card">
            <h2 class="lesson-title"><i class="fas fa-question-circle"></i> Advanced PHP Quiz</h2>
            <p>Test your advanced PHP knowledge!</p>
            
            <div class="quiz-section">
                <?php
                $advancedQuestions = [
                    [
                        'question' => 'What is the output of password_hash("password", PASSWORD_DEFAULT)?',
                        'options' => ['A hashed string', 'Boolean true', 'Encrypted string', 'Plain text'],
                        'correct' => 0
                    ],
                    [
                        'question' => 'Which magic method is called when accessing inaccessible properties?',
                        'options' => ['__get()', '__call()', '__isset()', '__set()'],
                        'correct' => 0
                    ],
                    [
                        'question' => 'What is the purpose of the "final" keyword?',
                        'options' => ['Prevents method overriding', 'Makes class abstract', 'Defines constant', 'Enables inheritance'],
                        'correct' => 0
                    ]
                ];
                
                $randomIndex = array_rand($advancedQuestions);
                $currentQuestion = $advancedQuestions[$randomIndex];
                ?>
                
                <div class="quiz-question">
                    <?= htmlspecialchars($currentQuestion['question']) ?>
                </div>
                
                <div class="quiz-options">
                    <?php foreach ($currentQuestion['options'] as $i => $option): ?>
                    <div class="quiz-option" onclick="checkAnswer(<?= $i ?>, <?= $currentQuestion['correct'] ?>)">
                        <?= chr(65 + $i) . '. ' . htmlspecialchars($option) ?>
                    </div>
                    <?php endforeach; ?>
                </div>
                
                <div id="quiz-result" style="margin-top: 15px; font-weight: bold;"></div>
            </div>
        </div>

        <div class="footer">
            <h3>Advanced PHP</h3>
            <p>Master enterprise-level PHP development with design patterns, security, and architecture best practices.</p>
            
            <div class="social-links">
                <?php foreach ($socialLinks as $platform => $url): ?>
                <a href="<?= htmlspecialchars($url) ?>" target="_blank">
                    <i class="fab fa-<?= $platform ?>"></i>
                </a>
                <?php endforeach; ?>
            </div>
            
            <p style="margin-top: 20px;">
                © <?= date('Y') ?> - Advanced Level. Become a PHP Architect!<br>
                Bank: Access Bank | Account: 0022692883 | Name: Udoinyang, Mfon Clement
            </p>
        </div>
    </div>

    <script>
        function checkAnswer(selected, correct) {
            const resultDiv = document.getElementById('quiz-result');
            const options = document.querySelectorAll('.quiz-option');
            
            // Reset all options
            options.forEach(option => {
                option.style.backgroundColor = '';
                option.style.borderColor = '#bdc3c7';
            });
            
            if (selected === correct) {
                options[selected].style.backgroundColor = '#d4edda';
                options[selected].style.borderColor = '#28a745';
                resultDiv.innerHTML = '<span style="color: #28a745;"><i class="fas fa-check"></i> Correct! Well done.</span>';
            } else {
                options[selected].style.backgroundColor = '#f8d7da';
                options[selected].style.borderColor = '#dc3545';
                options[correct].style.backgroundColor = '#d4edda';
                options[correct].style.borderColor = '#28a745';
                resultDiv.innerHTML = '<span style="color: #dc3545;"><i class="fas fa-times"></i> Incorrect. The correct answer is highlighted.</span>';
            }
            
            // Disable further clicks
            options.forEach(option => {
                option.style.pointerEvents = 'none';
            });
            
            // Re-enable after 3 seconds
            setTimeout(() => {
                location.reload();
            }, 3000);
        }

        // Add smooth scrolling
        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
            anchor.addEventListener('click', function (e) {
                e.preventDefault();
                document.querySelector(this.getAttribute('href')).scrollIntoView({
                    behavior: 'smooth'
                });
            });
        });
    </script>
</body>