<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Student Billing System</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        @page {
            size: A4;
            margin: 0;
        }
        @media print {
            body * {
                visibility: hidden;
            }
            .print-content, .print-content * {
                visibility: visible;
            }
            .print-content {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
            }
            .no-print {
                display: none !important;
            }
        }
        .image-preview {
            max-height: 150px;
            max-width: 100%;
        }
        .bill-preview {
            border: 1px dashed #ccc;
            padding: 20px;
            width: 80mm;
            margin: 0 auto;
            text-align: center;
        }
        .a4-preview {
            width: 210mm;
            min-height: 297mm;
            padding: 20px;
            margin: 0 auto;
            background: white;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .village-group {
            margin-bottom: 30px;
            page-break-inside: avoid;
        }
        .pagination-break {
            page-break-after: always;
        }
        [disabled] {
            opacity: 0.5;
            pointer-events: none;
        }
        .receipt {
            width: 80mm;
            margin: 0 auto;
            font-family: 'Courier New', monospace;
            padding: 10px;
            border: 1px solid #eee;
        }
        .receipt-header {
            text-align: center;
            margin-bottom: 10px;
        }
        .receipt-title {
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 5px;
        }
        .receipt-divider {
            border-top: 1px dashed #000;
            margin: 5px 0;
        }
        .receipt-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 3px;
        }
        .receipt-total {
            font-weight: bold;
            border-top: 2px solid #000;
            padding-top: 5px;
            margin-top: 5px;
        }
        .receipt-footer {
            text-align: center;
            margin-top: 10px;
            font-size: 12px;
        }
    </style>
