"""
Institute-related models - Institute, InstituteMember, Enrollment, LiveClass,
CourseInstructors, InstituteCourses, InstituteSettings, InstituteReviews,
InstituteConfig, InstitutePages, etc.
"""
from datetime import datetime
from config import db


class Institute(db.Model):
    """Institute model - matches actual database schema"""
    __tablename__ = 'institutes'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(255), nullable=False)
    slug = db.Column(db.String(255), unique=True, nullable=False)
    description = db.Column(db.Text)
    logo_url = db.Column(db.String(500))
    banner_url = db.Column(db.String(500))
    website = db.Column(db.String(255))
    email = db.Column(db.String(255), nullable=False)
    phone = db.Column(db.String(50))
    address = db.Column(db.Text)
    city = db.Column(db.String(100))
    state = db.Column(db.String(100))
    country = db.Column(db.String(100), default='Nepal')
    postal_code = db.Column(db.String(20))
    # Enhanced fields (from migration 004)
    institute_type = db.Column(db.Enum('university', 'college', 'training_center', 'coaching_center', 'individual', 'corporate', 'government'), default='training_center')
    registration_number = db.Column(db.String(100), comment='Official registration number')
    tax_number = db.Column(db.String(100), comment='Tax identification number')
    founded_year = db.Column(db.Integer, comment='Year institute was founded')
    license_number = db.Column(db.String(100))
    # Statistics
    total_students = db.Column(db.Integer, default=0)
    total_instructors = db.Column(db.Integer, default=0)
    total_courses = db.Column(db.Integer, default=0)
    average_rating = db.Column(db.Numeric(3, 2), default=0)
    total_reviews = db.Column(db.Integer, default=0)
    # Verification
    status = db.Column(db.String(20), default='pending')
    is_verified = db.Column(db.Boolean, default=False)
    verified_at = db.Column(db.DateTime)
    verification_date = db.Column(db.DateTime)
    verified_by = db.Column(db.Integer)
    # JSON fields
    settings = db.Column(db.Text)  # JSON
    social_links = db.Column(db.Text)  # JSON
    features = db.Column(db.Text)  # JSON
    # Custom Domain
    custom_domain = db.Column(db.String(255))
    domain_verified = db.Column(db.Boolean, default=False)
    domain_verification_code = db.Column(db.String(255))
    # SEO
    slogan = db.Column(db.String(500))
    meta_title = db.Column(db.String(255))
    meta_description = db.Column(db.Text)
    keywords = db.Column(db.String(500))
    author = db.Column(db.String(255))
    # Metadata
    created_by = db.Column(db.Integer, nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'slug': self.slug,
            'description': self.description,
            'logo_url': self.logo_url,
            'banner_url': self.banner_url,
            'website': self.website,
            'email': self.email,
            'phone': self.phone,
            'address': self.address,
            'city': self.city,
            'state': self.state,
            'country': self.country,
            'postal_code': self.postal_code,
            'institute_type': self.institute_type,
            'registration_number': self.registration_number,
            'tax_number': self.tax_number,
            'founded_year': self.founded_year,
            'status': self.status,
            'is_verified': self.is_verified,
            'social_links': self.social_links,
            'features': self.features,
            'total_instructors': self.total_instructors or 0,
            'total_courses': self.total_courses or 0,
            'total_students': self.total_students or 0,
            'average_rating': float(self.average_rating or 0),
            'total_reviews': self.total_reviews or 0,
            'custom_domain': self.custom_domain,
            'domain_verified': self.domain_verified or False,
            'domain_verification_code': self.domain_verification_code,
            'slogan': self.slogan,
            'meta_title': self.meta_title,
            'meta_description': self.meta_description,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }


