from django.shortcuts import render
from .models import Parcel
from django.utils import timezone
import datetime

def index(request):
    # If no parcels, create some demo data.
    if not Parcel.objects.exists():
        Parcel.objects.create(
            sender_name='John Doe',
            sender_email='john.doe@example.com',
            recipient_name='Jane Smith',
            recipient_email='jane.smith@example.com',
            tracking_number='JD123456789',
            status='pending',
            assignee_first_name='John',
            assignee_last_name='Smith',
            received_date=timezone.now() - datetime.timedelta(days=1)
        )
        Parcel.objects.create(
            sender_name='Peter Jones',
            sender_email='peter.jones@example.com',
            recipient_name='Mary Williams',
            recipient_email='mary.williams@example.com',
            tracking_number='PJ987654321',
            status='processed',
            assignee_first_name='Jane',
            assignee_last_name='Doe',
            received_date=timezone.now() - datetime.timedelta(hours=5)
        )
        Parcel.objects.create(
            sender_name='Susan Brown',
            sender_email='susan.brown@example.com',
            recipient_name='David Miller',
            recipient_email='david.miller@example.com',
            tracking_number='SB112233445',
            status='rejected',
            assignee_first_name='Peter',
            assignee_last_name='Jones',
            received_date=timezone.now() - datetime.timedelta(days=2)
        )

    parcels = Parcel.objects.all().order_by('-received_date')
    context = {
        'parcels': parcels,
        'page_title': 'Mail Screening Portal'
    }
    return render(request, 'core/index.html', context)