</head>
<body class="bg-gray-100 p-4">
    <div class="container mx-auto">
        <!-- Header -->
        <div class="bg-white rounded-lg shadow-md p-6 mb-6">
            <h1 class="text-3xl font-bold text-center text-blue-800 mb-4">Student Billing System</h1>
            
            <!-- Profile Controls -->
            <div class="flex justify-between items-center mb-6 no-print">
                <div class="flex items-center space-x-4">
                    <div class="text-lg font-semibold">
                        Current Profile: <span id="currentProfile" class="text-blue-600">1</span>
                    </div>
                    <button id="newProfileBtn" class="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg flex items-center">
                        <i class="fas fa-plus mr-2"></i> New Profile
                    </button>
                </div>
                <div class="flex items-center space-x-2">
                    <input type="number" id="profileSearch" placeholder="Search Profile..." class="border rounded-lg px-3 py-2">
                    <button id="searchProfileBtn" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg">
                        <i class="fas fa-search mr-2"></i> Search
                    </button>
                </div>
            </div>
            
            <!-- Image Upload -->
            <div class="mb-6 no-print">
                <div class="border-2 border-dashed border-gray-300 rounded-lg p-4 text-center">
                    <label for="imageUpload" class="cursor-pointer">
                        <div id="imagePreviewContainer" class="hidden">
                            <img id="imagePreview" class="image-preview mx-auto mb-2">
                            <p class="text-sm text-gray-500">Click to change image (Recommended: 1024x200px, Max 1MB)</p>
                        </div>
                        <div id="imageUploadPrompt" class="py-8">
                            <i class="fas fa-image text-4xl text-gray-400 mb-2"></i>
                            <p class="text-gray-600">Upload Department Image</p>
                            <p class="text-sm text-gray-500">Recommended: 1024x200px, Max 1MB</p>
                        </div>
                    </label>
                    <input type="file" id="imageUpload" accept="image/*" class="hidden">
                </div>
                <p id="imageError" class="text-red-500 text-sm mt-1 hidden">Please upload an image to proceed</p>
            </div>
            
            <!-- Department Name -->
            <div class="mb-6 no-print">
                <label for="departmentName" class="block text-gray-700 font-medium mb-2">Department Name</label>
                <input type="text" id="departmentName" class="w-full border rounded-lg px-4 py-2" placeholder="Enter department name">
            </div>
        </div>
        
        <!-- Billing Form -->
        <div id="billingForm" class="bg-white rounded-lg shadow-md p-6 mb-6 no-print" disabled>
            <h2 class="text-xl font-semibold mb-4">Student Information</h2>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- Left Column -->
                <div>
                    <div class="mb-4">
                        <label for="studentPhone" class="block text-gray-700 font-medium mb-2">Student Phone Number</label>
                        <input type="tel" id="studentPhone" class="w-full border rounded-lg px-4 py-2" placeholder="Enter phone number">
                    </div>
                    
                    <div class="mb-4">
                        <label for="studentVillageInitial" class="block text-gray-700 font-medium mb-2">Village Initial (Optional)</label>
                        <input type="text" id="studentVillageInitial" class="w-full border rounded-lg px-4 py-2" placeholder="Enter village initial">
                    </div>
                    
                    <div class="mb-4">
                        <label for="studentVillageName" class="block text-gray-700 font-medium mb-2">Village Name</label>
                        <input type="text" id="studentVillageName" class="w-full border rounded-lg px-4 py-2" placeholder="Enter village name">
                    </div>
                    
                    <div class="mb-4">
                        <label for="studentInitial" class="block text-gray-700 font-medium mb-2">Student Initial</label>
                        <input type="text" id="studentInitial" class="w-full border rounded-lg px-4 py-2" placeholder="Enter student initial">
                    </div>
                    
                    <div class="mb-4">
                        <label for="studentName" class="block text-gray-700 font-medium mb-2">Student Name</label>
                        <input type="text" id="studentName" class="w-full border rounded-lg px-4 py-2" placeholder="Enter student name">
                    </div>
                </div>
                
                <!-- Right Column -->
                <div>
                    <div class="mb-4">
                        <label for="studentProfession" class="block text-gray-700 font-medium mb-2">Student Profession (English)</label>
                        <input type="text" id="studentProfession" class="w-full border rounded-lg px-4 py-2" placeholder="Enter student profession">
                    </div>
                    
                    <div class="mb-4">
                        <label for="studentWifeInitial" class="block text-gray-700 font-medium mb-2">Wife Initial</label>
                        <input type="text" id="studentWifeInitial" class="w-full border rounded-lg px-4 py-2" placeholder="Enter wife initial">
                    </div>
                    
                    <div class="mb-4">
                        <label for="studentWifeName" class="block text-gray-700 font-medium mb-2">Wife Name</label>
                        <input type="text" id="studentWifeName" class="w-full border rounded-lg px-4 py-2" placeholder="Enter wife name">
                    </div>
                    
                    <div class="mb-4">
                        <label for="studentWifeProfession" class="block text-gray-700 font-medium mb-2">Wife Profession</label>
                        <input type="text" id="studentWifeProfession" class="w-full border rounded-lg px-4 py-2" placeholder="Enter wife profession">
                    </div>
                    
                    <div class="mb-4">
                        <label for="amount" class="block text-gray-700 font-medium mb-2">Amount (₹)</label>
                        <input type="number" id="amount" class="w-full border rounded-lg px-4 py-2" placeholder="Enter amount">
                    </div>
                </div>
            </div>
            
            <!-- Form Buttons -->
            <div class="flex justify-end space-x-4 mt-6">
                <button id="resetFormBtn" class="bg-gray-500 hover:bg-gray-600 text-white px-6 py-2 rounded-lg">
                    Reset
                </button>
                <button id="savePrintBtn" class="bg-green-600 hover:bg-green-700 text-white px-6 py-2 rounded-lg flex items-center">
                    <i class="fas fa-print mr-2"></i> Save & Print
                </button>
            </div>
        </div>
        
        <!-- Preview Section -->
        <div class="bg-white rounded-lg shadow-md p-6 mb-6 no-print">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-semibold">Preview</h2>
                <button id="a4ViewBtn" class="bg-purple-600 hover:bg-purple-700 text-white px-4 py-2 rounded-lg">
                    <i class="fas fa-file-alt mr-2"></i> A4 View
                </button>
            </div>
            
            <div id="billPreview" class="receipt">
                <p class="text-gray-500">Fill the form to see preview</p>
            </div>
        </div>
        
        <!-- Saved Bills Table -->
        <div class="bg-white rounded-lg shadow-md p-6 no-print">
            <h2 class="text-xl font-semibold mb-4">Saved Bills</h2>
            
            <div class="overflow-x-auto">
                <table class="min-w-full bg-white border">
                    <thead>
                        <tr class="bg-gray-100">
                            <th class="py-2 px-4 border">Bill No</th>
                            <th class="py-2 px-4 border">Student Name</th>
                            <th class="py-2 px-4 border">Village</th>
                            <th class="py-2 px-4 border">Phone</th>
                            <th class="py-2 px-4 border">Amount</th>
                            <th class="py-2 px-4 border">Actions</th>
                        </tr>
                    </thead>
                    <tbody id="billsTableBody">
                        <!-- Bills will be loaded here -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <!-- Print Modal -->
    <div id="printModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50">
        <div class="bg-white rounded-lg p-6 w-11/12 max-w-4xl">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-semibold">Print Preview</h3>
                <button id="closePrintModal" class="text-gray-500 hover:text-gray-700">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <div id="printContent" class="print-content">
                <!-- Bill content will be inserted here -->
            </div>
            
            <div class="flex justify-end mt-4">
                <button id="printNowBtn" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-2 rounded-lg mr-2">
                    <i class="fas fa-print mr-2"></i> Print Now
                </button>
                <button id="cancelPrintBtn" class="bg-gray-500 hover:bg-gray-600 text-white px-6 py-2 rounded-lg">
                    Cancel
                </button>
            </div>
        </div>
    </div>
    
    <!-- A4 View Modal -->
    <div id="a4ViewModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50 overflow-y-auto py-10">
        <div class="bg-white rounded-lg p-6 w-11/12 max-w-4xl">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-semibold">A4 View</h3>
                <button id="closeA4Modal" class="text-gray-500 hover:text-gray-700">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <div id="a4Content" class="a4-preview">
                <!-- A4 content will be inserted here -->
            </div>
            
            <div class="flex justify-end mt-4">
                <button id="printA4Btn" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-2 rounded-lg mr-2">
                    <i class="fas fa-print mr-2"></i> Print A4
                </button>
                <button id="closeA4Btn" class="bg-gray-500 hover:bg-gray-600 text-white px-6 py-2 rounded-lg">
                    Close
                </button>
            </div>
        </div>
    </div>

    <script>
        // Database setup
        const DB_NAME = 'studentBillingDB';
        const PROFILES_KEY = 'profiles';
        
        // Initialize database
        function initDB() {
            if (!localStorage.getItem(DB_NAME)) {
                const db = {
                    [PROFILES_KEY]: {
                        '1': {
                            departmentName: '',
                            departmentImage: '',
                            bills: []
                        }
                    },
                    currentProfile: '1'
                };
                localStorage.setItem(DB_NAME, JSON.stringify(db));
            }
        }
        
        // Get database
        function getDB() {
            return JSON.parse(localStorage.getItem(DB_NAME));
        }
        
        // Update database
        function updateDB(db) {
            localStorage.setItem(DB_NAME, JSON.stringify(db));
        }
        
        // Get current profile
        function getCurrentProfile() {
            const db = getDB();
            return db[PROFILES_KEY][db.currentProfile];
        }
        
        // Get all profiles
        function getAllProfiles() {
            const db = getDB();
            return db[PROFILES_KEY];
        }
        
        // Set current profile
        function setCurrentProfile(profileId) {
            const db = getDB();
            db.currentProfile = profileId;
            updateDB(db);
            document.getElementById('currentProfile').textContent = profileId;
        }
        
        // Create new profile
        function createNewProfile() {
            const db = getDB();
            const profileId = Object.keys(db[PROFILES_KEY]).length + 1;
            
            db[PROFILES_KEY][profileId] = {
                departmentName: '',
                departmentImage: '',
                bills: []
            };
            
            db.currentProfile = profileId.toString();
            updateDB(db);
            
            // Reset form
            resetForm();
            document.getElementById('departmentName').value = '';
            document.getElementById('imagePreviewContainer').classList.add('hidden');
            document.getElementById('imageUploadPrompt').classList.remove('hidden');
            document.getElementById('currentProfile').textContent = profileId;
            
            // Disable form until image is uploaded
            document.getElementById('billingForm').setAttribute('disabled', 'true');
            
            return profileId;
        }
        
        // Load profile data
        function loadProfileData(profileId) {
            const db = getDB();
            const profile = db[PROFILES_KEY][profileId];
            
            if (profile) {
                document.getElementById('departmentName').value = profile.departmentName || '';
                
                if (profile.departmentImage) {
                    document.getElementById('imagePreview').src = profile.departmentImage;
                    document.getElementById('imagePreviewContainer').classList.remove('hidden');
                    document.getElementById('imageUploadPrompt').classList.add('hidden');
                    document.getElementById('billingForm').removeAttribute('disabled');
                } else {
                    document.getElementById('imagePreviewContainer').classList.add('hidden');
                    document.getElementById('imageUploadPrompt').classList.remove('hidden');
                    document.getElementById('billingForm').setAttribute('disabled', 'true');
                }
                
                // Load bills table
                loadBillsTable();
            }
        }
        
        // Save bill
        function saveBill(billData, print = false) {
            const db = getDB();
            const currentProfile = db.currentProfile;
            const bills = db[PROFILES_KEY][currentProfile].bills;
            
            // Check if bill exists (for update)
            const existingBillIndex = bills.findIndex(bill => bill.id === billData.id);
            
            if (existingBillIndex !== -1) {
                // Update existing bill
                bills[existingBillIndex] = billData;
            } else {
                // Add new bill
                billData.id = bills.length + 1;
                billData.date = new Date().toISOString();
                bills.push(billData);
            }
            
            // Update department name and image if changed
            db[PROFILES_KEY][currentProfile].departmentName = document.getElementById('departmentName').value;
            
            if (document.getElementById('imagePreview').src) {
                db[PROFILES_KEY][currentProfile].departmentImage = document.getElementById('imagePreview').src;
            }
            
            updateDB(db);
            
            // Reload bills table
            loadBillsTable();
            
            if (print) {
                showPrintModal(billData);
            }
            
            return billData;
        }
        
        // Delete bill
        function deleteBill(billId) {
            const db = getDB();
            const currentProfile = db.currentProfile;
            const bills = db[PROFILES_KEY][currentProfile].bills;
            
            const billIndex = bills.findIndex(bill => bill.id === billId);
            
            if (billIndex !== -1) {
                bills.splice(billIndex, 1);
                
                // Reassign IDs to maintain sequence
                bills.forEach((bill, index) => {
                    bill.id = index + 1;
                });
                
                updateDB(db);
                loadBillsTable();
            }
        }
        
        // Get bill by ID
        function getBillById(billId) {
            const db = getDB();
            const currentProfile = db.currentProfile;
            const bills = db[PROFILES_KEY][currentProfile].bills;
            
            return bills.find(bill => bill.id === billId);
        }
        
        // Find bill by phone number across all profiles
        function findBillByPhone(phone) {
            const db = getDB();
            const profiles = db[PROFILES_KEY];
            
            for (const profileId in profiles) {
                const bills = profiles[profileId].bills;
                const existingBill = bills.find(bill => bill.studentPhone === phone);
                
                if (existingBill) {
                    return existingBill;
                }
            }
            
            return null;
        }
        
        // Load bills table
        function loadBillsTable() {
            const db = getDB();
            const currentProfile = db.currentProfile;
            const bills = db[PROFILES_KEY][currentProfile].bills;
            
            const tableBody = document.getElementById('billsTableBody');
            tableBody.innerHTML = '';
            
            if (bills.length === 0) {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td colspan="6" class="py-4 px-4 border text-center text-gray-500">No bills found</td>
                `;
                tableBody.appendChild(row);
                return;
            }
            
            bills.forEach(bill => {
                const row = document.createElement('tr');
                row.className = 'hover:bg-gray-50';
                row.innerHTML = `
                    <td class="py-2 px-4 border">${bill.id}</td>
                    <td class="py-2 px-4 border">${bill.studentName}</td>
                    <td class="py-2 px-4 border">${bill.studentVillageName}</td>
                    <td class="py-2 px-4 border">${bill.studentPhone}</td>
                    <td class="py-2 px-4 border">₹${bill.amount}</td>
                    <td class="py-2 px-4 border">
                        <button class="edit-bill text-blue-600 hover:text-blue-800 mr-2" data-id="${bill.id}">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="delete-bill text-red-600 hover:text-red-800" data-id="${bill.id}">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                `;
                tableBody.appendChild(row);
            });
            
            // Add event listeners to edit and delete buttons
            document.querySelectorAll('.edit-bill').forEach(btn => {
                btn.addEventListener('click', function() {
                    const billId = parseInt(this.getAttribute('data-id'));
                    editBill(billId);
                });
            });
            
            document.querySelectorAll('.delete-bill').forEach(btn => {
                btn.addEventListener('click', function() {
                    const billId = parseInt(this.getAttribute('data-id'));
                    if (confirm('Are you sure you want to delete this bill?')) {
                        deleteBill(billId);
                    }
                });
            });
        }
        
        // Edit bill
        function editBill(billId) {
            const bill = getBillById(billId);
            
            if (bill) {
                document.getElementById('studentPhone').value = bill.studentPhone;
                document.getElementById('studentVillageInitial').value = bill.studentVillageInitial;
                document.getElementById('studentVillageName').value = bill.studentVillageName;
                document.getElementById('studentInitial').value = bill.studentInitial;
                document.getElementById('studentName').value = bill.studentName;
                document.getElementById('studentProfession').value = bill.studentProfession;
                document.getElementById('studentWifeInitial').value = bill.studentWifeInitial;
                document.getElementById('studentWifeName').value = bill.studentWifeName;
                document.getElementById('studentWifeProfession').value = bill.studentWifeProfession;
                document.getElementById('amount').value = bill.amount;
                
                // Update preview
                updatePreview();
                
                // Scroll to form
                document.getElementById('studentPhone').scrollIntoView({ behavior: 'smooth' });
            }
        }
        
        // Reset form
        function resetForm() {
            document.getElementById('studentPhone').value = '';
            document.getElementById('studentVillageInitial').value = '';
            document.getElementById('studentVillageName').value = '';
            document.getElementById('studentInitial').value = '';
            document.getElementById('studentName').value = '';
            document.getElementById('studentProfession').value = '';
            document.getElementById('studentWifeInitial').value = '';
            document.getElementById('studentWifeName').value = '';
            document.getElementById('studentWifeProfession').value = '';
            document.getElementById('amount').value = '';
            
            document.getElementById('billPreview').innerHTML = '<p class="text-gray-500">Fill the form to see preview</p>';
        }
        
        // Update preview
        function updatePreview() {
            const preview = document.getElementById('billPreview');
            
            const studentPhone = document.getElementById('studentPhone').value;
            const studentVillageInitial = document.getElementById('studentVillageInitial').value;
            const studentVillageName = document.getElementById('studentVillageName').value;
            const studentInitial = document.getElementById('studentInitial').value;
            const studentName = document.getElementById('studentName').value;
            const studentProfession = document.getElementById('studentProfession').value;
            const studentWifeInitial = document.getElementById('studentWifeInitial').value;
            const studentWifeName = document.getElementById('studentWifeName').value;
            const studentWifeProfession = document.getElementById('studentWifeProfession').value;
            const amount = document.getElementById('amount').value;
            
            if (!studentPhone && !studentName && !amount) {
                preview.innerHTML = '<p class="text-gray-500">Fill the form to see preview</p>';
                return;
            }
            
            let previewHTML = `
                <div class="receipt-header">
                    <div class="receipt-title">${document.getElementById('departmentName').value || 'Department'}</div>
                    <div class="text-sm">${studentVillageInitial} ${studentVillageName}</div>
                </div>
                <div class="receipt-divider"></div>
                <div class="receipt-item">
                    <span>${studentInitial} ${studentName}</span>
                    <span>${studentProfession}</span>
                </div>
                <div class="receipt-item">
                    <span>${studentWifeInitial} ${studentWifeName}</span>
                    <span>${studentWifeProfession}</span>
                </div>
                <div class="receipt-divider"></div>
                <div class="receipt-item receipt-total">
                    <span>TOTAL</span>
                    <span>₹${amount || '0'}</span>
                </div>
                <div class="receipt-footer">
                    <div>Bill No: ${getCurrentProfile().bills.length + 1}</div>
                    <div>${new Date().toLocaleDateString()}</div>
                    <div>Thank you!</div>
                </div>
            `;
            
            preview.innerHTML = previewHTML;
        }
        
        // Show print modal
        function showPrintModal(billData) {
            const printContent = document.getElementById('printContent');
            const currentProfile = getCurrentProfile();
            
            let printHTML = `
                <div class="receipt">
                    <div class="receipt-header">
                        ${currentProfile.departmentImage ? `<img src="${currentProfile.departmentImage}" class="mx-auto mb-2" style="max-height: 40px;">` : ''}
                        <div class="receipt-title">${currentProfile.departmentName || 'Department'}</div>
                        <div class="text-sm">${billData.studentVillageInitial} ${billData.studentVillageName}</div>
                    </div>
                    <div class="receipt-divider"></div>
                    <div class="receipt-item">
                        <span>${billData.studentInitial} ${billData.studentName}</span>
                        <span>${billData.studentProfession}</span>
                    </div>
                    <div class="receipt-item">
                        <span>${billData.studentWifeInitial} ${billData.studentWifeName}</span>
                        <span>${billData.studentWifeProfession}</span>
                    </div>
                    <div class="receipt-divider"></div>
                    <div class="receipt-item receipt-total">
                        <span>TOTAL</span>
                        <span>₹${billData.amount || '0'}</span>
                    </div>
                    <div class="receipt-footer">
                        <div>Bill No: ${billData.id}</div>
                        <div>${new Date(billData.date).toLocaleDateString()}</div>
                        <div>Thank you!</div>
                    </div>
                </div>
            `;
            
            printContent.innerHTML = printHTML;
            document.getElementById('printModal').classList.remove('hidden');
        }
        
        // Show A4 view
        function showA4View() {
            const a4Content = document.getElementById('a4Content');
            const db = getDB();
            const currentProfileId = db.currentProfile;
            const profile = db[PROFILES_KEY][currentProfileId];
            const bills = profile.bills;
            
            if (bills.length === 0) {
                a4Content.innerHTML = '<p class="text-center text-gray-500 py-20">No bills found for this profile</p>';
                document.getElementById('a4ViewModal').classList.remove('hidden');
                return;
            }
            
            // Group bills by village
            const villageGroups = {};
            bills.forEach(bill => {
                const villageKey = `${bill.studentVillageInitial} ${bill.studentVillageName}`;
                if (!villageGroups[villageKey]) {
                    villageGroups[villageKey] = [];
                }
                villageGroups[villageKey].push(bill);
            });
            
            let a4HTML = '';
            let pageTotal = 0;
            let overallTotal = 0;
            let villageCount = 0;
            const villageKeys = Object.keys(villageGroups);
            
            // Department header
            a4HTML += `
                <div class="text-center mb-8">
                    ${profile.departmentImage ? `<img src="${profile.departmentImage}" class="mx-auto mb-2" style="max-height: 80px;">` : ''}
                    <h2 class="text-xl font-bold">${profile.departmentName || 'Department'}</h2>
                    <p class="text-sm">Billing Summary - Profile ${currentProfileId}</p>
                </div>
            `;
            
            // Village groups
            villageKeys.forEach((villageKey, index) => {
                const villageBills = villageGroups[villageKey];
                let villageTotal = 0;
                
                a4HTML += `
                    <div class="village-group ${villageCount > 0 && villageCount % 2 === 0 ? 'pagination-break' : ''}">
                        <h3 class="text-lg font-semibold mb-2 text-center">${villageKey}</h3>
                        <table class="w-full mb-4">
                            <thead>
                                <tr class="border-b">
                                    <th class="text-left py-2">No</th>
                                    <th class="text-left py-2">Name</th>
                                    <th class="text-left py-2">Profession</th>
                                    <th class="text-right py-2">Amount</th>
                                </tr>
                            </thead>
                            <tbody>
                `;
                
                villageBills.forEach((bill, billIndex) => {
                    villageTotal += parseFloat(bill.amount) || 0;
                    
                    a4HTML += `
                        <tr class="border-b">
                            <td class="py-2">${billIndex + 1}</td>
                            <td class="py-2">
                                ${bill.studentInitial} ${bill.studentName}<br>
                                <span class="text-sm">${bill.studentWifeInitial} ${bill.studentWifeName}</span>
                            </td>
                            <td class="py-2">
                                ${bill.studentProfession}<br>
                                <span class="text-sm">${bill.studentWifeProfession}</span>
                            </td>
                            <td class="py-2 text-right">₹${bill.amount}</td>
                        </tr>
                    `;
                });
                
                a4HTML += `
                            </tbody>
                            <tfoot>
                                <tr>
                                    <td colspan="3" class="text-right font-semibold py-2">Village Total:</td>
                                    <td class="text-right font-semibold py-2">₹${villageTotal.toFixed(2)}</td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                `;
                
                pageTotal += villageTotal;
                overallTotal += villageTotal;
                villageCount++;
                
                // Add page break after every 2 villages (adjust as needed)
                if (villageCount > 0 && villageCount % 2 === 0) {
                    a4HTML += `
                        <div class="mt-4 pt-4 border-t text-right">
                            <p class="font-semibold">Page Total: ₹${pageTotal.toFixed(2)}</p>
                        </div>
                    `;
                    pageTotal = 0;
                    
                    // Add page break except for last village
                    if (index < villageKeys.length - 1) {
                        a4HTML += '<div class="pagination-break"></div>';
                    }
                }
            });
            
            // Final total
            a4HTML += `
                <div class="mt-8 pt-4 border-t text-right">
                    <p class="text-lg font-bold">Overall Total: ₹${overallTotal.toFixed(2)}</p>
                    <p class="text-sm mt-4">Generated on: ${new Date().toLocaleString()}</p>
                </div>
            `;
            
            a4Content.innerHTML = a4HTML;
            document.getElementById('a4ViewModal').classList.remove('hidden');
        }
        
        // Initialize the app
        function initApp() {
            initDB();
            
            // Load current profile data
            const db = getDB();
            setCurrentProfile(db.currentProfile);
            loadProfileData(db.currentProfile);
            
            // Event listeners
            document.getElementById('imageUpload').addEventListener('change', function(e) {
                const file = e.target.files[0];
                if (file) {
                    // Check file size (max 1MB)
                    if (file.size > 1024 * 1024) {
                        alert('Image size must be less than 1MB');
                        return;
                    }
                    
                    const reader = new FileReader();
                    reader.onload = function(event) {
                        document.getElementById('imagePreview').src = event.target.result;
                        document.getElementById('imagePreviewContainer').classList.remove('hidden');
                        document.getElementById('imageUploadPrompt').classList.add('hidden');
                        
                        // Enable form
                        document.getElementById('billingForm').removeAttribute('disabled');
                        
                        // Save to profile
                        const db = getDB();
                        db[PROFILES_KEY][db.currentProfile].departmentImage = event.target.result;
                        updateDB(db);
                    };
                    reader.readAsDataURL(file);
                }
            });
            
            // Form field listeners for preview
            const formFields = [
                'studentPhone', 'studentVillageInitial', 'studentVillageName', 
                'studentInitial', 'studentName', 'studentProfession',
                'studentWifeInitial', 'studentWifeName', 'studentWifeProfession', 'amount'
            ];
            
            formFields.forEach(fieldId => {
                document.getElementById(fieldId).addEventListener('input', updatePreview);
            });
            
            // Check phone number for existing data across all profiles
            document.getElementById('studentPhone').addEventListener('blur', function() {
                const phone = this.value;
                if (phone) {
                    const existingBill = findBillByPhone(phone);
                    
                    if (existingBill) {
                        // Fill form with existing data except amount
                        document.getElementById('studentVillageInitial').value = existingBill.studentVillageInitial;
                        document.getElementById('studentVillageName').value = existingBill.studentVillageName;
                        document.getElementById('studentInitial').value = existingBill.studentInitial;
                        document.getElementById('studentName').value = existingBill.studentName;
                        document.getElementById('studentProfession').value = existingBill.studentProfession;
                        document.getElementById('studentWifeInitial').value = existingBill.studentWifeInitial;
                        document.getElementById('studentWifeName').value = existingBill.studentWifeName;
                        document.getElementById('studentWifeProfession').value = existingBill.studentWifeProfession;
                        
                        // Clear amount field
                        document.getElementById('amount').value = '';
                        
                        // Update preview
                        updatePreview();
                    }
                }
            });
            
            // Save & Print button
            document.getElementById('savePrintBtn').addEventListener('click', function() {
                if (!validateForm()) return;
                
                const billData = getFormData();
                saveBill(billData, true);
            });
            
            // Reset form button
            document.getElementById('resetFormBtn').addEventListener('click', resetForm);
            
            // New profile button
            document.getElementById('newProfileBtn').addEventListener('click', function() {
                if (confirm('Create a new profile? This will reset the current form.')) {
                    createNewProfile();
                }
            });
            
            // Search profile button
            document.getElementById('searchProfileBtn').addEventListener('click', function() {
                const profileId = document.getElementById('profileSearch').value;
                
                if (!profileId) {
                    alert('Please enter a profile number');
                    return;
                }
                
                const db = getDB();
                if (db[PROFILES_KEY][profileId]) {
                    setCurrentProfile(profileId);
                    loadProfileData(profileId);
                    resetForm();
                } else {
                    alert(`Profile ${profileId} not found`);
                }
            });
            
            // A4 View button
            document.getElementById('a4ViewBtn').addEventListener('click', showA4View);
            
            // Print modal buttons
            document.getElementById('printNowBtn').addEventListener('click', function() {
                window.print();
            });
            
            document.getElementById('cancelPrintBtn').addEventListener('click', function() {
                document.getElementById('printModal').classList.add('hidden');
            });
            
            document.getElementById('closePrintModal').addEventListener('click', function() {
                document.getElementById('printModal').classList.add('hidden');
            });
            
            // A4 modal buttons
            document.getElementById('printA4Btn').addEventListener('click', function() {
                window.print();
            });
            
            document.getElementById('closeA4Btn').addEventListener('click', function() {
                document.getElementById('a4ViewModal').classList.add('hidden');
            });
            
            document.getElementById('closeA4Modal').addEventListener('click', function() {
                document.getElementById('a4ViewModal').classList.add('hidden');
            });
            
            // Save department name when changed
            document.getElementById('departmentName').addEventListener('change', function() {
                const db = getDB();
                db[PROFILES_KEY][db.currentProfile].departmentName = this.value;
                updateDB(db);
            });
        }
        
        // Validate form
        function validateForm() {
            const imageUploaded = document.getElementById('imagePreview').src && 
                                 !document.getElementById('imagePreviewContainer').classList.contains('hidden');
            
            if (!imageUploaded) {
                document.getElementById('imageError').classList.remove('hidden');
                setTimeout(() => {
                    document.getElementById('imageError').classList.add('hidden');
                }, 3000);
                return false;
            }
            
            const studentPhone = document.getElementById('studentPhone').value;
            const studentName = document.getElementById('studentName').value;
            const amount = document.getElementById('amount').value;
            
            if (!studentPhone || !studentName || !amount) {
                alert('Please fill in all required fields: Phone, Name, and Amount');
                return false;
            }
            
            return true;
        }
        
        // Get form data
        function getFormData() {
            return {
                studentPhone: document.getElementById('studentPhone').value,
                studentVillageInitial: document.getElementById('studentVillageInitial').value,
                studentVillageName: document.getElementById('studentVillageName').value,
                studentInitial: document.getElementById('studentInitial').value,
                studentName: document.getElementById('studentName').value,
                studentProfession: document.getElementById('studentProfession').value,
                studentWifeInitial: document.getElementById('studentWifeInitial').value,
                studentWifeName: document.getElementById('studentWifeName').value,
                studentWifeProfession: document.getElementById('studentWifeProfession').value,
                amount: document.getElementById('amount').value
            };
        }
        
        // Initialize the application when DOM is loaded
        document.addEventListener('DOMContentLoaded', initApp);
    </script>
</body>
</html>


why bill view is not generating?

Uncaught TypeError: Cannot set properties of undefined (setting 'departmentImage')
    at reader.onload (pos.html:834:77)Understand this error
pos.html:947 Uncaught TypeError: Cannot set properties of undefined (setting 'departmentName')
    at HTMLInputElement.<anonymous> (pos.html:947:68)Understand this error
69pos.html:635 Uncaught TypeError: Cannot read properties of undefined (reading 'bills')
    at HTMLInputElement.updatePreview (pos.html:635:56)Understand this error
3pos.html:417 Uncaught TypeError: Cannot read properties of undefined (reading 'bills')
    at saveBill (pos.html:417:60)
    at HTMLButtonElement.<anonymous> (pos.html:883:17)Understand this error
16pos.html:635 Uncaught TypeError: Cannot read properties of undefined (reading 'bills')
    at HTMLInputElement.updatePreview (pos.html:635:56)Understand this error
5pos.html:417 Uncaught TypeError: Cannot read properties of undefined (reading 'bills')
    at saveBill (pos.html:417:60)
    at HTMLButtonElement.<anonymous> (pos.html:883:17)Understand this error
13pos.html:688 Uncaught TypeError: Cannot read properties of undefined (reading 'bills')
    at HTMLButtonElement.showA4View (pos.html:688:35)Understand this error
pos.html:417 Uncaught TypeError: Cannot read properties of undefined (reading 'bills')
    at saveBill (pos.html:417:60)
    at HTMLButtonElement.<anonymous> (pos.html:883:17)Understand this error
4pos.html:417 Uncaught TypeError: Cannot read properties of undefined (reading 'bills')
    at saveBill (pos.html:417:60)
    at HTMLButtonElement.<anonymous> (pos.html:883:17)
saveBill @ pos.html:417
(anonymous) @ pos.html:883Understand this error
3pos.html:688 Uncaught TypeError: Cannot read properties of undefined (reading 'bills')
    at HTMLButtonElement.showA4View (pos.html:688:35)
showA4View @ pos.html:688Understand this error