class InstituteMember(db.Model):
    __tablename__ = 'institute_members'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    institute_id = db.Column(db.Integer, db.ForeignKey('institutes.id'), nullable=False)
    user_id = db.Column(db.Integer, nullable=False)
    role = db.Column(db.Enum('owner', 'admin', 'instructor', 'moderator', 'student'), default='student')
    permissions = db.Column(db.Text)  # JSON
    status = db.Column(db.Enum('active', 'inactive', 'pending', 'suspended', 'rejected'), default='pending')
    title = db.Column(db.String(100))
    department = db.Column(db.String(100))
    bio = db.Column(db.Text, comment='Member bio within institute context')
    invited_by = db.Column(db.Integer)
    invitation_token = db.Column(db.String(100))
    invitation_expires_at = db.Column(db.DateTime)
    joined_at = db.Column(db.DateTime)
    approved_at = db.Column(db.DateTime)
    approved_by = db.Column(db.Integer)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    def to_dict(self):
        return {
            'id': self.id,
            'institute_id': self.institute_id,
            'user_id': self.user_id,
            'role': self.role,
            'permissions': self.permissions,
            'status': self.status,
            'title': self.title,
            'department': self.department,
            'bio': self.bio,
            'joined_at': self.joined_at.isoformat() if self.joined_at else None,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }


class Enrollment(db.Model):
    __tablename__ = 'enrollments'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.Integer, nullable=False)
    course_id = db.Column(db.Integer, nullable=False)
    institute_id = db.Column(db.Integer, nullable=True)
    enrolled_at = db.Column(db.DateTime, default=datetime.utcnow)
    progress = db.Column(db.Integer, default=0)
    is_completed = db.Column(db.Boolean, default=False)
    completed_at = db.Column(db.DateTime)
    payment_status = db.Column(db.String(20), default='pending')
    payment_id = db.Column(db.String(100))
    payment_amount = db.Column(db.Numeric(10, 2))
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    def to_dict(self):
        return {
            'id': self.id,
            'user_id': self.user_id,
            'course_id': self.course_id,
            'amount': float(self.payment_amount or 0),
            'payment_status': self.payment_status,
            'enrollment_date': self.enrolled_at.isoformat() if self.enrolled_at else None,
            'progress': self.progress or 0,
            'is_completed': self.is_completed
        }


class LiveClass(db.Model):
    """Live class model - matches actual database schema"""
    __tablename__ = 'live_classes'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    course_id = db.Column(db.Integer, nullable=False)
    instructor_id = db.Column(db.Integer, nullable=False)
    title = db.Column(db.String(255), nullable=False)
    description = db.Column(db.Text)
    scheduled_start_time = db.Column(db.DateTime, nullable=False)
    scheduled_end_time = db.Column(db.DateTime, nullable=False)
    actual_start_time = db.Column(db.DateTime)
    actual_end_time = db.Column(db.DateTime)
    jitsi_room_name = db.Column(db.String(255), nullable=False)
    jitsi_room_password = db.Column(db.String(100))
    max_participants = db.Column(db.Integer, default=100)
    status = db.Column(db.String(20), default='scheduled')
    recording_enabled = db.Column(db.Boolean, default=True)
    recording_url = db.Column(db.String(500))
    meeting_notes = db.Column(db.Text)
    thumbnail_url = db.Column(db.String(500))
    is_public = db.Column(db.Boolean, default=False)
    stream_type = db.Column(db.String(50), default='jitsi')
    youtube_url = db.Column(db.String(500))
    socket_room_id = db.Column(db.String(100))
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    def to_dict(self):
        return {
            'id': self.id,
            'title': self.title,
            'description': self.description,
            'course_id': self.course_id,
            'instructor_id': self.instructor_id,
            'scheduled_at': self.scheduled_start_time.isoformat() if self.scheduled_start_time else None,
            'scheduled_end_time': self.scheduled_end_time.isoformat() if self.scheduled_end_time else None,
            'duration_minutes': self._calculate_duration(),
            'meeting_url': f"https://meet.jit.si/{self.jitsi_room_name}" if self.jitsi_room_name else None,
            'jitsi_room_name': self.jitsi_room_name,
            'stream_type': self.stream_type or 'jitsi',
            'youtube_url': self.youtube_url,
            'socket_room_id': self.socket_room_id or f'live_class_{self.id}',
            'status': self.status,
            'max_participants': self.max_participants,
            'recording_enabled': self.recording_enabled,
            'recording_url': self.recording_url,
            'thumbnail_url': self.thumbnail_url,
            'is_public': self.is_public,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }
    
    def _calculate_duration(self):
        if self.scheduled_start_time and self.scheduled_end_time:
            delta = self.scheduled_end_time - self.scheduled_start_time
            return int(delta.total_seconds() / 60)
        return 60


