from django.db import models
from django.contrib.auth.models import User
import uuid
# Create your models here.
# User.add_to_class('profiles',  models.FileField(upload_to='uploads/', null=True, blank=True, default="../static/dummy.png"))


from decimal import Decimal


class Profiles(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='user_profiles')

    name = models.CharField(max_length=255, null=True)
    phone = models.CharField(max_length=255, null=True)
    email = models.CharField(max_length=255, null=True)
    address = models.CharField(max_length=255, null=True)
    servicename = models.CharField(max_length=255, null=True)
    
    gender = models.CharField(max_length=255, null=True)
    profiles = models.FileField(upload_to='uploads/', null=True, blank=True, default="../static/dummy.png")

    password = models.CharField(max_length=255, null=True)
    gstnumber = models.CharField(max_length=255, null=True)
    pincode = models.CharField(max_length=255, null=True)

    course = models.CharField(max_length=100, blank=True, null=True)
    batch = models.CharField(max_length=50, blank=True, null=True, default="Morning")


    doj = models.DateField(null=True)
    
    gst = models.FileField(upload_to='uploads/', null=True, blank=True)
    companylogo = models.FileField(upload_to='uploads/', null=True, blank=True)
    alteremail = models.CharField(max_length=255, null=True)
    alteremail1 = models.CharField(max_length=255, null=True)
    alteremail2 = models.CharField(max_length=255, null=True)


    pan = models.FileField(upload_to='uploads/', null=True, blank=True)
    role = models.SmallIntegerField(default=0)



    status = models.SmallIntegerField(default=1)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'profile'

# models.py
# ⚠️ CHANGE: Question.exam (ForeignKey) is replaced with Question.course
# (a plain string). This is what actually fixes the recurring
# "Selected exam does not exist" error — a question bank belongs to a
# COURSE, not to one specific student's scheduled exam.
#
# You MUST run migrations after this change:
#   python manage.py makemigrations
#   python manage.py migrate
# Since this changes column structure, if you already have Question rows
# tied to the old `exam` FK, they will need to be re-pointed at a course
# manually (or just delete old test rows if this is still in development).

from django.db import models
from django.contrib.auth.models import User


class Exam(models.Model):
    STATUS_CHOICES = [
        ("Scheduled", "Scheduled"),
        ("Completed", "Completed"),
        ("Cancelled", "Cancelled"),
    ]
    student = models.ForeignKey(User, on_delete=models.PROTECT, related_name="exams")

    title = models.CharField(max_length=255)
    course = models.CharField(max_length=100)          # e.g. "TallyPrime", "Zoho Books"
    date = models.DateField()
    duration = models.CharField(max_length=10)          # stored as "MM:SS", e.g. "30:00"
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default="Scheduled")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title


class Question(models.Model):
    course = models.CharField(max_length=100)     # e.g. "TallyPrime", "Zoho Books" — static dropdown, no FK
    question = models.TextField()
    options = models.JSONField()                   # list of option strings, e.g. ["A", "B", "C", "D"]
    answer = models.CharField(max_length=255)       # must match one of `options`
    marks = models.PositiveIntegerField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.course} — {self.question[:40]}"






# ---------------------------------------------------------------------------
# APPEND this class to your existing models.py (below Exam and Question).
# Then run:
#   python manage.py makemigrations
#   python manage.py migrate
# ---------------------------------------------------------------------------

class ExamAttempt(models.Model):
    """
    One attempt per scheduled Exam (an Exam already belongs to one student).
    The shuffled question order is fixed when the student starts, so a page
    refresh never reshuffles or changes the questions.
    """
    STATUS_CHOICES = [
        ("InProgress", "InProgress"),
        ("Submitted", "Submitted"),
    ]

    exam = models.OneToOneField(Exam, on_delete=models.CASCADE, related_name="attempt")
    question_ids = models.JSONField(default=list)      # shuffled order, e.g. [14, 3, 9, ...]
    answers = models.JSONField(default=dict)           # {"14": "Option text", "3": ""}  ("" = skipped)

    total_questions = models.PositiveIntegerField(default=0)
    correct_count = models.PositiveIntegerField(default=0)
    percentage = models.PositiveIntegerField(default=0)         # score out of 100
    grade = models.CharField(max_length=3, blank=True, default="")

    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default="InProgress")
    started_at = models.DateTimeField(auto_now_add=True)
    submitted_at = models.DateTimeField(null=True, blank=True)

    def __str__(self):
        return f"{self.exam.title} — {self.status}"

