# Helper Functions Usage Guide

This document describes the common helper functions available throughout the application.

## Overview

The helper functions are available globally in all Blade templates, PHP classes, and controllers. They are defined in:
- **Class**: `App\Helpers\ViewHelper` (static methods)
- **Global Functions**: Available via `app/helpers.php` (autoloaded)

## Available Functions

### Order & Customer ID Formatting

#### `format_order_id($id, $orderNumber = null, $prefix = 'ORD', $padding = 6)`
Format order ID with prefix and padding.

```php
// In Blade template
{{ format_order_id($order->id, $order->order_number) }}
// Output: "ORD-000123" or uses order_number if available

// In PHP class
use App\Helpers\ViewHelper;
$formatted = ViewHelper::formatOrderId($order->id, $order->order_number);
```

#### `format_customer_id($id, $externalId = null, $prefix = 'CUST', $padding = 6)`
Format customer ID with prefix and padding.

```php
// In Blade template
{{ format_customer_id($customer->id, $customer->external_customer_id) }}
// Output: "CUST-000456" or uses external_customer_id if available
```

### Date Formatting

#### `format_date($date, $format = 'Y-m-d', $fallback = 'N/A')`
Format date to specified format.

```php
// In Blade template
{{ format_date($order->order_date) }}
// Output: "2024-01-15"

{{ format_date($order->order_date, 'M d, Y') }}
// Output: "Jan 15, 2024"
```

#### `format_date_with_fallback($primaryDate, $fallbackDate = null, $format = 'Y-m-d')`
Format date with fallback to created_at.

```php
// In Blade template
{{ format_date_with_fallback($order->order_date, $order->created_at) }}
// Uses order_date if available, otherwise uses created_at
```

#### `format_relative_time($date, $fallback = 'N/A')`
Format date as relative time (e.g., "2 hours ago").

```php
// In Blade template
{{ format_relative_time($order->created_at) }}
// Output: "2 hours ago"
```

### Status Formatting

#### `get_status_class($status)`
Get CSS class based on status value.

```php
// In Blade template
<span class="status-badge {{ get_status_class($order->status) }}">
    {{ format_status_display($order->status) }}
</span>
// Output: <span class="status-badge status-active">Completed</span>
```

#### `format_status_display($status)`
Format status for display.

```php
// In Blade template
{{ format_status_display($order->status) }}
// Output: "Completed" (from "COMPLETED")
```

#### `get_status_info($status)`
Get both status class and display text.

```php
// In Blade template
@php
    $statusInfo = get_status_info($order->status);
@endphp
<span class="status-badge {{ $statusInfo['class'] }}">
    {{ $statusInfo['display'] }}
</span>
```

**Status Class Mapping:**
- `status-active`: COMPLETED, ACTIVE, SUCCESS, PAID, APPROVED
- `status-cancelled`: CANCELLED, CANCELED, FAILED, REVERSED, REJECTED, DECLINED
- `status-pending`: PENDING, INITIATED, INPROCESS, PROCESSING, AWAITING

### Amount & Currency Formatting

#### `format_amount($amount, $currency = 'INR', $decimals = 2, $fallback = '0.00')`
Format amount with currency.

```php
// In Blade template
{{ format_amount($order->total_amount, $order->currency) }}
// Output: "1,234.56 USD"

{{ format_amount($order->total_amount, 'EUR', 2) }}
// Output: "1,234.56 EUR"
```

#### `format_currency($amount, $decimals = 2)`
Format currency amount without currency code.

```php
// In Blade template
{{ format_currency($order->total_amount) }}
// Output: "1,234.56"
```

### Text Formatting

#### `format_phone($phone, $fallback = 'N/A')`
Format phone number.

```php
// In Blade template
{{ format_phone($customer->phone) }}
// Output: "(123) 456-7890" (for 10-digit numbers)
```

#### `format_email($email, $maxLength = 50, $fallback = 'N/A')`
Format email (truncate if too long).

```php
// In Blade template
{{ format_email($customer->email) }}
// Output: "user@example.com" or truncated with "..."
```

#### `format_name($name, $fallback = 'N/A')`
Format name (handle null/empty values).

