# portfolio/models.py
from django.db import models
from django.utils import timezone

class Service(models.Model):
    """Services offered"""
    title = models.CharField(max_length=100)
    description = models.TextField()
    icon = models.CharField(max_length=50, help_text="Font Awesome icon class (e.g., 'fa-code', 'fa-palette')")
    order = models.IntegerField(default=0, help_text="Display order")
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['order', 'title']

    def __str__(self):
        return self.title


class Skill(models.Model):
    """Technical skills"""
    name = models.CharField(max_length=100)
    percentage = models.IntegerField(help_text="Skill level (0-100)")
    category = models.CharField(max_length=50, choices=[
        ('frontend', 'Frontend'),
        ('backend', 'Backend'),
        ('tools', 'Tools & Others'),
    ])
    order = models.IntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['category', 'order']

    def __str__(self):
        return f"{self.name} - {self.percentage}%"


class Project(models.Model):
    """Portfolio projects"""
    title = models.CharField(max_length=200)
    description = models.TextField()
    image = models.ImageField(upload_to='projects/')
    technologies = models.CharField(max_length=300, help_text="Comma-separated (e.g., Django, React, Tailwind)")
    live_url = models.URLField(blank=True, null=True)
    github_url = models.URLField(blank=True, null=True)
    category = models.CharField(max_length=50, choices=[
        ('web', 'Web Development'),
        ('mobile', 'Mobile App'),
        ('design', 'UI/UX Design'),
        ('other', 'Other'),
    ])
    is_featured = models.BooleanField(default=False)
    order = models.IntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-is_featured', 'order', '-created_at']

    def __str__(self):
        return self.title

    def get_technologies_list(self):
        return [tech.strip() for tech in self.technologies.split(',')]


class Testimonial(models.Model):
    """Client testimonials"""
    client_name = models.CharField(max_length=100)
    client_position = models.CharField(max_length=100, help_text="e.g., CEO at Company")
    client_image = models.ImageField(upload_to='testimonials/', blank=True, null=True)
    testimonial = models.TextField()
    rating = models.IntegerField(default=5, choices=[(i, i) for i in range(1, 6)])
    is_active = models.BooleanField(default=True)
    order = models.IntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['order', '-created_at']

    def __str__(self):
        return f"{self.client_name} - {self.rating}⭐"


class Contact(models.Model):
    """Contact form submissions"""
    name = models.CharField(max_length=100)
    email = models.EmailField()
    subject = models.CharField(max_length=200)
    message = models.TextField()
    is_read = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.name} - {self.subject}"


class About(models.Model):
    """About section content (should only have 1 instance)"""
    full_name = models.CharField(max_length=100, default="Chris Dev")
    tagline = models.CharField(max_length=200, default="Full Stack Developer & Designer")
    bio = models.TextField(help_text="Main about text")
    profile_image = models.ImageField(upload_to='about/')
    years_experience = models.IntegerField(default=5)
    projects_completed = models.IntegerField(default=50)
    happy_clients = models.IntegerField(default=30)
    cv_file = models.FileField(upload_to='cv/', blank=True, null=True)
    
    # Social links
    github = models.URLField(blank=True, null=True)
    linkedin = models.URLField(blank=True, null=True)
    twitter = models.URLField(blank=True, null=True)
    instagram = models.URLField(blank=True, null=True)
    
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name_plural = "About"

    def __str__(self):
        return self.full_name

    def save(self, *args, **kwargs):
        if not self.pk and About.objects.exists():
            raise ValueError("Only one About instance is allowed")
        return super().save(*args, **kwargs)


class Pricing(models.Model):
    """Pricing plans"""
    plan_name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    duration = models.CharField(max_length=50, default="per project", help_text="e.g., per hour, per project, monthly")
    description = models.TextField()
    features = models.TextField(help_text="One feature per line")
    is_popular = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    order = models.IntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['order', 'price']
        verbose_name_plural = "Pricing"

    def __str__(self):
        return f"{self.plan_name} - ${self.price}"
    
    def get_features_list(self):
        return [feature.strip() for feature in self.features.split('\n') if feature.strip()]


class BookingSession(models.Model):
    """Session booking requests"""
    name = models.CharField(max_length=100)
    email = models.EmailField()
    phone = models.CharField(max_length=20)
    session_type = models.CharField(max_length=100, choices=[
        ('consultation', 'Free Consultation'),
        ('project_discussion', 'Project Discussion'),
        ('code_review', 'Code Review'),
        ('mentoring', 'Mentoring Session'),
        ('other', 'Other'),
    ])
    preferred_date = models.DateField()
    preferred_time = models.TimeField()
    message = models.TextField(blank=True)
    status = models.CharField(max_length=50, choices=[
        ('pending', 'Pending'),
        ('confirmed', 'Confirmed'),
        ('completed', 'Completed'),
        ('cancelled', 'Cancelled'),
    ], default='pending')
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.name} - {self.session_type} on {self.preferred_date}"


class SiteSettings(models.Model):
    """General site settings"""
    site_name = models.CharField(max_length=100, default="ChrisDev")
    site_logo = models.ImageField(upload_to='site/', blank=True, null=True)
    email = models.EmailField(default="hello@chrisdev.com")
    phone = models.CharField(max_length=20, blank=True)
    address = models.CharField(max_length=200, blank=True)
    footer_text = models.TextField(default="© 2025 ChrisDev. All rights reserved.")
    
    class Meta:
        verbose_name_plural = "Site Settings"

    def __str__(self):
        return self.site_name

    def save(self, *args, **kwargs):
        if not self.pk and SiteSettings.objects.exists():
            raise ValueError("Only one SiteSettings instance is allowed")
        return super().save(*args, **kwargs)
    
# Add these to your portfolio/models.py file

from django.utils.text import slugify

class BlogCategory(models.Model):
    """Blog post categories"""
    name = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100, unique=True)
    description = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = "Blog Categories"
        ordering = ['name']

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.name)
        super().save(*args, **kwargs)


class BlogPost(models.Model):
    """Blog posts"""
    title = models.CharField(max_length=200)
    slug = models.SlugField(max_length=200, unique=True)
    category = models.ForeignKey(BlogCategory, on_delete=models.SET_NULL, null=True, related_name='posts')
    featured_image = models.ImageField(upload_to='blog/')
    excerpt = models.TextField(max_length=300, help_text="Short description for previews")
    content = models.TextField(help_text="Full blog post content")
    
    # SEO fields
    meta_description = models.CharField(max_length=160, blank=True)
    meta_keywords = models.CharField(max_length=200, blank=True)
    
    # Publishing
    is_published = models.BooleanField(default=False)
    is_featured = models.BooleanField(default=False, help_text="Show on homepage")
    published_date = models.DateTimeField(null=True, blank=True)
    
    # Stats
    views = models.IntegerField(default=0)
    read_time = models.IntegerField(default=5, help_text="Estimated reading time in minutes")
    
    # Tags
    tags = models.CharField(max_length=200, blank=True, help_text="Comma-separated tags")
    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-published_date', '-created_at']

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        if self.is_published and not self.published_date:
            self.published_date = timezone.now()
        super().save(*args, **kwargs)

    def get_tags_list(self):
        return [tag.strip() for tag in self.tags.split(',') if tag.strip()]
    
    def increment_views(self):
        self.views += 1
        self.save(update_fields=['views'])


class BlogComment(models.Model):
    """Blog post comments"""
    post = models.ForeignKey(BlogPost, on_delete=models.CASCADE, related_name='comments')
    name = models.CharField(max_length=100)
    email = models.EmailField()
    comment = models.TextField()
    is_approved = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.name} on {self.post.title}"