# Bills Management Feature

## 🎯 **New Feature Added**

### **Bills Display in Admin Billing Page**

The admin billing page now displays all bills with intelligent sorting that prioritizes payment pending bills first.

## 📊 **Features Implemented**

### **1. Bills Table Display**
- **Comprehensive View**: Shows all bills in a detailed table format
- **Member Information**: Displays member name, ID, and mobile number
- **Bill Details**: Shows billing month, amount, due date, and status
- **Created Date**: Displays when the bill was created
- **Action Buttons**: View details and mark as paid options

### **2. Smart Sorting System**
- **Priority Order**: Payment pending bills appear first
- **Secondary Sort**: Overdue bills appear second
- **Tertiary Sort**: Paid bills appear last
- **Date Sorting**: Within each status group, sorted by due date and creation date

### **3. Status Management**
- **Visual Status Badges**: Color-coded status indicators
- **Overdue Detection**: Automatically detects and highlights overdue bills
- **Status Actions**: Mark pending bills as paid with confirmation

### **4. Enhanced UI Design**
- **Card Layout**: Organized into separate sections for bill generation and bills management
- **Responsive Table**: Works on all screen sizes
- **Loading States**: Shows spinner while loading bills
- **Empty State**: Displays message when no bills exist

## 🔧 **Technical Implementation**

### **Frontend Changes**

#### **HTML Structure (`public/admin.html`)**
```html
<!-- Bills Management Section -->
<div class="card">
    <div class="card-header bg-primary text-white">
        <h5 class="mb-0">
            <i class="fas fa-list me-2"></i>All Bills
        </h5>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-striped">
                <thead class="table-dark">
                    <tr>
                        <th>Bill ID</th>
                        <th>Member</th>
                        <th>Billing Month</th>
                        <th>Amount</th>
                        <th>Due Date</th>
                        <th>Status</th>
                        <th>Created Date</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody id="billsTable">
                    <!-- Bills loaded dynamically -->
                </tbody>
            </table>
        </div>
    </div>
</div>
```

#### **JavaScript Functions (`public/admin-script.js`)**
```javascript
// Load bills with sorting
async function loadBills() {
    try {
        const response = await fetch('/api/admin/bills', {
            headers: { 'Authorization': `Bearer ${authToken}` }
        });
        
        if (response.ok) {
            const bills = await response.json();
            displayBills(bills);
        } else if (response.status === 401) {
            clearInvalidToken();
        } else {
            showAlert('Error loading bills', 'danger');
        }
    } catch (error) {
        console.error('Error loading bills:', error);
        showAlert('Error loading bills', 'danger');
    }
}

// Display bills with status styling
function displayBills(bills) {
    const tbody = document.getElementById('billsTable');
    
    if (bills.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="8" class="text-center text-muted">
                    <i class="fas fa-inbox me-2"></i>No bills found
                </td>
            </tr>
        `;
        return;
    }
    
    tbody.innerHTML = '';
    
    bills.forEach(bill => {
        const row = document.createElement('tr');
        
        // Status badge styling
        let statusClass = 'bg-secondary';
        let statusText = bill.status.toUpperCase();
        
        switch (bill.status) {
            case 'pending':
                statusClass = 'bg-warning text-dark';
                break;
            case 'overdue':
                statusClass = 'bg-danger';
                break;
            case 'paid':
                statusClass = 'bg-success';
                break;
        }
        
        // Check if bill is overdue
        const dueDate = new Date(bill.due_date);
        const today = new Date();
        const isOverdue = dueDate < today && bill.status === 'pending';
        
        if (isOverdue) {
            statusClass = 'bg-danger';
            statusText = 'OVERDUE';
        }
        
        row.innerHTML = `
            <td>${bill.id}</td>
            <td>
                ${bill.member_name}<br>
                <small class="text-muted">ID: ${bill.member_id} | ${bill.member_mobile}</small>
            </td>
            <td>${bill.billing_month}</td>
            <td>MVR ${bill.amount}</td>
            <td>${formatDate(bill.due_date)}</td>
            <td><span class="badge ${statusClass}">${statusText}</span></td>
            <td>${formatDate(bill.created_at)}</td>
            <td>
                <div class="btn-group" role="group">
                    <button class="btn btn-sm btn-outline-info" onclick="viewBillDetails(${bill.id})" title="View Details">
                        <i class="fas fa-eye"></i>
                    </button>
                    ${bill.status === 'pending' ? `
                        <button class="btn btn-sm btn-outline-success" onclick="markBillAsPaid(${bill.id})" title="Mark as Paid">
                            <i class="fas fa-check"></i>
                        </button>
                    ` : ''}
                </div>
            </td>
        `;
        
        tbody.appendChild(row);
    });
}

