# Create your models here.
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
import os

class Client(models.Model):
    nom = models.CharField(max_length=200)
    adresse = models.TextField()
    telephone = models.CharField(max_length=20)
    email = models.EmailField()
    
    def __str__(self):
        return self.nom
    
class Projets(models.Model):
    nom_projet = models.CharField(max_length=200,null=True, blank=True)
    client = models.ForeignKey(Client, on_delete=models.PROTECT, related_name='projets')
    adresse = models.CharField(max_length=200)
    etat = models.CharField(max_length=20, choices=[('EN_COURS', 'En cours'), ('ARRETE', 'Arrêté'), ('TERMINE', 'Terminé')], default='EN_COURS')
    
    def __str__(self):
        return self.nom_projet        

class Participant(models.Model):
    pv = models.ForeignKey('ProcesVerbal', on_delete=models.CASCADE, related_name='participants',null=True, blank=True)
    nom = models.CharField(max_length=200)
    fonction = models.CharField(max_length=200, blank=True)
    organisme = models.CharField(max_length=200, blank=True)
    signature = models.TextField(null=True, blank=True)  # Stockage base64 de la signature
    date_signature = models.DateTimeField(auto_now_add=True, null=True, blank=True)

    @property
    def signature_presente(self):
        return bool(self.signature)
    
    class Meta:
        verbose_name = "Participant"
        verbose_name_plural = "Participants"
    
    def __str__(self):
        return f"{self.nom} - {self.pv.numero}"

class TypePV(models.Model):
    TYPE_CHOICES = [
        ('RECEPTION', 'Procès-verbal de réception'),
        ('CONSTAT', 'Procès-verbal de constat'),
        ('CONTROLE', 'Procès-verbal de visite de contrôle'),
        ('MISE_SERVICE', 'Procès-verbal de mise en service'),
        ('LEVER_RESERVES', 'Procès-verbal de lever de réserves'),
    ]
    
    type_pv = models.CharField(max_length=50, choices=TYPE_CHOICES, default='CONTROLE')
    code = models.CharField(max_length=20, unique=True)  # Code unique personnalisé

    
    def __str__(self):
        return self.type_pv
    
class Ouvrage(models.Model):
    code = models.CharField(max_length=50, unique=True)
    nom = models.CharField(max_length=200)
    description = models.TextField(blank=True)
    est_actif = models.BooleanField(default=True)
    
    def __str__(self):
        return f"{self.code} - {self.nom}"
    
class ElementOuvrage(models.Model):

    class EtatChoices(models.TextChoices):
        """Choix pour l'état de l'élément"""
        CONFORME = 'CONFORME', 'Conforme'
        NON_CONFORME = 'NON_CONFORME', 'Non conforme'
        SUSPENDU = 'SUSPENDU', 'Suspendu'
    
    
    ouvrage = models.ForeignKey(Ouvrage, on_delete=models.CASCADE, related_name='elements')
    code = models.CharField(max_length=50)
    nom = models.CharField(max_length=200)
    description = models.TextField(blank=True)

   # etat = models.CharField( max_length=20, choices=EtatChoices.choices,default=EtatChoices.CONFORME,verbose_name="État")
    
    def __str__(self):
        return f"{self.code}: {self.nom}"
    
class PointControle(models.Model):
    code = models.CharField(max_length=50, null=True, blank=True)
    element = models.ForeignKey(ElementOuvrage, on_delete=models.CASCADE, related_name='points_controle')
    point_de_controle = models.CharField(max_length=200,null=True, blank=True)

    
    def __str__(self):
        return f"{self.point_de_controle[:50]}"
    
class ProcesVerbal(models.Model):
    numero = models.CharField(max_length=50, unique=True)
    type_pv = models.ForeignKey(TypePV, on_delete=models.PROTECT)
    client = models.ForeignKey(Client, on_delete=models.PROTECT)
    date_visite = models.DateTimeField()
    objet_controle =  models.ForeignKey(Projets, on_delete=models.SET_NULL, null=True, blank=True)
    lieu = models.CharField(max_length=200)
    observations_generales = models.TextField(blank=True)
    date_creation = models.DateTimeField(auto_now_add=True)
    date_modification = models.DateTimeField(auto_now=True)
    createur = models.ForeignKey(User, on_delete=models.PROTECT)
    
    # Envoi email
    emails_envoyes = models.TextField(help_text="Emails séparés par des virgules", blank=True)
    date_envoi = models.DateTimeField(null=True, blank=True)
    
    class Meta:
        verbose_name = "Procès-verbal"
        verbose_name_plural = "Procès-verbaux"
        ordering = ['-date_visite']
    
    def __str__(self):
        return f"PV {self.numero} - {self.client.nom} - {self.date_visite.strftime('%d/%m/%Y')}"
    


class ControleResultat(models.Model):
    STATUT_CHOICES = [
        ('CONFORME', 'Conforme'),
        ('NON_CONFORME', 'Non conforme'),
        ('SUSPENDU', 'Suspendu'),
    ]
    
    # point_controle remplace l'ancien champ element/etat/etc.  
    pv = models.ForeignKey(ProcesVerbal, on_delete=models.CASCADE, related_name='controles')
    point_controle = models.ForeignKey(PointControle, related_name='resultats', on_delete=models.CASCADE)
    statut = models.CharField(max_length=20, choices=STATUT_CHOICES)
    observation = models.TextField(blank=True)
    date_controle = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        unique_together = ['pv', 'point_controle']
    
    def __str__(self):
        return f"{self.pv} - {self.point_controle}: {self.get_statut_display()}"

    # compatibilité avec le code existant qui utilisait `controle.element` et `controle.etat`
    @property
    def element(self):
        # Retourne l'élément d'ouvrage associé au point de contrôle
        return self.point_controle.element

    @property
    def etat(self):
        # anciennement `etat` : on expose la valeur de statut
        return self.statut

    # alias pour les modèles et templates encore non migrés
    @property
    def resultat(self):
        return self.statut

    
class Photo(models.Model):
    controle = models.ForeignKey(ControleResultat, on_delete=models.CASCADE, related_name='photos')
    image = models.ImageField(upload_to='photos/')
    legende = models.CharField(max_length=200, blank=True)
    date_prise = models.DateTimeField(default=timezone.now)
    
    def __str__(self):
        return f"Photo {self.id} - {self.controle}"

    def delete(self, *args, **kwargs):
        if self.image:
            if os.path.isfile(self.image.path):
                os.remove(self.image.path)
        super().delete(*args, **kwargs)


class Recommandation(models.Model):
    proces_verbal = models.ForeignKey(ProcesVerbal, on_delete=models.CASCADE, related_name='recommandations')
    texte = models.TextField()
    ordre = models.IntegerField(default=0)
    
    class Meta:
        ordering = ['ordre']
    
    def __str__(self):
        return f"Recommandation {self.ordre}: {self.texte[:50]}"
    
