from django.db import models
from django.contrib.auth.models import User

class Course(models.Model):
    name = models.CharField(max_length=200)
    slug = models.SlugField(unique=True)
    tags = models.CharField(max_length=200)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    thumbnail = models.ImageField(upload_to='thumbnails/courses/', default='default.jpg')
    description = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    enable = models.BooleanField(default=True)

    def __str__(self):
        return self.name

class Module(models.Model):
    name = models.CharField(max_length=200)
    slug = models.SlugField()
    course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='modules')
    description = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    enable = models.BooleanField(default=True)
    order = models.PositiveIntegerField()

class Lesson(models.Model):
    name = models.CharField(max_length=200)
    slug = models.SlugField()
    module = models.ForeignKey(Module, on_delete=models.CASCADE, related_name='lessons')
    content = models.TextField()
    video_id = models.CharField(max_length=200, blank=True)
    is_premium = models.BooleanField(default=False)
    order = models.PositiveIntegerField()

    def clean(self):
        # Remplacer les chevrons <?php et ?> par leurs équivalents HTML
        if self.content:
            self.content = self.content.replace('<?php', '&lt;?php')
            self.content = self.content.replace('?>', '?&gt;')

    def __str__(self):
        return self.name


class Comment(models.Model):
    lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, related_name='comments')
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='lesson_comments')
    content = models.TextField()
    parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='replies')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    is_active = models.BooleanField(default=True)

    class Meta:
        ordering = ("created_at",)

    def __str__(self):
        return f"Comment by {self.user} on {self.lesson}"