class ModelSet(db.Model):
    __tablename__ = 'model_sets'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(255), nullable=False)
    description = db.Column(db.Text)
    course_id = db.Column(db.Integer)
    total_questions = db.Column(db.Integer, default=0)
    duration_minutes = db.Column(db.Integer, default=60)
    difficulty = db.Column(db.String(20), default='medium')
    is_active = db.Column(db.Boolean, default=True)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    def to_dict(self):
        return {
            'id': self.id,
            'title': self.title,
            'description': self.description,
            'course_id': self.course_id,
            'total_questions': self.total_questions or 0,
            'duration_minutes': self.duration_minutes,
            'difficulty': self.difficulty,
            'is_active': self.is_active,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }


class QAQuestion(db.Model):
    __tablename__ = 'qa_questions'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    topic_id = db.Column(db.Integer, nullable=False)
    question_text = db.Column(db.Text, nullable=False)
    expected_answer = db.Column(db.Text)
    answer_keywords = db.Column(db.Text)
    difficulty = db.Column(db.Enum('easy', 'medium', 'hard', 'all'), default='medium')
    explanation = db.Column(db.Text)
    marks = db.Column(db.Integer, default=1)
    time_limit = db.Column(db.Integer, default=300)
    is_ai_generated = db.Column(db.Boolean, default=False)
    ai_metadata = db.Column(db.Text)
    user_id = db.Column(db.Integer)
    ai_model = db.Column(db.String(50))
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    def to_dict(self):
        return {
            'id': self.id,
            'topic_id': self.topic_id,
            'question_text': self.question_text,
            'expected_answer': self.expected_answer,
            'answer_keywords': self.answer_keywords,
            'difficulty': self.difficulty,
            'explanation': self.explanation,
            'marks': self.marks,
            'time_limit': self.time_limit,
            'is_ai_generated': self.is_ai_generated,
            'ai_metadata': self.ai_metadata,
            'user_id': self.user_id,
            'ai_model': self.ai_model,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }


# ============================================
# NEW MODELS (from migrations 004+)
# ============================================

class CourseInstructors(db.Model):
    """Multiple instructors per course"""
    __tablename__ = 'course_instructors'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    course_id = db.Column(db.Integer, db.ForeignKey('courses.id', ondelete='CASCADE'), nullable=False)
    instructor_id = db.Column(db.Integer, db.ForeignKey('instructors.id', ondelete='CASCADE'), nullable=False)
    role = db.Column(db.Enum('primary', 'secondary', 'guest', 'assistant'), default='secondary')
    responsibilities = db.Column(db.Text, comment='JSON: Specific responsibilities')
    compensation_type = db.Column(db.Enum('fixed', 'percentage', 'hourly', 'none'), default='none')
    compensation_amount = db.Column(db.Numeric(10, 2), default=0.00)
    status = db.Column(db.Enum('active', 'inactive', 'completed'), default='active')
    assigned_at = db.Column(db.DateTime, default=datetime.utcnow)
    started_at = db.Column(db.DateTime)
    completed_at = db.Column(db.DateTime)

    def to_dict(self):
        return {column.name: getattr(self, column.name) for column in self.__table__.columns}


