# setup_all_modules.py
import os
import sys

def create_directory_structure():
    base_dir = os.path.dirname(os.path.abspath(__file__))
    
    print("🚀 CREATING COMPLETE SCHOOL MANAGEMENT SYSTEM")
    print("=" * 60)
    
    # Create all template directories
    directories = [
        'templates/students',
        'templates/academics',
        'templates/attendance',
        'templates/finance',
        'templates/parents',
        'templates/reports',
        'templates/communication',
        'templates/auth',
    ]
    
    for directory in directories:
        dir_path = os.path.join(base_dir, directory)
        os.makedirs(dir_path, exist_ok=True)
        print(f"✅ Created: {directory}")
    
    return base_dir

def create_student_portal(base_dir):
    print("\n🎓 CREATING STUDENT PORTAL...")
    
    # Create student list view
    student_views = '''# students/views.py
from django.views.generic import ListView, DetailView, CreateView, UpdateView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy
from django.db.models import Q
from .models import Student, ParentGuardian

class StudentListView(LoginRequiredMixin, ListView):
    model = Student
    template_name = 'students/student_list.html'
    context_object_name = 'students'
    paginate_by = 20
    
    def get_queryset(self):
        queryset = super().get_queryset()
        
        # Search functionality
        search_query = self.request.GET.get('q', '')
        if search_query:
            queryset = queryset.filter(
                Q(first_name__icontains=search_query) |
                Q(last_name__icontains=search_query) |
                Q(student_id__icontains=search_query) |
                Q(home_address__icontains=search_query)
            )
        
        # Filter by class
        class_filter = self.request.GET.get('class')
        if class_filter:
            queryset = queryset.filter(current_class=class_filter)
        
        # Filter by status
        status_filter = self.request.GET.get('status')
        if status_filter:
            queryset = queryset.filter(status=status_filter)
        
        return queryset.order_by('-admission_date')
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['total_students'] = Student.objects.count()
        context['active_students'] = Student.objects.filter(status='active').count()
        
        # Get unique classes for filter dropdown
        from academics.models import SchoolClass
        context['all_classes'] = SchoolClass.objects.all()
        
        return context

class StudentDetailView(LoginRequiredMixin, DetailView):
    model = Student
    template_name = 'students/student_detail.html'
    context_object_name = 'student'
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # Add attendance records
        from academics.models import Attendance
        context['attendance_records'] = Attendance.objects.filter(
            student=self.object
        ).order_by('-date')[:10]
        
        # Add fee records
        from finance.models import Invoice
        context['invoice_records'] = Invoice.objects.filter(
            student=self.object
        ).order_by('-created_at')[:10]
        
        return context

class StudentCreateView(LoginRequiredMixin, CreateView):
    model = Student
    template_name = 'students/student_form.html'
    fields = '__all__'
    success_url = reverse_lazy('student_list')
    
class StudentUpdateView(LoginRequiredMixin, UpdateView):
    model = Student
    template_name = 'students/student_form.html'
    fields = '__all__'
    success_url = reverse_lazy('student_list')
'''
    
    views_path = os.path.join(base_dir, 'students', 'views.py')
    with open(views_path, 'w', encoding='utf-8') as f:
        f.write(student_views)
    print("✅ Created: students/views.py")
    
    # Create student list template
    student_list_template = '''{% extends 'base.html' %}
{% load static %}

{% block title %}Students - Rapha-Bethel BNPS{% endblock %}

{% block extra_css %}
<style>
    .student-card {
        transition: transform 0.3s;
    }
    .student-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    }
    .student-avatar {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        background: #4CAF50;
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.5rem;
        font-weight: bold;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- Page Header -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h1 class="h3 mb-0 text-gray-800">Students</h1>
            <p class="text-muted">Total: {{ total_students }} | Active: {{ active_students }}</p>
        </div>
        <div>
            <a href="/admin/students/student/add/" class="btn btn-primary">
                <i class="fas fa-user-plus"></i> Add New Student
            </a>
            <a href="/students/export/" class="btn btn-outline-secondary">
                <i class="fas fa-download"></i> Export
            </a>
        </div>
    </div>

    <!-- Search and Filter Card -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">Search & Filter</h6>
        </div>
        <div class="card-body">
            <form method="get" class="row g-3">
                <div class="col-md-5">
                    <div class="input-group">
                        <input type="text" class="form-control" name="q" 
                               placeholder="Search by name, ID, or address..." 
                               value="{{ request.GET.q }}">
                        <button class="btn btn-primary" type="submit">
                            <i class="fas fa-search"></i>
                        </button>
                    </div>
                </div>
                <div class="col-md-3">
                    <select class="form-control" name="class">
                        <option value="">All Classes</option>
                        {% for class in all_classes %}
                        <option value="{{ class.id }}" 
                                {% if request.GET.class == class.id|stringformat:"s" %}selected{% endif %}>
                            {{ class }}
                        </option>
                        {% endfor %}
                    </select>
                </div>
                <div class="col-md-2">
                    <select class="form-control" name="status">
                        <option value="">All Status</option>
                        <option value="active" {% if request.GET.status == 'active' %}selected{% endif %}>Active</option>
                        <option value="inactive" {% if request.GET.status == 'inactive' %}selected{% endif %}>Inactive</option>
                        <option value="graduated" {% if request.GET.status == 'graduated' %}selected{% endif %}>Graduated</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-filter"></i> Filter
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Students Grid/Table -->
    <div class="row">
        {% for student in students %}
        <div class="col-xl-3 col-md-4 col-sm-6 mb-4">
            <div class="card student-card h-100">
                <div class="card-body">
                    <div class="d-flex align-items-start mb-3">
                        <div class="student-avatar me-3">
                            {{ student.first_name.0 }}{{ student.last_name.0 }}
                        </div>
                        <div>
                            <h5 class="card-title mb-1">{{ student.first_name }} {{ student.last_name }}</h5>
                            <p class="text-muted small mb-0">ID: {{ student.student_id }}</p>
                            {% if student.current_class %}
                            <span class="badge bg-info">{{ student.current_class }}</span>
                            {% endif %}
                        </div>
                    </div>
                    
                    <div class="student-info mb-3">
                        <p class="mb-1">
                            <i class="fas fa-birthday-cake text-primary me-2"></i>
                            {{ student.date_of_birth|date:"d M Y" }} ({{ student.get_age }} yrs)
                        </p>
                        <p class="mb-1">
                            <i class="fas fa-venus-mars text-primary me-2"></i>
                            {{ student.get_gender_display }}
                        </p>
                        <p class="mb-1">
                            <i class="fas fa-calendar-alt text-primary me-2"></i>
                            Admitted: {{ student.admission_date|date:"d M Y" }}
                        </p>
                    </div>
                    
                    <div class="d-flex justify-content-between align-items-center">
                        <span class="badge bg-{{ student.status }}">
                            {{ student.status|title }}
                        </span>
                        <div>
                            <a href="{% url 'student_detail' student.pk %}" 
                               class="btn btn-sm btn-outline-primary">
                                <i class="fas fa-eye"></i>
                            </a>
                            <a href="/admin/students/student/{{ student.pk }}/change/" 
                               class="btn btn-sm btn-outline-warning">
                                <i class="fas fa-edit"></i>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        {% empty %}
        <div class="col-12">
            <div class="text-center py-5">
                <i class="fas fa-users fa-3x text-muted mb-3"></i>
                <h4 class="text-muted">No students found</h4>
                <p class="text-muted">Try adjusting your search or add a new student</p>
                <a href="/admin/students/student/add/" class="btn btn-primary">
                    <i class="fas fa-user-plus"></i> Add First Student
                </a>
            </div>
        </div>
        {% endfor %}
    </div>

    <!-- Pagination -->
    {% if is_paginated %}
    <nav aria-label="Page navigation" class="mt-4">
        <ul class="pagination justify-content-center">
            {% if page_obj.has_previous %}
            <li class="page-item">
                <a class="page-link" href="?page={{ page_obj.previous_page_number }}{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}">
                    Previous
                </a>
            </li>
            {% endif %}
            
            {% for num in page_obj.paginator.page_range %}
            {% if page_obj.number == num %}
            <li class="page-item active">
                <a class="page-link" href="#">{{ num }}</a>
            </li>
            {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
            <li class="page-item">
                <a class="page-link" href="?page={{ num }}{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}">
                    {{ num }}
                </a>
            </li>
            {% endif %}
            {% endfor %}
            
            {% if page_obj.has_next %}
            <li class="page-item">
                <a class="page-link" href="?page={{ page_obj.next_page_number }}{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}">
                    Next
                </a>
            </li>
            {% endif %}
        </ul>
    </nav>
    {% endif %}
</div>
{% endblock %}
'''
    
    list_path = os.path.join(base_dir, 'templates', 'students', 'student_list.html')
    with open(list_path, 'w', encoding='utf-8') as f:
        f.write(student_list_template)
    print("✅ Created: templates/students/student_list.html")

