# Network Report Controller Documentation

**File**: `/controllers/networkreport.php`  
**Purpose**: Payment network reporting and transaction analysis  
**Last Updated**: December 20, 2024  
**Total Functions**: 3+  
**Lines of Code**: ~178

---

## 📋 Overview

The Network Report Controller provides comprehensive reporting for payment network transactions, focusing on card payments, commissions, and network-specific analytics. It handles:
- Daily payment network summaries
- Transaction filtering by network and branch
- Commission and discount calculations
- MADA payment processing analytics
- Network performance reporting
- Branch-wise payment analysis

### Primary Functions
- [x] Daily network payment summaries
- [x] Network-specific transaction filtering
- [x] Commission and fee calculations
- [x] MADA payment analysis with tiered pricing
- [x] Branch-wise network reporting
- [x] Payment network performance metrics
- [x] YouTube tutorial integration

### Related Controllers
- [bills.php](bills.md) - Bill processing
- [clientController.php](clientController.md) - Customer management
- [branchesController.php](branchesController.md) - Branch management
- [index.php](index.md) - Dashboard analytics

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **bills** | Payment transactions | billid, netbillvalue, cardvalue, paymentnetworkid, billdate, branchid |
| **paymentnetworks** | Payment network definitions | paymentnetworkid, networkname, netdiscountpercent, deleted |
| **branch** | Business branches | branchid, branchname, branchcode |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **youtubelink** | Tutorial videos | youtubelinkid, title, url |

### Key Relationships
- `bills.paymentnetworkid` → `paymentnetworks.paymentnetworkid`
- `bills.branchid` → `branch.branchid`

---

## 🔑 Key Functions

### 1. **Default Action** - Today's Network Summary
**Location**: Line 62  
**Purpose**: Display today's payment network transaction summary

**Process Flow**:
1. Load all active payment networks
2. Load all branches
3. Query today's network transactions
4. Calculate totals and commissions
5. Display summary report

**Calculations Performed**:
```php
foreach ($allData as $data) {
    $billTotal += $data->netbillvalue;     // Total bill amount
    $payedTotal += $data->cardvalue;       // Total card payments
    $netTotal += ($data->cardvalue * $data->netdiscountpercent) / 100; // Commission
}
```

**Template Variables**:
- `$allNetworks` - Available payment networks
- `$allbranches` - Available branches
- `$allData` - Today's transaction data
- `$billTotal` - Total bill amounts
- `$payedTotal` - Total payments
- `$netTotal` - Total commissions

---

### 2. **show** - Filtered Network Report
**Location**: Line 82  
**Purpose**: Generate filtered network reports with date range and filters

**Function Signature**:
```php
$startDate = $_REQUEST['from'];
$endDate = $_REQUEST['to'];
$networkid = $_REQUEST['network'];
$branchid = $_REQUEST['branch'];
$reportType = $_REQUEST['reportType'];
```

**Process Flow**:
1. **Build Query Filters**:
   ```php
   $query = '';
   if (!empty($startDate) && empty($endDate)) {
       $query .=' and Date(billdate) >= "' . $startDate . '" ';
   } elseif (empty($startDate) && !empty($endDate)) {
       $query .=' and Date(billdate) <= "' . $endDate . '" ';
   } elseif (!empty($startDate) && !empty($endDate)) {
       $query.= ' and Date(billdate) >= "' . $startDate . '" and Date(billdate) <= "' . $endDate . '" ';
   }
   ```

2. **Apply Network and Branch Filters**:
   ```php
   if (!empty($networkid) && $networkid != '-1') {
       $query .= ' and paymentnetworkid = ' . $networkid . '';
   }
   if (!empty($branchid) && $branchid != '-1') {
       $query .=' and bills.branchid = ' . $branchid . '';
   }
   ```

3. **Process Report Types**:
   - `reportType = 0`: Detailed transaction report
   - `reportType = 1`: Summary/totals report

**Detailed vs Summary Reports**:
```php
if ($reportType == 0) {
    // Detailed report - show individual transactions
    $allData = $billsExt->queryNetworkReport($query);
} else {
    // Summary report - show totals by network
    $allData = $billsExt->queryTotalNetworkReportButMada($query);
}
```

---

