# Water Billing System (Laravel)

A modern, multi-tenant water billing system built with Laravel. Manage clients, record meter readings, auto-generate billings based on tiered pricing, and print billing statements.

## Features

### 1. **Multi-Tenant Architecture (SAAS)**
- Each property manages their own subscribers independently
- Isolated data with separate databases or database schemas
- Unique tenants with domain support
- Independent settings per tenant

### 2. **Client Management**
- Add, edit, view, and delete clients
- Track account number, meter number, and contact information
- Monitor outstanding balance
- Support for different client statuses (active, inactive, disconnected)
- Complete address tracking (barangay, city, province, zip code)

### 3. **Account Dashboard**
- Real-time overview of key metrics:
  - Total clients and active clients count
  - Unpaid and total billings
  - Total revenue from paid billings
  - Outstanding balance across all clients
- Recent billing activities
- Recent payment records
- Quick action buttons

### 4. **Meter Reading Management**
- Record water meter readings
- Calculate units consumed (current - previous reading)
- Draft/approval workflow (approve or reject readings)
- Automatic billing generation upon approval
- Mobile app API for remote meter reading submission

### 5. **Tiered Pricing System**
- Create multiple pricing tiers based on consumption levels
- Define min/max units for each tier
- Set price per unit for each tier
- Activate/deactivate tiers as needed
- Automatic billing calculation based on tiers

### 6. **Automatic Billing Generation**
- Billings auto-generated when meter readings are approved
- Calculates:
  - Previous reading
  - Current reading
  - Units consumed
  - Subtotal (based on tiered pricing)
  - Tax, additional charges, and penalties
  - Total amount due
- Generates unique billing numbers
- Set due dates automatically

### 7. **System Settings**
- Configure application name and contact information
- Email configuration
- SMS gateway integration (Twilio, Nexmo)
- Payment gateway setup (Stripe, PayPal)
- Currency and timezone settings

### 8. **Billing & Print Options**
- View and manage billing records
- **Normal Paper Print**: Full-featured PDF billing statements
- **Thermal Printer Print**: 58mm thermal format for point-of-sale thermal printers
- Edit billings (adjust taxes, charges, penalties)
- Track billing status (draft, sent, overdue, paid, cancelled)

### 9. **Mobile App API** 
REST API endpoints for water meter reading mobile application:
- **GET** `/api/v1/meter-reading/client-details` - Get client details and balance
- **POST** `/api/v1/meter-reading/submit` - Submit meter reading
- **GET** `/api/v1/meter-reading/history` - Get reading history (last 12 months)
- **GET** `/api/v1/billings` - Get client's outstanding billings

### 10. **Payment Tracking**
- Record payments by method (cash, check, bank transfer, credit card, online)
- Link payments to specific billings
- Track payment status
- Calculate outstanding balance

## Technology Stack

- **Framework**: Laravel 12.x
- **Frontend**: Bootstrap 5
- **Database**: MySQL/MariaDB
- **PDF Generation**: DomPDF
- **Authentication**: Laravel Breeze + Sanctum
- **API**: RESTful API for mobile apps

## Installation

### Prerequisites
- PHP 8.4+
- MySQL/MariaDB
- Composer
- Node.js & npm (for assets)

### Setup Steps

1. **Clone or Extract Project**
```bash
cd /var/www/html/billing.happyimart.com
```

2. **Install Dependencies**
```bash
composer install
npm install
npm run build
```

3. **Environment Configuration**
```bash
cp .env.example .env
php artisan key:generate
```

4. **Database Setup**
```bash
# Configure database in .env
DB_DATABASE=water_billing
DB_USERNAME=root
DB_PASSWORD=

# Run migrations
php artisan migrate

# Seed initial data (optional)
php artisan db:seed
```

5. **Start Development Server**
```bash
php artisan serve
```

Access at: `http://localhost:8000`

## Project Structure

```
billing.happyimart.com/
├── app/
│   ├── Models/
│   │   ├── Tenant.php
│   │   ├── Client.php
│   │   ├── Setting.php
│   │   ├── Tier.php
│   │   ├── MeterReading.php
│   │   ├── Billing.php
│   │   └── Payment.php
│   ├── Services/
│   │   └── BillingService.php
│   ├── Http/
│   │   ├── Controllers/
│   │   │   ├── DashboardController.php
│   │   │   ├── ClientController.php
│   │   │   ├── MeterReadingController.php
│   │   │   ├── BillingController.php
│   │   │   ├── SettingController.php
│   │   │   └── Api/
│   │   │       └── MeterReadingApiController.php
│   │   └── Middleware/
│   ├── Policies/
│   └── Http/Requests/
├── database/
│   └── migrations/
├── resources/
│   └── views/
│       ├── layouts/
│       │   └── app.blade.php
│       ├── dashboard.blade.php
│       ├── clients/
│       ├── meter-readings/
│       ├── billings/
│       └── settings/
├── routes/
│   ├── web.php
│   └── api.php
└── config/

```

## Database Schema

### Tables

1. **tenants** - Tenant information (property/organization)
2. **settings** - System settings per tenant
3. **users** - User accounts (belongs to tenant)
4. **clients** - Water supply clients
5. **tiers** - Pricing tiers for calculations
6. **meter_readings** - Water meter reading records
7. **billings** - Generated bills
8. **payments** - Payment records