def create_attendance_module(base_dir):
    print("\n📊 CREATING ATTENDANCE MODULE...")
    
    # Create attendance views
    attendance_views = '''# academics/views.py (attendance section)
from django.views.generic import ListView, CreateView, TemplateView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render, redirect
from django.contrib import messages
from django.db.models import Count, Q
from datetime import date, timedelta
from .models import Attendance, SchoolClass

class AttendanceMarkingView(LoginRequiredMixin, TemplateView):
    template_name = 'attendance/mark.html'
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        today = date.today()
        
        # Get classes
        context['classes'] = SchoolClass.objects.all()
        
        # Get selected class
        class_id = self.request.GET.get('class')
        if class_id:
            try:
                selected_class = SchoolClass.objects.get(id=class_id)
                context['selected_class'] = selected_class
                
                # Get students in this class
                from students.models import Student
                students = Student.objects.filter(current_class=selected_class, status='active')
                context['students'] = students
                
                # Get today's attendance for these students
                attendance_today = Attendance.objects.filter(
                    date=today,
                    student__in=students
                ).select_related('student')
                
                # Create attendance dict for quick lookup
                attendance_dict = {att.student_id: att.status for att in attendance_today}
                context['attendance_dict'] = attendance_dict
                
            except SchoolClass.DoesNotExist:
                pass
        
        context['today'] = today
        return context
    
    def post(self, request, *args, **kwargs):
        today = date.today()
        class_id = request.POST.get('class_id')
        
        if class_id:
            from students.models import Student
            students = Student.objects.filter(current_class_id=class_id, status='active')
            
            for student in students:
                status = request.POST.get(f'status_{student.id}', 'absent')
                
                # Update or create attendance record
                Attendance.objects.update_or_create(
                    student=student,
                    date=today,
                    defaults={
                        'school_class_id': class_id,
                        'status': status,
                        'remarks': request.POST.get(f'remarks_{student.id}', '')
                    }
                )
            
            messages.success(request, f'Attendance marked successfully for {today}')
            return redirect(f'/attendance/mark/?class={class_id}')
        
        return redirect('/attendance/mark/')

class AttendanceListView(LoginRequiredMixin, ListView):
    model = Attendance
    template_name = 'attendance/list.html'
    context_object_name = 'attendances'
    paginate_by = 50
    
    def get_queryset(self):
        queryset = super().get_queryset().select_related('student', 'school_class')
        
        # Date filter
        date_filter = self.request.GET.get('date')
        if date_filter:
            queryset = queryset.filter(date=date_filter)
        else:
            # Default to today
            queryset = queryset.filter(date=date.today())
        
        # Class filter
        class_filter = self.request.GET.get('class')
        if class_filter:
            queryset = queryset.filter(school_class_id=class_filter)
        
        # Status filter
        status_filter = self.request.GET.get('status')
        if status_filter:
            queryset = queryset.filter(status=status_filter)
        
        return queryset.order_by('-date', 'school_class', 'student__first_name')
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['classes'] = SchoolClass.objects.all()
        context['today'] = date.today()
        return context

class AttendanceReportView(LoginRequiredMixin, TemplateView):
    template_name = 'attendance/report.html'
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        from datetime import datetime
        
        # Get date range (default: this month)
        year = self.request.GET.get('year', datetime.now().year)
        month = self.request.GET.get('month', datetime.now().month)
        
        # Get attendance summary
        from django.db.models import Count, Case, When, IntegerField
        from django.db.models.functions import TruncMonth
        
        summary = Attendance.objects.filter(
            date__year=year,
            date__month=month
        ).values('school_class__name').annotate(
            total=Count('id'),
            present=Count(Case(When(status='present', then=1), output_field=IntegerField())),
            absent=Count(Case(When(status='absent', then=1), output_field=IntegerField())),
            late=Count(Case(When(status='late', then=1), output_field=IntegerField())),
        ).order_by('school_class__name')
        
        context['summary'] = summary
        context['selected_year'] = year
        context['selected_month'] = month
        
        return context
'''
    
    # Create attendance views file or append to existing
    views_path = os.path.join(base_dir, 'academics', 'views.py')
    if os.path.exists(views_path):
        with open(views_path, 'a', encoding='utf-8') as f:
            f.write('\n\n' + attendance_views)
    else:
        with open(views_path, 'w', encoding='utf-8') as f:
            f.write(attendance_views)
    print("✅ Created/updated: academics/views.py")
    
    # Create attendance templates
    attendance_mark_template = '''{% extends 'base.html' %}
{% load static %}

{% block title %}Mark Attendance - Rapha-Bethel BNPS{% endblock %}

{% block extra_css %}
<style>
    .attendance-btn {
        width: 100px;
    }
    .status-present { background-color: #d4edda !important; }
    .status-absent { background-color: #f8d7da !important; }
    .status-late { background-color: #fff3cd !important; }
    .status-excused { background-color: #d1ecf1 !important; }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="h3 mb-0 text-gray-800">Mark Attendance</h1>
        <div class="btn-group">
            <a href="/attendance/" class="btn btn-outline-primary">
                <i class="fas fa-list"></i> View Attendance
            </a>
            <a href="/attendance/report/" class="btn btn-outline-secondary">
                <i class="fas fa-chart-pie"></i> Reports
            </a>
        </div>
    </div>

    <!-- Class Selection -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">Select Class</h6>
        </div>
        <div class="card-body">
            <form method="get" class="row g-3">
                <div class="col-md-6">
                    <select class="form-control" name="class" onchange="this.form.submit()">
                        <option value="">-- Select Class --</option>
                        {% for class in classes %}
                        <option value="{{ class.id }}" 
                                {% if selected_class.id == class.id %}selected{% endif %}>
                            {{ class.name }} ({{ class.level|upper }} - {{ class.section }})
                        </option>
                        {% endfor %}
                    </select>
                </div>
            </form>
        </div>
    </div>

    {% if selected_class %}
    <!-- Attendance Form -->
    <div class="card shadow">
        <div class="card-header py-3 d-flex justify-content-between align-items-center">
            <h6 class="m-0 font-weight-bold text-primary">
                {{ selected_class.name }} - {{ today|date:"d M Y" }}
            </h6>
            <div>
                <span class="badge bg-success">Present: ✅</span>
                <span class="badge bg-danger">Absent: ❌</span>
                <span class="badge bg-warning">Late: ⏰</span>
                <span class="badge bg-info">Excused: 📝</span>
            </div>
        </div>
        <div class="card-body">
            <form method="post">
                {% csrf_token %}
                <input type="hidden" name="class_id" value="{{ selected_class.id }}">
                
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>Roll No.</th>
                                <th>Student Name</th>
                                <th>Attendance Status</th>
                                <th>Remarks</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for student in students %}
                            {% with status=attendance_dict|get_item:student.id %}
                            <tr class="status-{{ status|default:'absent' }}">
                                <td>{{ forloop.counter }}</td>
                                <td>
                                    <strong>{{ student.first_name }} {{ student.last_name }}</strong><br>
                                    <small class="text-muted">ID: {{ student.student_id }}</small>
                                </td>
                                <td>
                                    <div class="btn-group btn-group-sm" role="group">
                                        <input type="radio" class="btn-check" name="status_{{ student.id }}" 
                                               id="present_{{ student.id }}" value="present" 
                                               {% if status == 'present' %}checked{% endif %} autocomplete="off">
                                        <label class="btn btn-outline-success" for="present_{{ student.id }}">
                                            ✅ Present
                                        </label>
                                        
                                        <input type="radio" class="btn-check" name="status_{{ student.id }}" 
                                               id="absent_{{ student.id }}" value="absent"
                                               {% if not status or status == 'absent' %}checked{% endif %} autocomplete="off">
                                        <label class="btn btn-outline-danger" for="absent_{{ student.id }}">
                                            ❌ Absent
                                        </label>
                                        
                                        <input type="radio" class="btn-check" name="status_{{ student.id }}" 
                                               id="late_{{ student.id }}" value="late"
                                               {% if status == 'late' %}checked{% endif %} autocomplete="off">
                                        <label class="btn btn-outline-warning" for="late_{{ student.id }}">
                                            ⏰ Late
                                        </label>
                                        
                                        <input type="radio" class="btn-check" name="status_{{ student.id }}" 
                                               id="excused_{{ student.id }}" value="excused"
                                               {% if status == 'excused' %}checked{% endif %} autocomplete="off">
                                        <label class="btn btn-outline-info" for="excused_{{ student.id }}">
                                            📝 Excused
                                        </label>
                                    </div>
                                </td>
                                <td>
                                    <input type="text" class="form-control form-control-sm" 
                                           name="remarks_{{ student.id }}" 
                                           placeholder="Remarks (optional)" 
                                           value="{{ attendance_dict|get_item:student.id }}">
                                </td>
                            </tr>
                            {% endwith %}
                            {% empty %}
                            <tr>
                                <td colspan="4" class="text-center py-4">
                                    <i class="fas fa-users-slash fa-2x text-muted mb-3"></i>
                                    <p class="text-muted">No students in this class</p>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
                
                <div class="mt-4 text-center">
                    <button type="submit" class="btn btn-primary btn-lg px-5">
                        <i class="fas fa-save"></i> Save Attendance
                    </button>
                    <a href="/attendance/" class="btn btn-secondary btn-lg px-5">
                        <i class="fas fa-times"></i> Cancel
                    </a>
                </div>
            </form>
        </div>
    </div>
    {% endif %}
</div>
{% endblock %}

{% block extra_js %}
<script>
// Add custom template filter for dictionary lookup
if (typeof django !== 'undefined' && django.jQuery) {
    django.jQuery.extend(django.jQuery.fn, {
        get_item: function(key) {
            return this[key];
        }
    });
}

// Quick status selection with keyboard shortcuts
document.addEventListener('keydown', function(e) {
    if (e.ctrlKey) {
        const rows = document.querySelectorAll('tbody tr');
        const currentRow = document.activeElement.closest('tr');
        if (currentRow) {
            const index = Array.from(rows).indexOf(currentRow);
            if (index !== -1) {
                switch(e.key) {
                    case '1': // Present
                        rows[index].querySelector('input[value="present"]').click();
                        break;
                    case '2': // Absent
                        rows[index].querySelector('input[value="absent"]').click();
                        break;
                    case '3': // Late
                        rows[index].querySelector('input[value="late"]').click();
                        break;
                    case '4': // Excused
                        rows[index].querySelector('input[value="excused"]').click();
                        break;
                }
            }
        }
    }
});
</script>
{% endblock %}
'''
    
    mark_path = os.path.join(base_dir, 'templates', 'attendance', 'mark.html')
    with open(mark_path, 'w', encoding='utf-8') as f:
        f.write(attendance_mark_template)
    print("✅ Created: templates/attendance/mark.html")

