from django.db import models
from django.contrib.auth.hashers import make_password, check_password

class Login(models.Model):
    username = models.CharField(max_length=150, unique=True)
    print(f"Checking login for: {username}")


    password = models.CharField(max_length=255)  # Store hashed passwords
    user_type = models.CharField(max_length=10, choices=[('kds', 'KDS'), ('agent', 'Agent')])

    def save(self, *args, **kwargs):
        if not self.password.startswith("pbkdf2_sha256$"):  # Prevent rehashing
            self.password = make_password(self.password)
        super().save(*args, **kwargs)

    def check_password(self, raw_password):
        return check_password(raw_password, self.password)

    def __str__(self):
        return self.username


class TravelBill(models.Model):
    guest_name = models.CharField(max_length=255)
    cell_no = models.CharField(max_length=10)
    vehicle_type = models.CharField(max_length=100)
    vehicle_details = models.CharField(max_length=255, null=True, blank=True)
    from_date_time = models.DateTimeField()
    to_date_time = models.DateTimeField()
    visit_places = models.TextField()
    opening_kms = models.IntegerField()
    closing_kms = models.IntegerField()
    total_kms = models.IntegerField(default=0)  
    amt = models.DecimalField(max_digits=10, decimal_places=2)
    night = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
    toll = models.DecimalField(max_digits=10, decimal_places=2)
    total_amount = models.DecimalField(max_digits=10, decimal_places=2, default=0)
    driver_name = models.CharField(max_length=255, null=True, blank=True)
    driver_mobile = models.CharField(max_length=10, null=True, blank=True)
    document = models.FileField(upload_to='documents/', null=True, blank=True)

  

def save(self, *args, **kwargs):
    try:
        # Convert to integers before performing subtraction
        self.opening_kms = int(self.opening_kms)
        self.closing_kms = int(self.closing_kms)
        self.total_kms = self.closing_kms - self.opening_kms
    except ValueError:
        raise ValueError("opening_kms and closing_kms must be numeric values")
    
    super().save(*args, **kwargs)
    def __str__(self):
        return f"Bill for {self.guest_name} - {self.vehicle_type}"


