# Masunzu Bar Hotel - Integration Guide

## Overview

This guide explains how to integrate the new features and helpers into your existing pages and workflows.

---

## 1. Invoice Management System

### Initialization

The invoice expiration system is automatically initialized when you include the helper:

```php
require_once __DIR__ . '/../../includes/invoice_management.php';
```

This automatically creates necessary database columns if they don't exist.

### Creating Invoices with Expiration

Instead of inserting directly into the database, use the helper function:

```php
$invoice_data = [
    'stock_manager_id' => 5,
    'status' => 'pending',
    'customer_name' => 'John Doe',
    'phone_number' => '1234567890',
    'province_id' => 1,
    'nif' => '123456789',
    'rc' => 'RC123',
    'invoice_number' => 'INV-001',
    'serve_status' => 'Pending',
    'paid_amount' => 50000,
    'subtotal_amount' => 50000,
    'tax_amount' => 0,
    'tax_rate' => 18.00,
    'tax_mode' => 'HTVA',
    'approval_status' => 'pending',
    'created_by' => $_SESSION['user_id'],
    'payment_method' => 'cash',
    'payment_details' => '',
    'sale_type' => 'retail',
    'is_loan_sale' => 0,
    'loan_amount_bif' => 0,
    'customer_id' => null
];

$items = [
    ['product_id' => 1, 'quantity' => 10],
    ['product_id' => 2, 'quantity' => 5]
];

$invoice_id = create_invoice_with_expiration($invoice_data, $items);

if ($invoice_id) {
    echo "Invoice created successfully with ID: " . $invoice_id;
    // Stock is automatically reserved
} else {
    echo "Failed to create invoice";
}
```

### Checking for Expired Invoices

Call this periodically (e.g., from a cron job or page load):

```php
require_once __DIR__ . '/../../includes/invoice_management.php';

// Check and expire invoices older than 3 hours
$expired_count = check_and_expire_invoices();

if ($expired_count > 0) {
    error_log("Expired {$expired_count} invoices");
}
```

### Approving Invoices

When an invoice is approved, finalize the stock deduction:

```php
require_once __DIR__ . '/../../includes/invoice_management.php';

if (approve_invoice($invoice_id, $_SESSION['user_id'])) {
    echo "Invoice approved";
    // Stock is automatically deducted from inventory
} else {
    echo "Failed to approve invoice";
}
```

---

## 2. Security & Audit Logging

### Setup

Include the security helper in any page that performs critical actions:

```php
require_once __DIR__ . '/../../includes/security.php';
```

### Logging Actions

Log any important action:

```php
// Simple action log
audit_log(
    $_SESSION['user_id'],
    'PAYMENT_PROCESSED',
    'paid_invoices',
    $invoice_id,
    null,
    ['amount' => 50000, 'method' => 'cash'],
    'Payment processed for invoice #' . $invoice_id
);

// Update log (track old and new values)
audit_log(
    $_SESSION['user_id'],
    'INVOICE_STATUS_UPDATED',
    'paid_invoices',
    $invoice_id,
    ['status' => 'pending'],
    ['status' => 'paid'],
    'Invoice status changed'
);
```

### Verifying Authorization

Before performing critical actions:

```php
require_once __DIR__ . '/../../includes/security.php';

if (!verify_transaction_authorization($_SESSION['user_id'], 'paid_invoices', $invoice_id)) {
    die('Unauthorized access');
}
```

### Double-Submission Prevention

In your form:

```php
<?php
require_once __DIR__ . '/../../includes/security.php';
$token = get_transaction_token();
?>
<form method="POST">
    <input type="hidden" name="transaction_token" value="<?php echo htmlspecialchars($token); ?>">
    <!-- form fields -->
</form>
```

In your processing code:

```php
if (!verify_transaction_token($_POST['transaction_token'] ?? '')) {
    die('Invalid or expired transaction token');
}
// Process transaction
```

### Preventing Suspicious Activity

Check before processing large transactions:

```php
if (is_suspicious_activity($_SESSION['user_id'], $amount, 'payment')) {
    error_log("Suspicious activity detected for user " . $_SESSION['user_id']);
    die('Transaction blocked due to security check');
}
```