def create_finance_module(base_dir):
    print("\n💰 CREATING FINANCE MODULE...")
    
    # Create finance templates
    finance_invoices = '''{% extends 'base.html' %}
{% load static %}

{% block title %}Invoices - Rapha-Bethel BNPS{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="h3 mb-0 text-gray-800">Fee Invoices</h1>
        <div class="btn-group">
            <a href="/finance/invoices/create/" class="btn btn-primary">
                <i class="fas fa-plus"></i> Create Invoice
            </a>
            <a href="/finance/invoices/export/" class="btn btn-outline-secondary">
                <i class="fas fa-download"></i> Export
            </a>
        </div>
    </div>

    <!-- Stats Cards -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card border-left-primary shadow h-100 py-2">
                <div class="card-body">
                    <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                        Total Invoices
                    </div>
                    <div class="h5 mb-0 font-weight-bold text-gray-800">$24,000</div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-left-success shadow h-100 py-2">
                <div class="card-body">
                    <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                        Paid Invoices
                    </div>
                    <div class="h5 mb-0 font-weight-bold text-gray-800">$18,500</div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-left-warning shadow h-100 py-2">
                <div class="card-body">
                    <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                        Pending Invoices
                    </div>
                    <div class="h5 mb-0 font-weight-bold text-gray-800">$4,200</div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-left-danger shadow h-100 py-2">
                <div class="card-body">
                    <div class="text-xs font-weight-bold text-danger text-uppercase mb-1">
                        Overdue Invoices
                    </div>
                    <div class="h5 mb-0 font-weight-bold text-gray-800">$1,300</div>
                </div>
            </div>
        </div>
    </div>

    <!-- Invoices Table -->
    <div class="card shadow">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">All Invoices</h6>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>Invoice #</th>
                            <th>Student</th>
                            <th>Class</th>
                            <th>Amount</th>
                            <th>Due Date</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Sample data - replace with actual data -->
                        <tr>
                            <td>INV-2024-001</td>
                            <td>John Doe</td>
                            <td>Class 5A</td>
                            <td>$500.00</td>
                            <td>15 Dec 2024</td>
                            <td><span class="badge bg-success">Paid</span></td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary">
                                    <i class="fas fa-eye"></i>
                                </button>
                                <button class="btn btn-sm btn-outline-warning">
                                    <i class="fas fa-edit"></i>
                                </button>
                            </td>
                        </tr>
                        <tr>
                            <td>INV-2024-002</td>
                            <td>Jane Smith</td>
                            <td>Class 6B</td>
                            <td>$500.00</td>
                            <td>15 Dec 2024</td>
                            <td><span class="badge bg-warning">Pending</span></td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary">
                                    <i class="fas fa-eye"></i>
                                </button>
                                <button class="btn btn-sm btn-outline-warning">
                                    <i class="fas fa-edit"></i>
                                </button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
{% endblock %}
'''
    
    invoices_path = os.path.join(base_dir, 'templates', 'finance', 'invoices.html')
    with open(invoices_path, 'w', encoding='utf-8') as f:
        f.write(finance_invoices)
    print("✅ Created: templates/finance/invoices.html")