### 3. **MADA Payment Processing** - Special Network Handling
**Location**: Lines 124-157  
**Purpose**: Handle MADA payment network with tiered commission structure

**MADA Commission Structure**:
```php
if ($networkid == 4) { // MADA network
    $madaData = $billsExt->queryTotalNetworkReportMada($query);
    $madaData->totalNet = $madaData->totalCarry;
    $payedTotal += $madaData->totalCarry;
    
    // Tiered commission calculation
    if ($madaData->totalCarry < 5000) {
        $dis = (7 * $madaData->totalCarry) / 1000; // 0.7% for under 5000
    } else {
        $dis = 40; // Flat 40 for 5000 and above
    }
    
    $madaData->totalCarry = $dis;
    $netTotal += $madaData->totalCarry;
}
```

**Commission Tiers**:
- **Under 5000**: 0.7% commission (7/1000)
- **5000 and above**: Flat 40 commission

---

## 🔄 Workflows

### Workflow 1: Network Report Generation
```
┌─────────────────────────────────────────────────────────────┐
│               START: Network Report Request                │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Reference Data                                     │
│     - Load all payment networks                             │
│     - Load all branches                                     │
│     - Load YouTube tutorials                                │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Parse Filter Parameters                                 │
│     - Extract date range (from/to)                          │
│     - Get network filter                                    │
│     - Get branch filter                                     │
│     - Determine report type                                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Build Dynamic Query                                     │
│     - Add date range conditions                             │
│     - Add network filter conditions                         │
│     - Add branch filter conditions                          │
│     - Prepare SQL query string                              │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Execute Report Query                                    │
│     - Query network transaction data                        │
│     - Handle MADA special processing                        │
│     - Calculate commissions and totals                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Display Report Results                                  │
│     - Format transaction data                               │
│     - Display totals and summaries                          │
│     - Render report template                                │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Today's network transaction summary |
| `do=show` | Filtered report | Network report with date/filter options |
| `do=sucess` | Success page | Display success message |
| `do=error` | Error page | Display error message |

### Report Parameters
**Filter Parameters**:
- `from` - Start date (YYYY-MM-DD)
- `to` - End date (YYYY-MM-DD)
- `network` - Payment network ID (-1 for all)
- `branch` - Branch ID (-1 for all)
- `reportType` - Report type (0=detailed, 1=summary)

**Example URLs**:
```
# Today's summary
networkreport.php

# Monthly MADA report for branch 1
networkreport.php?do=show&from=2024-12-01&to=2024-12-31&network=4&branch=1&reportType=1

# All networks summary for last week
networkreport.php?do=show&from=2024-12-13&to=2024-12-20&network=-1&branch=-1&reportType=1
```

---

## 🔒 Security & Permissions

### Access Control
**Current Implementation**:
- Session-based authentication required
- No explicit permission checks
- All authenticated users can access reports

**Security Gaps**:
- No role-based access control
- No branch-level restrictions
- No audit logging of report access

### Recommended Security Enhancements
```php
// Add permission checks
if (!hasPermission('view_network_reports')) {
    throw new Exception('Access denied');
}

// Branch-level security
if (!canAccessBranch($_SESSION['userid'], $branchid)) {
    throw new Exception('Branch access denied');
}

// Audit logging
logReportAccess($_SESSION['userid'], 'network_report', $filters);
```

---

## 🔢 Calculation Methods

### Standard Network Commission
```php
// Standard percentage-based commission
foreach ($allData as $data) {
    $commission = ($data->cardvalue * $data->netdiscountpercent) / 100;
    $netTotal += $commission;
}
```

### MADA Tiered Commission
```php
// MADA network special calculation
if ($madaData->totalCarry < 5000) {
    $commission = (7 * $madaData->totalCarry) / 1000; // 0.7%
} else {
    $commission = 40; // Flat rate for high volume
}
```

### Report Totals
```php
// Calculate report totals
$billTotal = 0;    // Sum of all bill amounts
$payedTotal = 0;   // Sum of all card payments  
$netTotal = 0;     // Sum of all commissions

