from django.db import models
from django.core.validators import FileExtensionValidator
from django.utils import timezone
from django.utils.text import slugify
from django.urls import reverse
from django.core.files import File
from PIL import Image, ImageDraw
from io import BytesIO
from phonenumber_field.modelfields import PhoneNumberField



class Categories(models.Model):
    title = models.CharField(max_length=100, blank=True)
    slug = models.SlugField(unique=True, blank=True, null=True)
    picture = models.ImageField(upload_to='main/images', null=True, blank=True)
    citation = models.TextField(blank=True)
    date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
    parentcategory = models.ManyToManyField('self', symmetrical=False, blank=True, related_name='children')

    class Meta:
        verbose_name_plural = 'Categories'
        ordering = ['id']

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

    def __str__(self):
        return self.title

class Images(models.Model):
    title = models.CharField(max_length=33, blank=True)
    course = models.ForeignKey('Courses', on_delete=models.CASCADE, blank=True, null=True)
    file = models.ImageField(upload_to='main/images', blank=True, null=True)
    
    class Meta:
        verbose_name_plural = 'Images'
        ordering = ['id']
    
    IMAGE_MAX_SIZE = (900, 484)
    
    def resize_image(self):
        file = Image.open(self.file)
        file.thumbnail(self.IMAGE_MAX_SIZE)
        file.save(self.file.path)
    
    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        self.resize_image()

    def __str__(self):
        return self.title


class Partners(models.Model):
    title = models.CharField(max_length=50)
    slug = models.SlugField(unique=True, blank=True, null=True)
    image = models.ImageField(upload_to='main/images')
    
    class Meta:
        verbose_name_plural = 'Partners'
        ordering = ['id']

    IMAGE_MAX_SIZE = (300, 300)

    def resize_image(self):
        image = Image.open(self.image)
        image.thumbnail(self.IMAGE_MAX_SIZE)
        image.save(self.image.path)

    def save(self, *args, **kwargs):
        
        
        if not self.slug:
            base_slug = slugify(self.title)
            slug = base_slug
            counter = 1
            while Products.objects.filter(slug=slug).exists():
                slug = f'{base_slug}-{counter}'
                counter += 1
            self.slug = slug

        super().save(*args, **kwargs)
        self.resize_image()

    def __str__(self):
        return self.title

class Cities(models.Model):
    city = models.CharField(max_length=200, blank=True)
    wilaya = models.ForeignKey('Wilayas', on_delete=models.CASCADE, blank=True, null=True)

    class Meta:
        verbose_name_plural = 'Villes'
        ordering = ['id']

    def __str__(self):
        return self.city

class Wilayas(models.Model):
    title = models.CharField(max_length=200, blank=True)
    slug = models.SlugField(unique=True, blank=True, null=True)
    size = models.IntegerField(blank=True, null=True)
    image = models.ImageField(upload_to='main/images', blank=True, null=True)

    class Meta:
        verbose_name_plural = 'Wilayas'
        ordering = ['id']

    IMAGE_MAX_SIZE = (500, 350)

    def save(self, *args, **kwargs):
        if not self.slug:
            base_slug = slugify(self.title)
            slug = base_slug
            counter = 1
            while Store.objects.filter(slug=slug).exists():
                slug = f'{base_slug}-{counter}'
                counter += 1
            self.slug = slug

        super().save(*args, **kwargs)

    def __str__(self):
        return self.title

class Codes(models.Model):
    code = models.CharField(max_length=200, blank=True)

    class Meta:
        verbose_name_plural = 'code Zip'
        ordering = ['id']

    def __str__(self):
        return self.code

class Countries(models.Model):
    country = models.CharField(max_length=200, blank=True)

    class Meta:
        verbose_name_plural = 'Pays'
        ordering = ['id']

    def __str__(self):
        return self.country