class InstituteCourses(db.Model):
    """Institute-specific course settings"""
    __tablename__ = 'institute_courses'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    institute_id = db.Column(db.Integer, db.ForeignKey('institutes.id', ondelete='CASCADE'), nullable=False)
    course_id = db.Column(db.Integer, db.ForeignKey('courses.id', ondelete='CASCADE'), nullable=False)
    display_order = db.Column(db.Integer, default=0)
    is_featured = db.Column(db.Boolean, default=False)
    custom_price = db.Column(db.Numeric(10, 2), comment='Institute-specific pricing')
    custom_description = db.Column(db.Text, comment='Institute-specific description')
    status = db.Column(db.Enum('active', 'inactive', 'archived'), default='active')
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    def to_dict(self):
        return {column.name: getattr(self, column.name) for column in self.__table__.columns}


class InstituteSettings(db.Model):
    """Institute-specific settings"""
    __tablename__ = 'institute_settings'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    institute_id = db.Column(db.Integer, db.ForeignKey('institutes.id', ondelete='CASCADE'), nullable=False, unique=True)
    # General
    allow_public_courses = db.Column(db.Boolean, default=True)
    require_course_approval = db.Column(db.Boolean, default=True)
    allow_instructor_signup = db.Column(db.Boolean, default=False)
    auto_approve_instructors = db.Column(db.Boolean, default=False)
    # Branding
    primary_color = db.Column(db.String(7), default='#3B82F6')
    secondary_color = db.Column(db.String(7), default='#8B5CF6')
    custom_css = db.Column(db.Text)
    # Communication
    welcome_message = db.Column(db.Text)
    course_completion_message = db.Column(db.Text)
    certificate_message = db.Column(db.Text)
    # Payment
    payment_methods = db.Column(db.Text, comment='JSON: Accepted payment methods')
    default_currency = db.Column(db.String(3), default='NPR')
    tax_rate = db.Column(db.Numeric(5, 2), default=0.00)
    # Email
    email_from_name = db.Column(db.String(100))
    email_from_address = db.Column(db.String(255))
    email_templates = db.Column(db.Text, comment='JSON: Custom email templates')
    # Integrations
    integrations = db.Column(db.Text, comment='JSON: Third-party integrations')
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    def to_dict(self):
        return {column.name: getattr(self, column.name) for column in self.__table__.columns}


class InstituteReview(db.Model):
    """Institute reviews and ratings"""
    __tablename__ = 'institute_reviews'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    institute_id = db.Column(db.Integer, db.ForeignKey('institutes.id', ondelete='CASCADE'), nullable=False)
    user_id = db.Column(db.Integer, nullable=False)
    course_id = db.Column(db.Integer, nullable=True)
    rating = db.Column(db.SmallInteger, nullable=False)
    title = db.Column(db.String(255))
    comment = db.Column(db.Text)
    is_verified = db.Column(db.Boolean, default=False)
    is_featured = db.Column(db.Boolean, default=False)
    helpful_count = db.Column(db.Integer, default=0)
    status = db.Column(db.Enum('pending', 'approved', 'rejected', 'hidden'), default='pending')
    moderated_by = db.Column(db.Integer)
    moderated_at = db.Column(db.DateTime)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    def to_dict(self):
        return {column.name: getattr(self, column.name) for column in self.__table__.columns}


