
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MinValueValidator, MaxValueValidator
from datetime import date

class Customer(models.Model):
    """مدل مشتریان"""
    GENDER_CHOICES = [
        ('M', 'Male'),
        ('F', 'Female'),
    ]
    
    user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True, blank=True)
    name = models.CharField(max_length=200)
    passport_no = models.CharField(max_length=50, unique=True)
    phone = models.CharField(max_length=20)
    email = models.EmailField(blank=True, null=True)
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES, blank=True)
    date_of_birth = models.DateField(null=True, blank=True)
    address = models.TextField(blank=True)
    notes = models.TextField(blank=True, help_text="Special requirements, medical conditions, etc.")
    
    # آماری
    total_tickets = models.IntegerField(default=0)
    total_visas = models.IntegerField(default=0)
    total_spent = models.DecimalField(max_digits=10, decimal_places=2, default=0)
    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    def __str__(self):
        return f"{self.name} ({self.passport_no})"
    
    class Meta:
        ordering = ['-created_at']


class Airline(models.Model):
    """مدل خطوط هوایی"""
    code = models.CharField(max_length=2, unique=True)  # RQ, FG, TK, etc.
    name = models.CharField(max_length=100)
    commission = models.IntegerField(default=5, help_text="Commission percentage")
    contact = models.CharField(max_length=100)
    balance = models.DecimalField(max_digits=12, decimal_places=2, default=0)
    status = models.CharField(max_length=20, default='Active')
    details = models.TextField(blank=True)
    
    def __str__(self):
        return f"{self.code} - {self.name}"


class Flight(models.Model):
    """مدل پروازها"""
    airline = models.ForeignKey(Airline, on_delete=models.CASCADE)
    flight_no = models.CharField(max_length=10)
    origin = models.CharField(max_length=100)  # مبدأ
    destination = models.CharField(max_length=100)  # مقصد
    departure_date = models.DateField()
    departure_time = models.TimeField(null=True, blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    available_seats = models.IntegerField(default=50)
    total_seats = models.IntegerField(default=50)
    is_manual = models.BooleanField(default=False, help_text="Added manually by admin")
    
    def __str__(self):
        return f"{self.airline.name} {self.flight_no}: {self.origin} → {self.destination} ({self.departure_date})"
    
    class Meta:
        ordering = ['departure_date', 'departure_time']


class Booking(models.Model):
    """مدل رزرو بلیط"""
    STATUS_CHOICES = [
        ('pending', 'Pending'),
        ('confirmed', 'Confirmed'),
        ('cancelled', 'Cancelled'),
        ('completed', 'Completed'),
    ]
    
    SOURCE_CHOICES = [
        ('online', 'Online Website'),
        ('phone', 'Phone Call'),
        ('walkin', 'Walk-in Customer'),
    ]
    
    booking_ref = models.CharField(max_length=20, unique=True)
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    flight = models.ForeignKey(Flight, on_delete=models.CASCADE)
    passenger_name = models.CharField(max_length=200)
    passenger_passport = models.CharField(max_length=50)
    passenger_phone = models.CharField(max_length=20)
    passenger_email = models.EmailField(blank=True)
    
    route_display = models.CharField(max_length=200)  # "Kabul → Dubai"
    travel_date = models.DateField()
    amount = models.DecimalField(max_digits=10, decimal_places=2)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending')
    source = models.CharField(max_length=20, choices=SOURCE_CHOICES, default='phone')
    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    def __str__(self):
        return f"{self.booking_ref} - {self.customer.name} - {self.status}"
    
    class Meta:
        ordering = ['-created_at']


class VisaRequest(models.Model):
    """مدل درخواست ویزا"""
    COUNTRY_CHOICES = [
        ('Turkey', 'Turkey'),
        ('Tajikistan', 'Tajikistan'),
        ('India', 'India'),
        ('Pakistan', 'Pakistan'),
        ('UAE', 'United Arab Emirates'),
        ('Saudi Arabia', 'Saudi Arabia'),
        ('Qatar', 'Qatar'),
        ('Oman', 'Oman'),
    ]
    
    VISA_TYPE_CHOICES = [
        ('Tourist', 'Tourist Visa'),
        ('Business', 'Business Visa'),
        ('Medical', 'Medical Visa'),
        ('Student', 'Student Visa'),
        ('Transit', 'Transit Visa'),
    ]
    
    CATEGORY_CHOICES = [
        ('Individual', 'Individual'),
        ('Family', 'Family'),
        ('Group', 'Group'),
    ]
    
    STATUS_CHOICES = [
        ('pending_docs', 'Pending Documents'),
        ('processing', 'Processing'),
        ('at_embassy', 'At Embassy'),
        ('approved', 'Approved'),
        ('rejected', 'Rejected'),
        ('ready', 'Ready for Collection'),
    ]
    
    visa_ref = models.CharField(max_length=20, unique=True)
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    passport_no = models.CharField(max_length=50)
    phone = models.CharField(max_length=20)
    email = models.EmailField(blank=True)
    
    country = models.CharField(max_length=50, choices=COUNTRY_CHOICES)
    visa_type = models.CharField(max_length=20, choices=VISA_TYPE_CHOICES)
    category = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default='Individual')
    urgency = models.CharField(max_length=20, default='Normal')
    
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending_docs')
    fee = models.DecimalField(max_digits=10, decimal_places=2)
    details = models.TextField(blank=True)
    
    submitted_date = models.DateField(auto_now_add=True)
    updated_date = models.DateField(auto_now=True)
    
    # مدارک آپلودی (فقط مسیر فایل)
    passport_copy = models.FileField(upload_to='visa_documents/', blank=True, null=True)
    photo = models.FileField(upload_to='visa_documents/', blank=True, null=True)
    id_card = models.FileField(upload_to='visa_documents/', blank=True, null=True)
    education_doc = models.FileField(upload_to='visa_documents/', blank=True, null=True)
    medical_doc = models.FileField(upload_to='visa_documents/', blank=True, null=True)
    
    def __str__(self):
        return f"{self.visa_ref} - {self.customer.name} - {self.country}"
    
    class Meta:
        ordering = ['-submitted_date']