// Mark bill as paid
async function markBillAsPaid(billId) {
    if (!confirm('Are you sure you want to mark this bill as paid?')) {
        return;
    }
    
    try {
        const response = await fetch(`/api/admin/bills/${billId}/mark-paid`, {
            method: 'PUT',
            headers: { 'Authorization': `Bearer ${authToken}` }
        });
        
        const result = await response.json();
        
        if (response.ok) {
            showAlert(result.message, 'success');
            loadBills(); // Refresh bills list
        } else {
            showAlert(result.error || 'Error updating bill', 'danger');
        }
    } catch (error) {
        console.error('Error updating bill:', error);
        showAlert('Error updating bill', 'danger');
    }
}
```

### **Backend API Endpoints**

#### **Get All Bills with Sorting (`server.js`)**
```javascript
// Get all bills with sorting (payment pending first)
app.get('/api/admin/bills', authenticateAdmin, async (req, res) => {
  try {
    const [bills] = await pool.execute(`
      SELECT 
        b.id,
        b.member_id,
        CONCAT(m.first_name, ' ', m.last_name) as member_name,
        m.mobile as member_mobile,
        b.billing_month,
        b.amount,
        b.due_date,
        b.status,
        b.created_at,
        CASE 
          WHEN b.status = 'pending' THEN 1
          WHEN b.status = 'overdue' THEN 2
          WHEN b.status = 'paid' THEN 3
          ELSE 4
        END as sort_order
      FROM bills b
      JOIN members m ON b.member_id = m.id
      ORDER BY sort_order ASC, b.due_date ASC, b.created_at DESC
    `);

    res.json(bills);
  } catch (error) {
    console.error('Error fetching bills:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});
```

#### **Mark Bill as Paid (`server.js`)**
```javascript
// Mark bill as paid
app.put('/api/admin/bills/:id/mark-paid', authenticateAdmin, async (req, res) => {
  try {
    const { id } = req.params;
    
    const [result] = await pool.execute(
      'UPDATE bills SET status = ? WHERE id = ?',
      ['paid', id]
    );

    if (result.affectedRows === 0) {
      return res.status(404).json({ error: 'Bill not found' });
    }

    res.json({ message: 'Bill marked as paid successfully' });
  } catch (error) {
    console.error('Error updating bill:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});
```

## 🎯 **Sorting Logic**

### **Priority Order**
1. **Pending Bills** (sort_order = 1)
   - Bills awaiting payment
   - Most urgent for admin attention
   - Sorted by due date (earliest first)

2. **Overdue Bills** (sort_order = 2)
   - Bills past due date but still pending
   - Requires immediate attention
   - Sorted by due date (most overdue first)

3. **Paid Bills** (sort_order = 3)
   - Successfully paid bills
   - For reference and record keeping
   - Sorted by creation date (newest first)

### **Secondary Sorting**
- **Within Status Groups**: Sorted by due date (ASC) then creation date (DESC)
- **Overdue Detection**: Automatically detects bills past due date
- **Dynamic Status**: Updates status display based on current date

## 🎨 **Visual Design**

### **Status Badges**
- **Pending**: Yellow badge (`bg-warning text-dark`)
- **Overdue**: Red badge (`bg-danger`)
- **Paid**: Green badge (`bg-success`)
- **Default**: Gray badge (`bg-secondary`)

### **Member Information**
- **Primary**: Member full name
- **Secondary**: Member ID and mobile number (smaller text)
- **Clear Hierarchy**: Easy to scan and identify members

### **Action Buttons**
- **View Details**: Blue outline button with eye icon
- **Mark as Paid**: Green outline button with checkmark icon (only for pending bills)
- **Button Group**: Organized in a button group for clean layout

## 🚀 **Current Status**

✅ **Bills table implemented**  
✅ **Smart sorting system working**  
✅ **Status management functional**  
✅ **API endpoints operational**  
✅ **Frontend integration complete**  
✅ **Server running on port 3000**  

## 🎉 **Benefits**

### **For Admins**
- **Priority Focus**: Payment pending bills appear first
- **Quick Actions**: Mark bills as paid with one click
- **Clear Overview**: See all bills in one organized view
- **Status Tracking**: Visual status indicators for quick assessment

### **For Operations**
- **Efficient Workflow**: Focus on urgent bills first
- **Reduced Errors**: Clear visual distinction between bill statuses
- **Better Organization**: Logical sorting reduces time spent searching
- **Real-time Updates**: Bills list refreshes after status changes

### **For Record Keeping**
- **Complete History**: All bills visible in one place
- **Status Tracking**: Clear audit trail of bill statuses
- **Member Context**: Easy identification of bill owners
- **Date Information**: Creation and due dates for reference

**The bills management feature is now fully operational with intelligent sorting and comprehensive bill tracking!** 📊✅

Admins can now efficiently manage all bills with payment pending bills prioritized at the top, making it easy to focus on urgent payments and maintain accurate billing records.
