# parents/models.py
"""
Parent portal models for parent-specific functionality.
"""
from django.db import models
from django.contrib.auth import get_user_model

User = get_user_model()


# Note: The main Parent/Guardian model is in students/models.py as ParentGuardian
# This file contains additional parent-specific models for the parent portal


class ParentFeedback(models.Model):
    """
    Stores feedback submitted by parents through the parent portal.
    
    This model allows parents to submit feedback, suggestions, or concerns
    directly through the portal, which can be reviewed by administrators.
    
    Attributes:
        parent (ForeignKey): The parent submitting feedback
        subject (str): Subject/title of the feedback
        message (str): Detailed feedback message
        submitted_at (datetime): When feedback was submitted
        is_read (bool): Whether feedback has been read by staff
        response (str): Staff response to feedback
        responded_at (datetime): When response was sent
        responded_by (ForeignKey): Staff member who responded
    """
    
    parent = models.ForeignKey(
        'students.ParentGuardian',
        on_delete=models.CASCADE,
        related_name='feedbacks'
    )
    subject = models.CharField(
        max_length=200
    )
    message = models.TextField()
    submitted_at = models.DateTimeField(
        auto_now_add=True
    )
    is_read = models.BooleanField(
        default=False
    )
    
    # Response fields
    response = models.TextField(
        blank=True
    )
    responded_at = models.DateTimeField(
        null=True,
        blank=True
    )
    responded_by = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='feedback_responses'
    )
    
    class Meta:
        verbose_name = "Parent Feedback"
        verbose_name_plural = "Parent Feedbacks"
        ordering = ['-submitted_at']
        indexes = [
            models.Index(fields=['submitted_at']),
            models.Index(fields=['is_read']),
        ]
    
    def __str__(self):
        """Return string representation of the feedback."""
        return f"{self.parent} - {self.subject} ({self.submitted_at.date()})"
    
    def mark_as_read(self):
        """
        Mark this feedback as read.
        
        Returns:
            bool: True if successfully marked as read.
        """
        self.is_read = True
        self.save(update_fields=['is_read'])
        return True


class ParentNotification(models.Model):
    """
    Stores notifications sent to parents through the parent portal.
    
    This model tracks notifications sent to specific parents, including
    read status and delivery confirmation.
    
    Attributes:
        parent (ForeignKey): Parent receiving the notification
        title (str): Notification title
        message (str): Notification content
        sent_at (datetime): When notification was sent
        is_read (bool): Whether parent has read the notification
        read_at (datetime): When notification was read
        notification_type (str): Type of notification from TYPE_CHOICES
        link (str): Optional link to related content
    """
    
    TYPE_CHOICES = [
        ('fee_reminder', 'Fee Reminder'),
        ('attendance_alert', 'Attendance Alert'),
        ('exam_notice', 'Exam Notice'),
        ('event', 'School Event'),
        ('general', 'General Announcement'),
    ]
    
    parent = models.ForeignKey(
        'students.ParentGuardian',
        on_delete=models.CASCADE,
        related_name='notifications'
    )
    title = models.CharField(
        max_length=200
    )
    message = models.TextField()
    sent_at = models.DateTimeField(
        auto_now_add=True
    )
    is_read = models.BooleanField(
        default=False
    )
    read_at = models.DateTimeField(
        null=True,
        blank=True
    )
    notification_type = models.CharField(
        max_length=20,
        choices=TYPE_CHOICES,
        default='general'
    )
    link = models.CharField(
        max_length=200,
        blank=True
    )
    
    class Meta:
        verbose_name = "Parent Notification"
        verbose_name_plural = "Parent Notifications"
        ordering = ['-sent_at']
        indexes = [
            models.Index(fields=['sent_at']),
            models.Index(fields=['is_read']),
            models.Index(fields=['notification_type']),
        ]
    
    def __str__(self):
        """Return string representation of the notification."""
        return f"{self.parent} - {self.title}"
    
    def mark_as_read(self):
        """
        Mark this notification as read.
        
        Returns:
            bool: True if successfully marked as read.
        """
        from django.utils import timezone
        self.is_read = True
        self.read_at = timezone.now()
        self.save(update_fields=['is_read', 'read_at'])
        return True


class ParentSession(models.Model):
    """
    Tracks parent login sessions for the parent portal.
    
    This model helps monitor parent activity and can be used for
    security auditing and analytics.
    
    Attributes:
        parent (ForeignKey): Parent who logged in
        login_time (datetime): When parent logged in
        logout_time (datetime): When parent logged out
        ip_address (str): IP address used for login
        user_agent (str): Browser/device information
        is_active (bool): Whether session is still active
    """
    
    parent = models.ForeignKey(
        'students.ParentGuardian',
        on_delete=models.CASCADE,
        related_name='sessions'
    )
    login_time = models.DateTimeField(
        auto_now_add=True
    )
    logout_time = models.DateTimeField(
        null=True,
        blank=True
    )
    ip_address = models.GenericIPAddressField(null=True, blank=True)
    user_agent = models.TextField(blank=True)
    is_active = models.BooleanField(
        default=True
    )
    
    class Meta:
        verbose_name = "Parent Session"
        verbose_name_plural = "Parent Sessions"
        ordering = ['-login_time']
    
    def __str__(self):
        """Return string representation of the session."""
        return f"{self.parent} - {self.login_time.date()}"
    
    def end_session(self):
        """
        End this parent session.
        
        Returns:
            bool: True if session ended successfully.
        """
        from django.utils import timezone
        self.is_active = False
        self.logout_time = timezone.now()
        self.save(update_fields=['is_active', 'logout_time'])
        return True