# Right Sidebar Context Panel Integration Guide

## Overview

The Right Sidebar provides 4 contextual panels accessible via icon tabs:
1. **Activity Feed** - Record change history
2. **Data Scope** - Location/permissions indicator
3. **Quick Actions** - Context-aware shortcuts
4. **Related Records** - Linked data navigator

## Quick Start

### 1. Add Routes to `index.php`

```php
// Right Sidebar API endpoints
$router->addRoute('GET', '/api/right-sidebar/activity', 'RightSidebarController', 'activity');
$router->addRoute('GET', '/api/right-sidebar/scope', 'RightSidebarController', 'scope');
$router->addRoute('GET', '/api/right-sidebar/actions', 'RightSidebarController', 'actions');
$router->addRoute('GET', '/api/right-sidebar/related', 'RightSidebarController', 'related');
$router->addRoute('POST', '/api/user-preferences', 'UserController', 'savePreference');
$router->addRoute('GET', '/api/switch-location', 'LocationController', 'switchLocation');
```

### 2. Add Sidebar to Any View

```php
<!-- In your view file (e.g., views/customers/show.php) -->
<?php
require_once BASE_PATH . '/views/components/right_sidebar.php';
renderRightSidebar([
    'record_type' => 'customer',
    'record_id' => $customer['id'],
    'context' => $customer
]);
?>
```

### 3. Database Tables Required

#### Activity Log Table (if not exists)
```sql
CREATE TABLE IF NOT EXISTS activity_log (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT,
    record_type VARCHAR(50),
    record_id INT,
    action VARCHAR(255),
    details TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_record (record_type, record_id),
    INDEX idx_user (user_id),
    FOREIGN KEY (user_id) REFERENCES users(id)
);
```

#### User Action History (for Quick Actions)
```sql
CREATE TABLE IF NOT EXISTS user_action_history (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT,
    action_name VARCHAR(100),
    action_url VARCHAR(255),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_user_date (user_id, created_at),
    FOREIGN KEY (user_id) REFERENCES users(id)
);
```

#### Sidebar Actions in `page_actions` Table
Add `group_name = 'sidebar'` to relevant actions:

```sql
INSERT INTO page_actions (page_identifier, action_name, icon, action_type, action_target, group_name, display_order)
VALUES
('customer', 'Create Order', 'fas fa-shopping-cart', 'link', 'sales-orders/create?customer_id={customer_id}', 'sidebar', 1),
('customer', 'Record Payment', 'fas fa-dollar-sign', 'link', 'payments/create?customer_id={customer_id}', 'sidebar', 2),
('customer', 'View Orders', 'fas fa-list', 'link', 'sales-orders?customer_id={customer_id}', 'sidebar', 3);
```

## Usage Examples

### Example 1: Customer Detail Page

```php
<!-- views/customers/show.php -->
<div class="container">
    <div class="row">
        <div class="col-md-12">
            <h1>Customer: <?= e($customer['name']) ?></h1>
            
            <!-- Customer details here -->
            <div class="card">
                <div class="card-body">
                    <!-- ... -->
                </div>
            </div>
        </div>
    </div>
</div>

<?php
// Add right sidebar
require_once BASE_PATH . '/views/components/right_sidebar.php';
renderRightSidebar([
    'record_type' => 'customer',
    'record_id' => $customer['id'],
    'context' => [
        'customer_id' => $customer['id'],
        'customer_name' => $customer['name']
    ]
]);
?>
```

### Example 2: Sales Order Page

```php
<!-- views/sales_orders/show.php -->
<?php
require_once BASE_PATH . '/views/components/right_sidebar.php';
renderRightSidebar([
    'record_type' => 'sales_order',
    'record_id' => $order['id'],
    'context' => [
        'order_id' => $order['id'],
        'customer_id' => $order['customer_id']
    ]
]);
?>
```

### Example 3: Dashboard (Scope Only)

```php
<!-- views/dashboard.php -->
<?php
// On dashboard, you might only want Data Scope visible
require_once BASE_PATH . '/views/components/right_sidebar.php';
renderRightSidebar([
    'record_type' => null, // No specific record
    'record_id' => null,
    'context' => []
]);
?>
```

## Extending Related Records

To add related records for new entity types, edit `RightSidebarController.php`:

```php
// In related() method, add new case:
case 'product':
    $relatedRecords = $this->getProductRelatedRecords($recordId);
    break;

// Implement the method:
private function getProductRelatedRecords($productId) {
    $db = Database::getInstance();
    $related = [];
    
    // Work Orders using this product
    $workOrders = $db->fetchAll(
        "SELECT id, wo_number as title, status as subtitle 
         FROM work_orders 
         WHERE product_id = ? 
         ORDER BY created_at DESC LIMIT 5", 
        [$productId]
    );
    $woCount = $db->fetchOne(
        "SELECT COUNT(*) as count FROM work_orders WHERE product_id = ?", 
        [$productId]
    )['count'];
    
    $related[] = [
        'key' => 'work_orders',
        'label' => 'Work Orders',
        'icon' => 'fas fa-tools',
        'count' => $woCount,
        'records' => $workOrders,
        'url_base' => 'work-orders',
        'view_all_url' => 'work-orders?product_id=' . $productId
    ];
    
    // Sales Orders
    $salesOrders = $db->fetchAll(
        "SELECT so.id, so.order_number as title, so.status as subtitle
         FROM sales_order_items soi
         JOIN sales_orders so ON soi.order_id = so.id
         WHERE soi.product_id = ?
         GROUP BY so.id
         ORDER BY so.created_at DESC LIMIT 5",
        [$productId]
    );
    $soCount = $db->fetchOne(
        "SELECT COUNT(DISTINCT so.id) as count
         FROM sales_order_items soi
         JOIN sales_orders so ON soi.order_id = so.id
         WHERE soi.product_id = ?",
        [$productId]
    )['count'];
    
    $related[] = [
        'key' => 'sales_orders',
        'label' => 'Sales Orders',
        'icon' => 'fas fa-shopping-cart',
        'count' => $soCount,
        'records' => $salesOrders,
        'url_base' => 'sales-orders',
        'view_all_url' => 'sales-orders?product_id=' . $productId
    ];
    
    return $related;
}
```

## Logging Activity

To populate the Activity Feed, log actions in your controllers:

```php
// In CustomerController::update()
public function update($id) {
    // ... perform update ...
    
    // Log activity
    $db = Database::getInstance();
    $db->insert('activity_log', [
        'user_id' => $_SESSION['user_id'],
        'record_type' => 'customer',
        'record_id' => $id,
        'action' => 'Updated customer information',
        'details' => 'Changed: ' . implode(', ', array_keys($changes))
    ]);
    
    // ... rest of code ...
}
```

## Helper Functions

Add to `includes/helpers.php`:

```php
/**
 * Format time as "X ago"
 */
function timeAgo($timestamp) {
    $time = strtotime($timestamp);
    $diff = time() - $time;
    
    if ($diff < 60) return 'just now';
    if ($diff < 3600) return floor($diff / 60) . ' minutes ago';
    if ($diff < 86400) return floor($diff / 3600) . ' hours ago';
    if ($diff < 604800) return floor($diff / 86400) . ' days ago';
    
    return date('M j, Y', $time);
}

/**
 * Log user action for quick actions tracking
 */
function logUserAction($actionName, $actionUrl) {
    if (!isset($_SESSION['user_id'])) return;
    
    $db = Database::getInstance();
    $db->insert('user_action_history', [
        'user_id' => $_SESSION['user_id'],
        'action_name' => $actionName,
        'action_url' => $actionUrl
    ]);
}
```

## Styling Considerations

The sidebar uses CSS variables for theming:
- `--bs-body-bg` - Background color
- `--bs-border-color` - Border color
- `--bs-primary` - Primary accent color
- `--bs-tertiary-bg` - Section backgrounds
- `--bs-secondary-color` - Muted text

These should already be defined in your Bootstrap theme.

## Performance Tips

1. **Lazy Loading**: Tabs load content only when clicked (already implemented)
2. **Caching**: Consider caching related record counts for high-traffic pages
3. **Pagination**: Activity feed limits to 50 entries (adjustable in controller)
4. **Indexing**: Ensure database indexes exist on foreign keys used in queries

## Mobile Behavior

On screens < 768px:
- Sidebar becomes full-width overlay
- Toggle button remains visible
- Same functionality, better mobile UX

## Browser Compatibility

- Modern browsers (Chrome, Firefox, Safari, Edge)
- Uses ES6 JavaScript features
- Requires `fetch` API support
- Bootstrap 5 CSS variables

## Next Steps

1. Add routes to `public/index.php`
2. Create database tables (migration file recommended)
3. Test on customer detail page first
4. Roll out to other entity pages (orders, products, etc.)
5. Customize related records for your entity types
6. Add activity logging to your controllers

## Troubleshooting

**Sidebar doesn't appear:**
- Check browser console for JS errors
- Verify routes are registered
- Ensure `base_url()` helper is correct

**No data in tabs:**
- Check database tables exist
- Verify record_type and record_id are passed correctly
- Check browser Network tab for API errors

**Styling issues:**
- Ensure Bootstrap 5 is loaded
- Check for CSS conflicts with existing styles
- Verify CSS variables are defined in theme