class InstituteConfig(db.Model):
    """Comprehensive institute customization settings"""
    __tablename__ = 'institute_config'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    institute_id = db.Column(db.Integer, nullable=False, unique=True)
    # Template
    template_id = db.Column(db.String(50), default='modern')
    template_variant = db.Column(db.String(50), default='default')
    # Theme Colors
    primary_color = db.Column(db.String(9), default='#10B981')
    secondary_color = db.Column(db.String(9), default='#3B82F6')
    accent_color = db.Column(db.String(9), default='#F59E0B')
    text_color = db.Column(db.String(9), default='#1F2937')
    background_color = db.Column(db.String(9), default='#FFFFFF')
    surface_color = db.Column(db.String(9), default='#F9FAFB')
    # Gradient
    gradient_start = db.Column(db.String(9), default='#10B981')
    gradient_end = db.Column(db.String(9), default='#059669')
    gradient_direction = db.Column(db.String(50), default='to right')
    # Typography
    heading_font = db.Column(db.String(100), default='Inter')
    body_font = db.Column(db.String(100), default='Inter')
    font_size_base = db.Column(db.Integer, default=16)
    # Border & Shadows
    border_radius = db.Column(db.String(20), default='0.5rem')
    shadow_style = db.Column(db.Enum('none', 'subtle', 'medium', 'strong'), default='subtle')
    # Header
    header_style = db.Column(db.Enum('transparent', 'solid', 'gradient', 'sticky'), default='solid')
    header_bg_color = db.Column(db.String(9), default='#FFFFFF')
    header_text_color = db.Column(db.String(9), default='#1F2937')
    show_top_bar = db.Column(db.Boolean, default=False)
    top_bar_text = db.Column(db.String(500))
    header_cta_text = db.Column(db.String(100))
    header_cta_link = db.Column(db.String(255))
    # Hero
    hero_style = db.Column(db.Enum('full', 'split', 'centered', 'video', 'slider', 'minimal'), default='full')
    hero_title = db.Column(db.Text)
    hero_subtitle = db.Column(db.Text)
    hero_cta_primary_text = db.Column(db.String(100), default='Explore Courses')
    hero_cta_primary_link = db.Column(db.String(255), default='/marketplace')
    hero_cta_secondary_text = db.Column(db.String(100), default='Contact Us')
    hero_cta_secondary_link = db.Column(db.String(255), default='/contact')
    hero_image_url = db.Column(db.String(500))
    hero_video_url = db.Column(db.String(500))
    # Sections
    sections_config = db.Column(db.Text, comment='JSON: Section order and settings')
    # Footer
    footer_style = db.Column(db.Enum('simple', 'detailed', 'minimal', 'mega'), default='detailed')
    footer_bg_color = db.Column(db.String(9), default='#1F2937')
    footer_text_color = db.Column(db.String(9), default='#D1D5DB')
    copyright_text = db.Column(db.String(500))
    footer_links = db.Column(db.Text, comment='JSON: Footer links')
    # Navigation
    nav_style = db.Column(db.Enum('horizontal', 'hamburger', 'mega'), default='horizontal')
    nav_items = db.Column(db.Text, comment='JSON: Navigation items')
    show_search_in_nav = db.Column(db.Boolean, default=True)
    show_auth_buttons = db.Column(db.Boolean, default=True)
    # Custom code
    custom_css = db.Column(db.Text)
    custom_js = db.Column(db.Text)
    custom_head_code = db.Column(db.Text)
    # SEO
    meta_title = db.Column(db.String(255))
    meta_description = db.Column(db.Text)
    meta_keywords = db.Column(db.Text)
    og_image_url = db.Column(db.String(500))
    favicon_url = db.Column(db.String(500))
    # Feature toggles
    enable_dark_mode = db.Column(db.Boolean, default=True)
    enable_language_switcher = db.Column(db.Boolean, default=False)
    enable_search = db.Column(db.Boolean, default=True)
    enable_wishlist = db.Column(db.Boolean, default=True)
    enable_reviews = db.Column(db.Boolean, default=True)
    enable_certificates = db.Column(db.Boolean, default=True)
    enable_discussions = db.Column(db.Boolean, default=True)
    enable_live_classes = db.Column(db.Boolean, default=True)
    enable_blog = db.Column(db.Boolean, default=False)
    enable_cart = db.Column(db.Boolean, default=True)
    # Analytics tracking
    google_analytics_id = db.Column(db.String(50))
    google_tag_manager_id = db.Column(db.String(50))
    facebook_pixel_id = db.Column(db.String(50))
    # Mobile
    mobile_menu_style = db.Column(db.Enum('slide', 'fullscreen', 'dropdown'), default='slide')
    mobile_bottom_nav = db.Column(db.Boolean, default=False)
    # Animations
    loading_style = db.Column(db.Enum('spinner', 'skeleton', 'progress', 'none'), default='skeleton')
    animations_enabled = db.Column(db.Boolean, default=True)
    animation_speed = db.Column(db.Enum('slow', 'normal', 'fast'), default='normal')
    # Courses layout
    courses_layout = db.Column(db.Enum('grid', 'carousel', 'list'), default='grid')
    courses_per_row = db.Column(db.Integer, default=3)
    show_course_price = db.Column(db.Boolean, default=True)
    show_course_rating = db.Column(db.Boolean, default=True)
    # Timestamps
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    def to_dict(self):
        return {column.name: getattr(self, column.name) for column in self.__table__.columns}


