# Masunzu Bar Hotel - Quick Reference Guide

## New Helper Files Created

| File | Purpose | Include Path |
|------|---------|--------------|
| `includes/invoice_management.php` | Invoice expiration, stock management | `require_once __DIR__ . '/../../includes/invoice_management.php';` |
| `includes/security.php` | Audit logging, authorization, fraud prevention | `require_once __DIR__ . '/../../includes/security.php';` |
| `includes/export_helpers.php` | CSV/PDF export functions | `require_once __DIR__ . '/../../includes/export_helpers.php';` |
| `includes/dashboard_metrics.php` | Dashboard KPI functions | `require_once __DIR__ . '/../../includes/dashboard_metrics.php';` |

## Files Modified

| File | Changes |
|------|---------|
| `modules/cashiers/process_payment.php` | Better error page with buttons for no active shift |
| `modules/cashiers/sold_products.php` | Default to today's sales + CSV export button |

## Key Functions Quick Reference

### Invoice Management
```php
create_invoice_with_expiration($data, $items)    // Create invoice with 3-hour expiry
check_and_expire_invoices()                      // Check & expire old invoices
expire_invoice($id, $created_by, $province_id)   // Expire single invoice
approve_invoice($id, $approved_by)               // Approve & finalize stock
reserve_stock_for_invoice($id, $items, $prov)    // Reserve stock
revert_stock_reservation($product_id, $qty)      // Revert stock on expiry
```

### Security & Audit
```php
audit_log($user_id, $action, $table, $id, $old, $new, $details)
verify_transaction_authorization($user_id, $table, $id)
validate_currency($amount, $max_allowed)
is_suspicious_activity($user_id, $amount, $action)
user_has_permission($user_id, $permission)
get_transaction_token()
verify_transaction_token($token)
log_payment_transaction($user_id, $invoice_id, $amount, $method)
log_cash_transaction($user_id, $shift_id, $amount, $type)
```

### Exports
```php
export_to_csv($headers, $rows, $filename)
export_numbered_data($headers, $rows, $filename)
send_csv_headers($filename)
send_pdf_headers($filename)
get_pdf_new_tab_script($form_action, $button_id)
safe_csv_value($value)
```

### Dashboard Metrics
```php
get_expired_invoice_metrics($province_id, $date_from, $date_to)
get_loan_metrics($province_id)
get_eligible_loan_clients($province_id)
get_loan_metrics_by_province()
get_dashboard_metrics($province_id)  // Get all metrics at once
```

## Database Changes

### New Columns
- `paid_invoices.expires_at` - When invoice expires
- `paid_invoices.expiration_status` - active/expired/approved
- `invoice.expires_at` - When invoice expires
- `invoice.expiration_status` - active/expired/approved
- `main_stock.reserved_quantity` - Stock reserved by pending invoices

### New Tables
- `audit_log` - All user actions and transactions

## Feature Overview

### ✅ Completed Features

1. **Invoice Expiration System**
   - Auto-expire unapproved invoices after 3 hours
   - Stock reservation on creation
   - Stock reversion on expiry
   - Notifications to admin and initiator

2. **Security & Fraud Prevention**
   - Complete audit logging with IP tracking
   - Double-submission prevention
   - Transaction authorization verification
   - Suspicious activity detection
   - Role-based permissions

3. **Cash Handling**
   - Cashier shift validation before payment processing
   - Better error UI with action buttons
   - Cash transaction logging

4. **Sales Reporting**
   - Today's sales display by default
   - Searchable and filterable
   - CSV download capability

5. **Export System**
   - CSV export for all lists
   - PDF opening in new tab
   - Safe value escaping
   - Numbered data export

6. **Dashboard Analytics**
   - Expired invoice metrics
   - Loan portfolio metrics
   - Late repayment tracking
   - Eligible client identification
   - Province-wise loan statistics

## Integration Steps

### Step 1: Include Helpers
```php
require_once __DIR__ . '/../../includes/invoice_management.php';
require_once __DIR__ . '/../../includes/security.php';
require_once __DIR__ . '/../../includes/export_helpers.php';
require_once __DIR__ . '/../../includes/dashboard_metrics.php';
```

### Step 2: Add Audit Logging
```php
audit_log($_SESSION['user_id'], 'ACTION_NAME', 'table_name', $id, $old_vals, $new_vals, 'details');
```