### Logging Cash Transactions

```php
log_cash_transaction($_SESSION['user_id'], $shift_id, 100000, 'deposit');
```

---

## 3. Export Helpers (CSV & PDF)

### Setup

```php
require_once __DIR__ . '/../../includes/export_helpers.php';
```

### CSV Export

Simple CSV export:

```php
$headers = ['Invoice #', 'Customer', 'Amount', 'Date'];
$rows = [
    ['INV-001', 'John Doe', '50000', '2025-11-06'],
    ['INV-002', 'Jane Smith', '75000', '2025-11-06']
];

export_to_csv($headers, $rows, 'invoices_' . date('Y-m-d') . '.csv');
exit;
```

Numbered export:

```php
$headers = ['#', 'Invoice #', 'Customer', 'Amount'];
$rows = [
    ['INV-001', 'John Doe', '50000'],
    ['INV-002', 'Jane Smith', '75000']
];

export_numbered_data($headers, $rows, 'invoices.csv');
exit;
```

### PDF to New Tab

In your HTML button:

```php
<?php require_once __DIR__ . '/../../includes/export_helpers.php'; ?>

<form method="POST" id="pdf-form">
    <!-- form fields -->
    <button type="button" id="print-pdf">Print PDF</button>
</form>

<?php echo get_pdf_new_tab_script('/path/to/pdf_generator.php', 'print-pdf'); ?>
```

In your PDF generator script:

```php
require_once __DIR__ . '/../../includes/export_helpers.php';

// Generate your PDF
// ...

send_pdf_headers('invoice.pdf');

// Output PDF content
echo $pdf->Output('I', 'invoice.pdf');
exit;
```

---

## 4. Dashboard Metrics

### Setup

```php
require_once __DIR__ . '/../../includes/dashboard_metrics.php';
```

### Get All Metrics

```php
$metrics = get_dashboard_metrics($province_id);

// Access individual metrics:
$expired_count = $metrics['expired_invoices']['count'];
$late_borrowers = $metrics['loan_metrics']['late_borrowers'];
$eligible_clients = $metrics['eligible_loan_clients'];
```

### Get Specific Metrics

```php
// Expired invoices for last 7 days
$expired = get_expired_invoice_metrics($province_id, date('Y-m-d', strtotime('-7 days')), date('Y-m-d'));

echo "Expired invoices: " . $expired['count'];
echo "Total amount: " . number_format($expired['total_amount']);

// Loan metrics
$loans = get_loan_metrics($province_id);

echo "Total outstanding: " . number_format($loans['total_outstanding']);
echo "Late repayments: " . $loans['late_loans'];

// Eligible clients
$eligible = get_eligible_loan_clients($province_id);

echo "Eligible for loans: " . $eligible;

// By province
$by_province = get_loan_metrics_by_province();
foreach ($by_province as $prov) {
    echo $prov['province_name'] . ": " . number_format($prov['total_due']) . " BIF due";
}
```

---

## 5. Integration Examples

### Example 1: Adding Audit Logging to Invoice Creation

```php
<?php
require_once __DIR__ . '/../../includes/invoice_management.php';
require_once __DIR__ . '/../../includes/security.php';

if ($_POST) {
    // Verify token
    if (!verify_transaction_token($_POST['transaction_token'] ?? '')) {
        die('Invalid submission');
    }

    // Check authorization
    if (!user_has_permission($_SESSION['user_id'], 'create_invoice')) {
        die('Unauthorized');
    }

    // Create invoice with expiration
    $invoice_id = create_invoice_with_expiration($invoice_data, $items);

    if ($invoice_id) {
        // Log the action
        audit_log(
            $_SESSION['user_id'],
            'INVOICE_CREATED',
            'paid_invoices',
            $invoice_id,
            null,
            ['customer' => $invoice_data['customer_name'], 'amount' => $invoice_data['paid_amount']],
            'Invoice created and stock reserved'
        );

        echo "Invoice created successfully";
    }
}
?>
```

### Example 2: Dashboard with Metrics