class InstituteTemplate(db.Model):
    """Pre-built website templates"""
    __tablename__ = 'institute_templates'

    id = db.Column(db.String(50), primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    description = db.Column(db.Text)
    thumbnail_url = db.Column(db.String(500))
    preview_url = db.Column(db.String(500))
    category = db.Column(db.Enum('modern', 'classic', 'minimal', 'bold', 'academic'), default='modern')
    is_premium = db.Column(db.Boolean, default=False)
    is_active = db.Column(db.Boolean, default=True)
    default_config = db.Column(db.Text, comment='JSON: Default config for this template')
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    def to_dict(self):
        return {column.name: getattr(self, column.name) for column in self.__table__.columns}


class InstituteWidget(db.Model):
    """Dynamic content widgets for institutes"""
    __tablename__ = 'institute_widgets'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    institute_id = db.Column(db.Integer, db.ForeignKey('institutes.id', ondelete='CASCADE'), nullable=False)
    widget_type = db.Column(db.String(50), nullable=False)
    title = db.Column(db.String(255))
    subtitle = db.Column(db.Text)
    config = db.Column(db.Text, nullable=False, comment='JSON: Widget-specific config')
    content = db.Column(db.Text, comment='JSON: Widget content data')
    position = db.Column(db.String(50), default='content')
    page_target = db.Column(db.String(100), default='all')
    display_order = db.Column(db.Integer, default=0)
    is_active = db.Column(db.Boolean, default=True)
    start_date = db.Column(db.DateTime)
    end_date = db.Column(db.DateTime)
    display_rules = db.Column(db.Text, comment='JSON: Conditional display rules')
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    def to_dict(self):
        return {column.name: getattr(self, column.name) for column in self.__table__.columns}


class InstitutePage(db.Model):
    """Custom pages for institutes"""
    __tablename__ = 'institute_pages'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    institute_id = db.Column(db.Integer, db.ForeignKey('institutes.id', ondelete='CASCADE'), nullable=False)
    slug = db.Column(db.String(100), nullable=False)
    title = db.Column(db.String(255), nullable=False)
    content = db.Column(db.Text)
    page_type = db.Column(db.Enum('static', 'landing', 'course_list', 'instructor_list', 'custom'), default='static')
    template = db.Column(db.String(50), default='default')
    meta_title = db.Column(db.String(255))
    meta_description = db.Column(db.Text)
    is_published = db.Column(db.Boolean, default=False)
    show_in_nav = db.Column(db.Boolean, default=False)
    nav_order = db.Column(db.Integer, default=0)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    def to_dict(self):
        return {column.name: getattr(self, column.name) for column in self.__table__.columns}


class InstituteAnalytics(db.Model):
    """Institute performance analytics"""
    __tablename__ = 'institute_analytics'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    institute_id = db.Column(db.Integer, db.ForeignKey('institutes.id', ondelete='CASCADE'), nullable=False)
    period_type = db.Column(db.Enum('daily', 'weekly', 'monthly', 'yearly'), nullable=False)
    period_start = db.Column(db.Date, nullable=False)
    period_end = db.Column(db.Date, nullable=False)
    new_enrollments = db.Column(db.Integer, default=0)
    total_enrollments = db.Column(db.Integer, default=0)
    course_completions = db.Column(db.Integer, default=0)
    revenue = db.Column(db.Numeric(12, 2), default=0.00)
    new_instructors = db.Column(db.Integer, default=0)
    total_instructors = db.Column(db.Integer, default=0)
    new_courses = db.Column(db.Integer, default=0)
    total_active_courses = db.Column(db.Integer, default=0)
    student_satisfaction_score = db.Column(db.Numeric(3, 2), default=0.00)
    metrics_data = db.Column(db.Text, comment='JSON: Additional analytics')
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    def to_dict(self):
        return {column.name: getattr(self, column.name) for column in self.__table__.columns}


# ============================================
# PAYMENT & COUPON MODELS
# ============================================

class Coupon(db.Model):
    """Coupon codes for discounts — matches actual DB schema"""
    __tablename__ = 'coupons'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    code = db.Column(db.String(50), unique=True, nullable=False)
    name = db.Column(db.String(255), nullable=False)
    description = db.Column(db.Text)
    balance = db.Column(db.Numeric(10, 2), nullable=False, default=0.00)
    initial_balance = db.Column(db.Numeric(10, 2), nullable=False, default=0.00)
    is_active = db.Column(db.Boolean, default=True)
    created_by = db.Column(db.Integer, nullable=True)
    valid_from = db.Column(db.DateTime, default=datetime.utcnow)
    valid_until = db.Column(db.DateTime, nullable=True)
    usage_limit = db.Column(db.Integer, default=None, comment='Max total uses')
    used_count = db.Column(db.Integer, default=0)
    min_purchase_amount = db.Column(db.Numeric(10, 2), default=0.00)
    max_discount_amount = db.Column(db.Numeric(10, 2), nullable=True)
    coupon_type = db.Column(db.Enum('balance', 'percentage', 'fixed'), default='balance')
    discount_value = db.Column(db.Numeric(10, 2), default=0.00)
    applicable_courses = db.Column(db.Text, comment='JSON: Course IDs, null=all')
    applicable_institutes = db.Column(db.Text, comment='JSON: Institute IDs, null=all')
    institute_id = db.Column(db.Integer, nullable=True)
    notes = db.Column(db.Text)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    def to_dict(self):
        return {column.name: getattr(self, column.name) for column in self.__table__.columns}


class PaymentMethod(db.Model):
    """Payment methods with QR codes"""
    __tablename__ = 'payment_methods'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(100), nullable=False)
    method_type = db.Column(db.String(50), nullable=False)
    details = db.Column(db.Text, comment='JSON: Bank/wallet details')
    qr_code_url = db.Column(db.String(500))
    instructions = db.Column(db.Text)
    is_active = db.Column(db.Boolean, default=True)
    display_order = db.Column(db.Integer, default=0)
    institute_id = db.Column(db.Integer, nullable=True)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    def to_dict(self):
        return {column.name: getattr(self, column.name) for column in self.__table__.columns}


class PaymentSubmission(db.Model):
    """Payment screenshot submissions — matches actual DB schema"""
    __tablename__ = 'payment_submissions'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.Integer, nullable=False)
    enrollment_id = db.Column(db.Integer, nullable=True)
    package_id = db.Column(db.Integer, nullable=True)
    payment_method_id = db.Column(db.Integer, nullable=False)
    amount = db.Column(db.Numeric(10, 2), nullable=False)
    screenshot_url = db.Column(db.String(500), nullable=False)
    transaction_id = db.Column(db.String(100))
    notes = db.Column(db.Text)
    status = db.Column(db.Enum('pending', 'verified', 'rejected'), default='pending')
    rejection_reason = db.Column(db.Text)
    submitted_at = db.Column(db.DateTime, default=datetime.utcnow)
    verified_at = db.Column(db.DateTime)
    verified_by = db.Column(db.Integer)

    def to_dict(self):
        return {column.name: getattr(self, column.name) for column in self.__table__.columns}