foreach ($transactions as $transaction) {
    $billTotal += $transaction->netbillvalue;
    $payedTotal += $transaction->cardvalue;
    $netTotal += calculateCommission($transaction);
}
```

---

## 📊 Performance Considerations

### Database Optimization
1. **Indexes Required**:
   ```sql
   CREATE INDEX idx_bills_network_date ON bills(paymentnetworkid, billdate);
   CREATE INDEX idx_bills_branch_date ON bills(branchid, billdate);
   CREATE INDEX idx_bills_date_network ON bills(billdate, paymentnetworkid);
   ```

2. **Query Optimization**:
   - Date range filtering with proper indexing
   - Network ID filtering for faster queries
   - Branch filtering for multi-location businesses

### Report Performance
```php
// Optimized query for large datasets
$query = "SELECT 
    paymentnetworkid,
    SUM(netbillvalue) as total_bills,
    SUM(cardvalue) as total_payments,
    COUNT(*) as transaction_count
    FROM bills 
    WHERE billdate >= ? AND billdate <= ?
    GROUP BY paymentnetworkid";
```

### Memory Management
- Pagination for large date ranges
- Summary queries for overview reports
- Proper resource cleanup

---

## 🐛 Common Issues & Troubleshooting

### 1. **MADA Commission Calculation Errors**
**Issue**: Incorrect MADA commission amounts  
**Cause**: Tiered calculation logic errors or data type issues

**Debug**:
```php
// Debug MADA calculation
echo "MADA Total: " . $madaData->totalCarry . "<br>";
if ($madaData->totalCarry < 5000) {
    $commission = (7 * $madaData->totalCarry) / 1000;
    echo "Low volume commission (0.7%): " . $commission;
} else {
    $commission = 40;
    echo "High volume commission (flat): " . $commission;
}
```

### 2. **Date Range Issues**
**Issue**: Reports show no data for valid date ranges  
**Cause**: Date format mismatches or timezone issues

**Fix**:
```php
// Standardize date format
$startDate = date('Y-m-d', strtotime($_REQUEST['from']));
$endDate = date('Y-m-d', strtotime($_REQUEST['to']));

// Add time components for full day coverage
if (!empty($startDate)) $startDate .= ' 00:00:00';
if (!empty($endDate)) $endDate .= ' 23:59:59';
```

### 3. **Network Filter Not Working**
**Issue**: Network filter returns all networks  
**Cause**: String comparison issues or invalid network IDs

**Debug**:
```php
// Debug network filtering
echo "Network ID: '{$networkid}'<br>";
echo "Is -1: " . ($networkid == '-1' ? 'Yes' : 'No') . "<br>";
echo "Is empty: " . (empty($networkid) ? 'Yes' : 'No') . "<br>";
echo "Query: {$query}<br>";
```

### 4. **Performance Issues with Large Date Ranges**
**Issue**: Reports timeout on large date ranges  
**Cause**: Unoptimized queries or missing indexes

**Fix**:
```php
// Add query limits and pagination
$limit = 10000; // Reasonable limit
$query .= " LIMIT {$limit}";

// Consider summary queries for large ranges
if (dateDiffInDays($startDate, $endDate) > 30) {
    // Use aggregated summary query
    $query = "SELECT DATE(billdate) as bill_date, 
                     SUM(cardvalue) as daily_total 
              FROM bills WHERE billdate BETWEEN ? AND ? 
              GROUP BY DATE(billdate)";
}
```

---

## 🧪 Testing Scenarios

### Test Case 1: MADA Commission Calculation
```
1. Create MADA transactions under 5000
2. Verify 0.7% commission calculation
3. Create MADA transactions over 5000  
4. Verify flat 40 commission
5. Test edge case exactly 5000
```

### Test Case 2: Date Range Filtering
```
1. Test single date ranges
2. Test multi-day ranges
3. Test month-end boundaries
4. Test leap year dates
5. Test invalid date formats
```

### Test Case 3: Network and Branch Filtering
```
1. Test single network filter
2. Test all networks (-1)
3. Test single branch filter
4. Test all branches (-1)
5. Test combined filters
```

### Test Case 4: Report Type Differences
```
1. Generate detailed report (type 0)
2. Generate summary report (type 1)
3. Compare totals match between types
4. Verify data completeness
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [bills.md](bills.md) - Bill processing system
- [index.php](index.md) - Dashboard analytics
- [branchesController.php](branchesController.md) - Branch management

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Next Review**: When payment network configurations change