class School(models.Model):
    title = models.CharField(max_length=33)
    owner = models.ForeignKey('authentication.User', on_delete=models.CASCADE)
    category = models.ManyToManyField('Categories', related_name="product_categories")
    partner = models.ManyToManyField('Partners', blank=True)
    city = models.CharField(max_length=33, blank=True)
    wilaya = models.ForeignKey('Wilayas', blank=True, null=True, on_delete=models.CASCADE)
    code = models.ManyToManyField('Codes', related_name="code_store", blank=True)
    country = models.ManyToManyField('Countries', related_name="country_store", blank=True)
    slug = models.SlugField(unique=True, blank=True, null=True)
    description = models.TextField(blank=True)
    logo = models.ImageField(upload_to='main/images')
    banner = models.ImageField(upload_to='main/images')
    email = models.EmailField()
    facebook = models.URLField(blank=True, null=True)
    instagram = models.URLField(blank=True, null=True)
    linkedin = models.URLField(blank=True, null=True)
    youtube = models.URLField(blank=True, null=True)
    website = models.URLField(blank=True, null=True)
    whatsapp = PhoneNumberField(blank=True, null=True)
    maps = models.URLField(blank=True, null=True)
    location = models.TextField(blank=True)
    date_created = models.DateTimeField(auto_now_add=True)
    date_updated = models.DateTimeField(auto_now=True)
    active = models.BooleanField(default=False)
    sponsored = models.BooleanField(default=False)

    class Meta:
        verbose_name_plural = 'Schools'
        ordering = ['date_created']

    LOGO_MAX_SIZE = (370, 200)
    BANNER_MAX_SIZE = (1920, 550)
    def resize_image(self):
        if self.logo:
            logo = Image.open(self.logo.path)
            logo.thumbnail(self.LOGO_MAX_SIZE)
            logo.save(self.logo.path)
        if self.banner:
            banner = Image.open(self.banner.path)
            banner.thumbnail(self.BANNER_MAX_SIZE)
            banner.save(self.banner.path)

    def save(self, *args, **kwargs):
        if not self.slug:
            base_slug = slugify(self.title)
            slug = base_slug
            counter = 1
            while Store.objects.filter(slug=slug).exists():
                slug = f'{base_slug}-{counter}'
                counter += 1
            self.slug = slug
        super().save(*args, **kwargs)
        self.resize_image()
        
    def get_absolute_url(self):
        return reverse('main:seller_shop', kwargs={'slug': self.slug})

    def __str__(self):
        return self.title

class Addresses(models.Model):
    title = models.CharField(max_length=200, blank=True)  # Par exemple, "Maison", "Bureau", etc.
    school = models.ForeignKey(School, on_delete=models.SET_NULL, null=True, blank=True)
    address = models.TextField()

    class Meta:
        verbose_name_plural = 'Adresses'
        ordering = ['id']
        

    def __str__(self):
        return self.title

class Phones(models.Model):
    title = models.CharField(max_length=200, blank=True)  # Par exemple, "Portable", "Bureau", etc.
    phone = PhoneNumberField()  # Champ pour stocker le numéro de téléphone
    school = models.ForeignKey(School, on_delete=models.SET_NULL, null=True, blank=True)

    class Meta:
        verbose_name_plural = 'Numéros Téléphone'
        ordering = ['id']

    def __str__(self):
        return self.title

class Courses(models.Model):
    Online = 'Online'
    Facetoface = 'Facetoface'
    Blended = 'Blended'

    ROLE_CHOICES = (
        (Online, 'Online'),
        (Facetoface, 'Facetoface'),
        (Blended, 'Blended'),
        )
    title = models.CharField(max_length=33)
    owner = models.ForeignKey('authentication.User', on_delete=models.CASCADE)
    school = models.ForeignKey(School, on_delete=models.CASCADE, null=True, blank=True)
    category = models.ManyToManyField('Categories')
    slug = models.SlugField(unique=True, blank=True, null=True)
    partner = models.ForeignKey('Partners', on_delete=models.CASCADE)
    price = models.DecimalField(max_digits=19, decimal_places=2, default=0.0)
    description = models.TextField(blank=True)
    status = models.CharField(max_length=30, choices=ROLE_CHOICES, default=Online, blank=True, null=True)
    date_created = models.DateTimeField(auto_now_add=True)
    date_updated = models.DateTimeField(auto_now=True)
    active = models.BooleanField(default=False)
    
    class Meta:
        verbose_name_plural = 'Courses'
        ordering = ['date_created']

    IMAGE_MAX_SIZE = (500, 350)

    
        
    def save(self, *args, **kwargs):    
        if not self.slug:
            base_slug = slugify(self.title)
            slug = base_slug
            counter = 1
            while Products.objects.filter(slug=slug).exists():
                slug = f'{base_slug}-{counter}'
                counter += 1
            self.slug = slug

        super().save(*args, **kwargs)
        

    def get_absolute_url(self):
        return reverse('main:product_detail', kwargs={'slug': self.slug})

    def __str__(self):
        return self.title


class Contact(models.Model):
    name = models.CharField(max_length=50)
    email = models.EmailField()
    subject = models.CharField(max_length=50)
    phone_number = PhoneNumberField()
    message = models.TextField()
    date_created = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        verbose_name_plural = 'Contacts'
        ordering = ['id']
    

    def __str__(self):
        return self.subject

class Testimonials(models.Model):
    title = models.CharField(max_length=200)
    testimonial = models.TextField()
    date_created = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey('authentication.User', on_delete=models.CASCADE)
    class Meta:
        verbose_name_plural = 'Testimonials'
        ordering = ['date_created']

    def __str__(self):
        return self.title