class Studentprofiles(models.Model):
    # உங்கள் existing fields எல்லாம் அப்படியே இருக்கும்...

    name = models.CharField(max_length=255, null=True)
    phone = models.CharField(max_length=255, null=True)
    email = models.CharField(max_length=255, null=True)
    location = models.CharField(max_length=255, null=True)


    # NEW
    skills = models.TextField(null=True, blank=True)

    resume = models.FileField(
        upload_to="student_resumes/",
        null=True,
        blank=True
    )

    status = models.SmallIntegerField(default=1)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'studentprofiles'



class Company(models.Model):
    company_name = models.CharField(max_length=200)
    address = models.TextField(blank=True, null=True)
    mobile = models.CharField(max_length=20, blank=True, null=True)
    email = models.EmailField(blank=True, null=True)
    gst_number = models.CharField(max_length=50, blank=True, null=True)
    bank_details = models.TextField(blank=True, null=True)
    logo = models.ImageField(upload_to="company/", blank=True, null=True)

    # --- added to match the client's Excel invoice header ---
    dealers_in = models.CharField(
        max_length=255, blank=True, null=True,
        help_text="Shown on the invoice header, e.g. 'Iron & Steel'"
    )
    invoice_terms = models.TextField(
        blank=True, null=True,
        default=(
            "Interest @ 30% pa will be charged if payment not made within 20 days.\n"
            "Goods once sold cannot be taken back or exchanged.\n"
            "Our responsibility ceases once goods leave our godown.\n"
            "All disputes are subject to Chennai jurisdiction."
        ),
        help_text="Printed as footer notes/terms on every invoice PDF.",
    )

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.company_name


class Customer(models.Model):
    name = models.CharField(max_length=200)
    address = models.TextField(blank=True, null=True)
    gst_number = models.CharField(max_length=50, blank=True, null=True)
    mobile = models.CharField(max_length=20, blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name
 
class Course(models.Model):
    name = models.CharField(max_length=100, unique=True)   # e.g. "TallyPrime", "Zoho Books"
    created_at = models.DateTimeField(auto_now_add=True)
 
    class Meta:
        ordering = ["name"]
 
    def __str__(self):
        return self.name

class SeoSettings(models.Model):
    page_slug = models.CharField(max_length=100, unique=True)   # home, about, courses...
    meta_title = models.CharField(max_length=255)
    meta_description = models.TextField()
    meta_keywords = models.TextField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "seo_settings"
        ordering = ["page_slug"]

    def __str__(self):
        return self.page_slug


class Product(models.Model):
    name = models.CharField(max_length=200)
    hsn_code = models.CharField(max_length=50, blank=True, null=True)
    default_rate = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal("0.00"))
    unit = models.CharField(max_length=50, default="Kg")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name


class Invoice(models.Model):
    invoice_number = models.CharField(max_length=50, unique=True)
    invoice_date = models.DateField()
    customer = models.ForeignKey(Customer, on_delete=models.PROTECT, related_name="invoices")

    # --- added to match the client's Excel invoice header ---
    eway_bill_no = models.CharField(max_length=50, blank=True, null=True)
    eway_bill_date = models.DateField(blank=True, null=True)
    vehicle_no = models.CharField(max_length=50, blank=True, null=True)

    subtotal = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal("0.00"))  # "Gross Total"
    cgst = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal("0.00"))
    sgst = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal("0.00"))
    igst = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal("0.00"))  # inter-state tax
    round_off = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal("0.00"))
    grand_total = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal("0.00"))  # "Net Total"

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.invoice_number


class InvoiceItem(models.Model):
    invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE, related_name="items")
    product = models.ForeignKey(Product, on_delete=models.PROTECT, related_name="invoice_items")
    quantity = models.DecimalField(max_digits=12, decimal_places=2)
    rate = models.DecimalField(max_digits=12, decimal_places=2)
    amount = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal("0.00"))

    def __str__(self):
        return f"{self.invoice.invoice_number} - {self.product.name}"