```php
// In Blade template
{{ format_name($customer->full_name) }}
// Output: "John Doe" or "N/A" if empty
```

#### `truncate_text($text, $length = 50, $suffix = '...')`
Truncate text with ellipsis.

```php
// In Blade template
{{ truncate_text($product->description, 100) }}
// Output: "This is a very long description that will be truncated..."
```

### Other Formatting

#### `format_percentage($value, $decimals = 2)`
Format percentage.

```php
// In Blade template
{{ format_percentage(85.5) }}
// Output: "85.50%"
```

#### `format_boolean($value, $trueText = 'Yes', $falseText = 'No')`
Format boolean value.

```php
// In Blade template
{{ format_boolean($customer->status) }}
// Output: "Yes" or "No"
```

#### `get_boolean_status_class($value, $trueClass = 'status-active', $falseClass = 'status-cancelled')`
Get CSS class for boolean value.

```php
// In Blade template
<span class="{{ get_boolean_status_class($customer->status) }}">
    {{ format_boolean($customer->status) }}
</span>
```

## Usage Examples

### Example 1: Order Display in Blade Template

```blade
@foreach($orders as $order)
    <tr>
        <td>{{ format_order_id($order->id, $order->order_number) }}</td>
        <td>{{ format_date_with_fallback($order->order_date, $order->created_at) }}</td>
        <td>{{ format_amount($order->total_amount, $order->currency) }}</td>
        <td>
            <span class="status-badge {{ get_status_class($order->status) }}">
                {{ format_status_display($order->status) }}
            </span>
        </td>
    </tr>
@endforeach
```

### Example 2: Customer Profile Display

```blade
<div class="customer-info">
    <h3>{{ format_name($customer->full_name) }}</h3>
    <p>Email: {{ format_email($customer->email) }}</p>
    <p>Phone: {{ format_phone($customer->phone) }}</p>
    <p>Customer ID: {{ format_customer_id($customer->id, $customer->external_customer_id) }}</p>
    <p>Joined: {{ format_date($customer->created_at, 'M d, Y') }}</p>
    <p>Last Active: {{ format_relative_time($customer->updated_at) }}</p>
</div>
```

### Example 3: Using in PHP Classes

```php
use App\Helpers\ViewHelper;

class OrderController extends Controller
{
    public function show(Order $order)
    {
        $formattedOrder = [
            'id' => ViewHelper::formatOrderId($order->id, $order->order_number),
            'date' => ViewHelper::formatDate($order->order_date),
            'amount' => ViewHelper::formatAmount($order->total_amount, $order->currency),
            'status' => ViewHelper::getStatusInfo($order->status),
        ];
        
        return view('orders.show', compact('formattedOrder'));
    }
}
```

## Benefits

1. **Consistency**: All formatting follows the same rules across the application
2. **Maintainability**: Update formatting logic in one place
3. **Reusability**: Use the same functions in Blade templates, controllers, and classes
4. **Type Safety**: Functions handle null values gracefully with fallbacks
5. **Flexibility**: Customizable parameters for different use cases

### Churn Risk Calculation

#### `calculate_churn_risk($customer, $subscription = null, $options = [])`
Calculate churn risk for customer subscription with detailed analysis.

```php
// In Blade template
@php
    $churnRisk = calculate_churn_risk($customer);
@endphp

<div class="churn-risk {{ get_churn_risk_class($churnRisk['level']) }}">
    <h4>Churn Risk: {{ $churnRisk['level_display'] }} ({{ $churnRisk['score'] }}%)</h4>
    <p>Days until expiry: {{ $churnRisk['days_until_expiry'] ?? 'N/A' }}</p>
    
    <h5>Risk Factors:</h5>
    <ul>
        @foreach($churnRisk['factors'] as $factor)
            <li>{{ $factor }}</li>
        @endforeach
    </ul>
    
    <h5>Recommendations:</h5>
    <ul>
        @foreach($churnRisk['recommendations'] as $recommendation)
            <li>{{ $recommendation }}</li>
        @endforeach
    </ul>
</div>
```