## Usage Guide

### For System Administrators

1. **Setup Initial Tenant**
   - Create tenant/property in the system
   - Configure settings (name, email, payment gateway)

2. **Configure Pricing Tiers**
   - Navigate to Settings
   - Add pricing tiers based on consumption levels
   - Example: 0-10 units @ ₱50/unit, 11-20 units @ ₱60/unit

3. **Add Clients**
   - Go to Clients > Add New Client
   - Fill in client information
   - System auto-generates account number

### For Meter Readers/Operators

1. **Record Meter Reading**
   - Go to Meter Readings > Add Reading
   - Select client
   - Enter current meter value
   - Submit for approval

2. **Approve/Reject Reading**
   - Review submitted readings
   - Click Approve to generate billing
   - Click Reject if reading is incorrect

### For Billers/Accountants

1. **Review Billings**
   - View all billings in Billings menu
   - Edit if needed (add taxes, charges, penalties)
   - View client-specific billings

2. **Print Billings**
   - Open billing record
   - Click "Print PDF" for normal paper
   - Click "Print Thermal" for POS thermal printer

3. **Track Payments**
   - Record payments against billings
   - Monitor outstanding balance

## API Documentation

### Authentication
Include tenant ID in header:
```
X-Tenant: tenant_slug
```

### Get Client Details
```
POST /api/v1/meter-reading/client-details
Content-Type: application/json

{
  "api_key": "your-api-key",
  "account_number": "ACC-1-000001"
}
```

### Submit Meter Reading
```
POST /api/v1/meter-reading/submit
Content-Type: application/json

{
  "api_key": "your-api-key",
  "account_number": "ACC-1-000001",
  "reading_value": 1234.56,
  "recorded_by": "John Doe",
  "notes": "Optional notes"
}
```

### Get Reading History
```
GET /api/v1/meter-reading/history?api_key=xxx&account_number=ACC-1-000001
```

### Get Outstanding Billings
```
GET /api/v1/billings?api_key=xxx&account_number=ACC-1-000001
```

## Mobile App Integration

### Android/iOS Requirements
- API endpoint: `/api/v1/`
- API key authentication
- Tenant slug in headers
- HTTPS recommended for production

### Sample Mobile Implementation
```kotlin
// Kotlin Example
val apiClient = HttpClient()
val response = apiClient.post("https://domain.com/api/v1/meter-reading/submit") {
    header("X-Tenant", "property-slug")
    body = MeterReadingRequest(
        api_key = "your-api-key",
        account_number = "ACC-1-000001",
        reading_value = 1234.56
    )
}
```

## Configuration

### Environment Variables (.env)
```
APP_NAME="Water Billing System"
APP_DEBUG=false
APP_URL=https://billing.happyimart.com

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=water_billing
DB_USERNAME=root
DB_PASSWORD=

# SMS Configuration
SMS_PROVIDER=twilio
TWILIO_ACCOUNT_SID=your-sid
TWILIO_AUTH_TOKEN=your-token
TWILIO_PHONE=+1234567890

# Payment Gateway
STRIPE_PUBLIC_KEY=your-key
STRIPE_SECRET_KEY=your-secret
```

## Customization

### Adding Custom Charges
Edit `BillingService.php` to add custom calculation logic:
```php
public function calculateBillingAmount(Billing $billing, Collection $tiers): void
{
    // Your custom logic
    $billing->calculateAmount($tiers);
}
```

### Extending Print Templates
Modify or create new print templates in:
- `resources/views/billings/pdf.blade.php`
- `resources/views/billings/thermal.blade.php`

### Adding New Reports
Create report generators in `app/Services/ReportService.php`

## Security

- **Authentication**: Laravel Breeze with email verification
- **Authorization**: Policy-based authorization
- **CSRF Protection**: Enabled on all POST/PUT/DELETE
- **API Security**: API key validation
- **Data Isolation**: Multi-tenant data isolation
- **Encryption**: Laravel encryption for sensitive data

## Performance Optimization

- Database indexing on frequently queried fields
- Pagination for large datasets
- Query optimization with eager loading
- Caching for system settings

## Troubleshooting

### Migration Errors
```bash
# Reset migrations (development only)
php artisan migrate:reset
php artisan migrate

# Check migration status
php artisan migrate:status
```

### Permission Issues
```bash
# Fix storage permissions
chmod -R 775 storage bootstrap/cache

# Clear cache
php artisan cache:clear
php artisan config:clear
```

### API Issues
- Verify X-Tenant header is present
- Check API key configuration
- Review API logs in storage/logs/

## License

This project is licensed under the MIT License.

## Support

For issues, questions, or feature requests:
- Check the documentation
- Review error logs in `storage/logs/laravel.log`
- Contact system administrator

## Future Enhancements

- [ ] SMS/Email notifications for billings
- [ ] Automated payment reminders
- [ ] Advanced reporting and analytics
- [ ] Bulk client import (CSV)
- [ ] Meter reading photographs/attachments
- [ ] Multi-language support
- [ ] Mobile app (native)
- [ ] Real-time notifications
- [ ] Audit logs
- [ ] Discount/voucher system

---

**Version**: 1.0.0  
**Last Updated**: January 2026