class Wallet(models.Model):
    """مدل کیف پول مشتری"""
    customer = models.OneToOneField(Customer, on_delete=models.CASCADE)
    balance = models.DecimalField(max_digits=10, decimal_places=2, default=0)
    total_deposited = models.DecimalField(max_digits=12, decimal_places=2, default=0)
    total_withdrawn = models.DecimalField(max_digits=12, decimal_places=2, default=0)
    last_transaction_date = models.DateField(null=True, blank=True)
    
    def __str__(self):
        return f"{self.customer.name} - Balance: ${self.balance}"


class WalletTransaction(models.Model):
    """مدل تراکنش‌های کیف پول"""
    TRANSACTION_TYPE = [
        ('deposit', 'Deposit'),
        ('withdrawal', 'Withdrawal'),
    ]
    
    wallet = models.ForeignKey(Wallet, on_delete=models.CASCADE)
    transaction_type = models.CharField(max_length=20, choices=TRANSACTION_TYPE)
    amount = models.DecimalField(max_digits=10, decimal_places=2)
    reference = models.CharField(max_length=100, blank=True)
    notes = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    
    def __str__(self):
        return f"{self.transaction_type} - ${self.amount} - {self.wallet.customer.name}"
    
    class Meta:
        ordering = ['-created_at']


class MoneyTransaction(models.Model):
    """مدل تراکنش‌های مالی عمومی (درآمد/هزینه)"""
    TRANSACTION_DIRECTION = [
        ('in', 'Money In'),
        ('out', 'Money Out'),
    ]
    
    PAYMENT_METHODS = [
        ('cash', 'Cash'),
        ('bank', 'Bank Transfer'),
        ('card', 'Credit Card'),
        ('crypto', 'Cryptocurrency'),
    ]
    
    direction = models.CharField(max_length=3, choices=TRANSACTION_DIRECTION)
    amount = models.DecimalField(max_digits=12, decimal_places=2)
    party = models.CharField(max_length=200, help_text="Customer or Supplier name")
    category = models.CharField(max_length=100)
    payment_method = models.CharField(max_length=20, choices=PAYMENT_METHODS)
    reference = models.CharField(max_length=100, blank=True)
    description = models.TextField(blank=True)
    status = models.CharField(max_length=20, default='paid')
    transaction_date = models.DateField(auto_now_add=True)
    
    def __str__(self):
        return f"{self.direction.upper()} - ${self.amount} - {self.party}"
    
    class Meta:
        ordering = ['-transaction_date']