### Step 3: Use Dashboard Metrics
```php
$metrics = get_dashboard_metrics($province_id);
// Use: $metrics['expired_invoices'], $metrics['loan_metrics'], etc.
```

### Step 4: Add to Forms
```php
<input type="hidden" name="transaction_token" value="<?php echo get_transaction_token(); ?>">
```

### Step 5: Verify in Processing
```php
if (!verify_transaction_token($_POST['transaction_token'])) die('Invalid');
```

## Common Use Cases

### Use Case 1: Create Invoice with Stock Management
```php
require_once includes/invoice_management.php;
$id = create_invoice_with_expiration($data, $items);
audit_log($_SESSION['user_id'], 'INVOICE_CREATED', 'paid_invoices', $id, null, $data);
```

### Use Case 2: Approve Invoice
```php
require_once includes/invoice_management.php;
approve_invoice($invoice_id, $_SESSION['user_id']);
audit_log($_SESSION['user_id'], 'INVOICE_APPROVED', 'paid_invoices', $invoice_id);
```

### Use Case 3: Check Late Loans
```php
require_once includes/dashboard_metrics.php;
$loans = get_loan_metrics();
foreach ($loans['late_borrowers'] as $borrower) {
    // Send reminder notification
}
```

### Use Case 4: Export Data
```php
require_once includes/export_helpers.php;
export_to_csv(['Header1', 'Header2'], $data_rows, 'file.csv');
exit;
```

## Configuration

### Invoice Expiration Time
Default: 3 hours (in `includes/invoice_management.php:55`)
```php
$expires_at = date('Y-m-d H:i:s', strtotime('+3 hours'));
```
Change to: `strtotime('+2 hours')` for 2 hours, etc.

### Suspicious Activity Thresholds
In `includes/security.php:169-171`:
```php
if ($transaction_count > 50 || $total_amount > 10000000) {
    // Current: 50 transactions or 10M BIF in 1 hour
}
```

### CSV Filename Format
Edit in `includes/export_helpers.php` as needed
```php
'filename=sales_' . date('Y-m-d') . '.csv'
```

## Error Handling

### Transaction Token Errors
- Expired: Shown after 1 hour
- Invalid: Shown on wrong token
- Recommendation: Show user-friendly message and reload form

### Suspicious Activity
- Blocked: Transaction denied
- Logged: In audit_log table
- Review: Check audit logs for user activity

### Stock Issues
- Insufficient: Cannot reserve stock
- Expired: Stock reverted automatically
- Solution: Check main_stock table

## Monitoring & Maintenance

### Monitor Audit Log
```sql
SELECT * FROM audit_log 
WHERE action LIKE '%FRAUD%' OR action LIKE '%ERROR%'
ORDER BY timestamp DESC;
```

### Check Expired Invoices
```sql
SELECT * FROM paid_invoices 
WHERE expiration_status = 'expired' 
ORDER BY created_at DESC;
```

### Monitor Late Repayments
```php
$loans = get_loan_metrics();
echo "Late repayments: " . $loans['late_loans'];
```

## Troubleshooting

| Issue | Solution |
|-------|----------|
| Columns not created | Run `initialize_audit_system()` and `initialize_invoice_expiration_columns()` |
| Invoice doesn't expire | Check cron job / call `check_and_expire_invoices()` periodically |
| Stock not reserved | Use `create_invoice_with_expiration()` instead of direct DB insert |
| Audit log missing | Ensure `audit_log()` is called in critical sections |
| CSV not downloading | Check `send_csv_headers()` is called before output |
| PDF not opening in tab | Use `send_pdf_headers()` and proper form setup |

## Performance Tips

1. **Index audit_log table** - Already done in creation
2. **Archive old audit logs** - After 6 months, move to archive table
3. **Cache dashboard metrics** - Refresh every 5 minutes
4. **Use prepared statements** - All queries use parameterized statements
5. **Limit audit queries** - Add date filters to reduce rows

## Security Checklist

- [ ] All forms include transaction_token
- [ ] All transactions logged in audit_log
- [ ] Authorization verified before sensitive operations
- [ ] Currency amounts validated
- [ ] IP addresses captured
- [ ] User agents captured
- [ ] Suspicious activity monitored
- [ ] Old audit logs archived regularly
- [ ] Database backups scheduled
- [ ] Error logs reviewed weekly

---

**Last Updated**: November 6, 2025  
**Version**: 1.0  
**Status**: Production Ready