```php
<?php
require_once __DIR__ . '/../../includes/dashboard_metrics.php';

$province_id = $_SESSION['province_id'] ?? null;
$metrics = get_dashboard_metrics($province_id);

extract($metrics);
?>

<div class="dashboard-section">
    <h3>Expired Invoices (Last 7 Days)</h3>
    <p>Count: <strong><?php echo $expired_invoices['count']; ?></strong></p>
    <p>Total Amount: <strong><?php echo number_format($expired_invoices['total_amount']); ?> BIF</strong></p>
    
    <?php if ($expired_invoices['count'] > 0): ?>
        <table>
            <thead>
                <tr>
                    <th>Invoice #</th>
                    <th>Customer</th>
                    <th>Amount</th>
                    <th>Date</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($expired_invoices['list'] as $inv): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($inv['invoice_number']); ?></td>
                        <td><?php echo htmlspecialchars($inv['customer_name']); ?></td>
                        <td><?php echo number_format($inv['paid_amount']); ?></td>
                        <td><?php echo $inv['created_at']; ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>

<div class="dashboard-section">
    <h3>Loan Metrics</h3>
    <p>Total Outstanding: <strong><?php echo number_format($loan_metrics['total_outstanding']); ?> BIF</strong></p>
    <p>Active Loans: <strong><?php echo $loan_metrics['active_loans']; ?></strong></p>
    <p>Late Repayments: <strong><?php echo $loan_metrics['late_loans']; ?></strong></p>
    
    <?php if (count($loan_metrics['late_borrowers']) > 0): ?>
        <h4>Clients Late on Repayment</h4>
        <table>
            <thead>
                <tr>
                    <th>Client Name</th>
                    <th>Outstanding Balance</th>
                    <th>Due Date</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($loan_metrics['late_borrowers'] as $borrower): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($borrower['full_name']); ?></td>
                        <td><?php echo number_format($borrower['loan_balance_bif']); ?></td>
                        <td><?php echo $borrower['next_repayment_date']; ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>

<div class="dashboard-section">
    <h3>Clients Eligible for Loans</h3>
    <p><strong><?php echo $eligible_loan_clients; ?></strong> customers are eligible for new loans</p>
</div>
```

### Example 3: CSV Export from Invoice List

```php
<?php
require_once __DIR__ . '/../../includes/export_helpers.php';

// Handle export request
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    $headers = ['Invoice #', 'Customer', 'Amount', 'Status', 'Date'];
    $rows = [];

    // Fetch data from database
    $conn = get_db_connection();
    $stmt = $conn->prepare("SELECT invoice_number, customer_name, paid_amount, status, created_at FROM paid_invoices LIMIT 100");
    $stmt->execute();
    $invoices = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    $conn->close();

    foreach ($invoices as $inv) {
        $rows[] = [
            $inv['invoice_number'],
            $inv['customer_name'],
            $inv['paid_amount'],
            $inv['status'],
            $inv['created_at']
        ];
    }

    export_to_csv($headers, $rows, 'invoices_' . date('Y-m-d') . '.csv');
    exit;
}

// Display list
?>
<a href="?export=csv">Download as CSV</a>
```

---

## Security Best Practices

1. **Always validate input** - Use filter_var, filter_input, etc.
2. **Verify authorization** - Use verify_transaction_authorization()
3. **Log critical actions** - Use audit_log()
4. **Use transaction tokens** - Prevent double-submission
5. **Check permissions** - Use user_has_permission()
6. **Validate currency** - Use validate_currency()
7. **Track suspicious activity** - Use is_suspicious_activity()
8. **Escape output** - Always use htmlspecialchars() for display

---

## Testing Checklist

- [ ] Invoice expires after 3 hours without approval
- [ ] Stock is reserved when invoice created
- [ ] Stock is reverted when invoice expires
- [ ] Notifications sent to admin and initiator on expiry
- [ ] Audit log captures all actions with IP address
- [ ] Double-submission tokens prevent duplicate transactions
- [ ] Authorization checks work correctly
- [ ] CSV exports include all data correctly
- [ ] PDF opens in new tab
- [ ] Dashboard metrics display correctly
- [ ] Responsive design works on mobile devices

---

## Support

For issues or questions about integration, refer to:
- IMPLEMENTATION_SUMMARY.md - Feature overview
- Database schema - SQL dump file
- Function documentation in helper files