def create_urls_config(base_dir):
    print("\n🔗 CREATING URL CONFIGURATION...")
    
    urls_content = '''# backend/urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from core.views import HomeView, DashboardView

urlpatterns = [
    # Home & Dashboard
    path('', HomeView.as_view(), name='home'),
    path('dashboard/', DashboardView.as_view(), name='dashboard'),
    
    # Students
    path('students/', include('students.urls')),
    
    # Academics
    path('attendance/', include('academics.urls_attendance')),
    path('classes/', include('academics.urls_classes')),
    
    # Finance
    path('finance/', include('finance.urls')),
    
    # Parents
    path('parents/', include('parents.urls')),
    
    # Reports
    path('reports/', include('reports.urls')),
    
    # Communication
    path('communication/', include('communication.urls')),
    
    # Admin
    path('admin/', admin.site.urls),
]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
'''
    
    urls_path = os.path.join(base_dir, 'backend', 'urls.py')
    with open(urls_path, 'w', encoding='utf-8') as f:
        f.write(urls_content)
    print("✅ Created: backend/urls.py")
    
    # Create app-specific URL files
    app_urls = {
        'students/urls.py': '''from django.urls import path
from .views import StudentListView, StudentDetailView

urlpatterns = [
    path('', StudentListView.as_view(), name='student_list'),
    path('<int:pk>/', StudentDetailView.as_view(), name='student_detail'),
]''',
        
        'academics/urls_attendance.py': '''from django.urls import path
from .views import AttendanceMarkingView, AttendanceListView, AttendanceReportView

urlpatterns = [
    path('mark/', AttendanceMarkingView.as_view(), name='mark_attendance'),
    path('', AttendanceListView.as_view(), name='attendance_list'),
    path('report/', AttendanceReportView.as_view(), name='attendance_report'),
]''',
        
        'finance/urls.py': '''from django.urls import path
from .views import InvoiceListView, PaymentListView

urlpatterns = [
    path('invoices/', InvoiceListView.as_view(), name='invoice_list'),
    path('payments/', PaymentListView.as_view(), name='payment_list'),
]''',
    }
    
    for url_file, content in app_urls.items():
        url_path = os.path.join(base_dir, url_file)
        os.makedirs(os.path.dirname(url_path), exist_ok=True)
        with open(url_path, 'w', encoding='utf-8') as f:
            f.write(content)
        print(f"✅ Created: {url_file}")

def create_complete_setup_script():
    base_dir = create_directory_structure()
    create_student_portal(base_dir)
    create_attendance_module(base_dir)
    create_finance_module(base_dir)
    create_urls_config(base_dir)
    
    print("\n" + "=" * 60)
    print("🎉 COMPLETE SYSTEM SETUP READY!")
    print("=" * 60)
    print("\n📋 NEXT STEPS:")
    print("1. Run migrations: python manage.py makemigrations")
    print("2. Apply migrations: python manage.py migrate")
    print("3. Create superuser: python manage.py createsuperuser")
    print("4. Run server: python manage.py runserver")
    print("\n🔗 AVAILABLE PAGES:")
    print("   • Home: http://127.0.0.1:8000/")
    print("   • Dashboard: http://127.0.0.1:8000/dashboard/")
    print("   • Students: http://127.0.0.1:8000/students/")
    print("   • Attendance: http://127.0.0.1:8000/attendance/")
    print("   • Finance: http://127.0.0.1:8000/finance/invoices/")
    print("\n⚡ QUICK START:")
    print("   Run: python manage.py runserver")
    print("   Login with admin credentials")
    print("   Start using all modules!")

if __name__ == "__main__":
    create_complete_setup_script()