**Return Structure:**
```php
[
    'score' => 75,                    // Risk score (0-100)
    'level' => 'high',                // Risk level: 'low', 'medium', 'high', 'critical'
    'level_display' => 'High',        // Formatted display name
    'factors' => [                    // Array of risk factors
        'Subscription expires in 5 days',
        'No payment in 45 days',
        '2 failed payment(s) in last 30 days'
    ],
    'recommendations' => [            // Array of action recommendations
        'High priority - Reach out to customer within 24 hours',
        'Consider offering renewal incentives',
        'Send subscription renewal reminder'
    ],
    'days_until_expiry' => 5,        // Days until subscription expires
    'subscription_active' => true,    // Whether subscription is active
    'auto_renew_enabled' => false     // Whether auto-renewal is enabled
]
```

#### `get_churn_risk_level($score)`
Get churn risk level based on score.

```php
// In Blade template
{{ get_churn_risk_level(75) }}
// Output: "high"
```

**Risk Level Thresholds:**
- **Critical**: 80-100 points
- **High**: 60-79 points
- **Medium**: 35-59 points
- **Low**: 0-34 points

#### `get_churn_risk_class($riskLevelOrScore)`
Get CSS class for churn risk level.

```php
// In Blade template
<span class="badge {{ get_churn_risk_class($churnRisk['level']) }}">
    {{ $churnRisk['level_display'] }}
</span>

// Or using score directly
<span class="badge {{ get_churn_risk_class($churnRisk['score']) }}">
    {{ $churnRisk['level_display'] }}
</span>
```

**CSS Classes:**
- `churn-risk-critical` - For critical risk
- `churn-risk-high` - For high risk
- `churn-risk-medium` - For medium risk
- `churn-risk-low` - For low risk

### Churn Risk Calculation Example

```php
// In PHP Controller or Class
use App\Helpers\ViewHelper;
use App\Models\Customer;

$customer = Customer::with('subscriptions')->find($customerId);
$churnRisk = ViewHelper::calculateChurnRisk($customer);

if ($churnRisk['score'] >= 60) {
    // High risk - take immediate action
    $this->sendRetentionEmail($customer, $churnRisk);
}
```

```blade
{{-- In Blade Template --}}
@php
    $churnRisk = calculate_churn_risk($customer, $customer->subscriptions->first());
@endphp

<div class="churn-risk-card">
    <div class="risk-header">
        <h3>Churn Risk Assessment</h3>
        <span class="risk-badge {{ get_churn_risk_class($churnRisk['score']) }}">
            {{ $churnRisk['level_display'] }} Risk ({{ $churnRisk['score'] }}%)
        </span>
    </div>
    
    @if($churnRisk['days_until_expiry'])
        <p><strong>Expires in:</strong> {{ $churnRisk['days_until_expiry'] }} days</p>
    @endif
    
    <div class="risk-factors">
        <h4>Risk Factors:</h4>
        <ul>
            @foreach($churnRisk['factors'] as $factor)
                <li>{{ $factor }}</li>
            @endforeach
        </ul>
    </div>
    
    <div class="recommendations">
        <h4>Recommended Actions:</h4>
        <ul>
            @foreach($churnRisk['recommendations'] as $recommendation)
                <li>{{ $recommendation }}</li>
            @endforeach
        </ul>
    </div>
</div>
```

**Churn Risk Factors Considered:**
1. **Subscription Expiration** (0-35 points): How soon the subscription expires
2. **Last Payment Date** (0-30 points): Days since last successful payment
3. **Failed Payments** (0-20 points): Number of failed payments in last 30 days
4. **Customer Tenure** (0-15 points): How long the customer has been active
5. **Subscription Status** (0-10 points): Whether subscription is active
6. **Auto-Renewal** (0-10 points): Whether auto-renewal is enabled
7. **Account Status** (0-10 points): Whether customer account is active
8. **Payment Method Issues** (0-5 points): Recent failures with payment method

## Notes

- All functions are available globally after running `composer dump-autoload`
- Functions handle null values gracefully with appropriate fallbacks
- The ViewHelper class can be used for static method calls if preferred
- Status classes are mapped to common status values used in the application
- Churn risk calculation automatically loads active subscription if not provided
- Churn risk factors are weighted to prioritize subscription expiration and payment issues

