<?php
/**
 * Product Activity Log Viewer
 * XChange 2025 Registration System
 */

require_once 'auth_rbac.php';
require_once '../db_config.php';
require_once 'ProductLogger.php';

// Get database connection
$conn = getDBConnection();

// Check authentication and permissions
$auth = new AdminAuth($conn);
$auth->requirePermission('registrations');

$productLogger = new ProductLogger($conn, $auth->getCurrentUser());
$currentPage = 'product-activity-log';

// Get filters
$filters = [
    'activity_type' => $_GET['activity_type'] ?? '',
    'product_id' => $_GET['product_id'] ?? '',
    'user_id' => $_GET['user_id'] ?? '',
    'severity' => $_GET['severity'] ?? '',
    'date_from' => $_GET['date_from'] ?? '',
    'date_to' => $_GET['date_to'] ?? '',
    'limit' => intval($_GET['limit'] ?? 50)
];

// Get activity log data
$activities = $productLogger->getRecentActivities($filters['limit'], $filters);

// Get filter options
$activityTypes = [
    'product_create' => 'Product Created',
    'product_update' => 'Product Updated', 
    'product_delete' => 'Product Deleted',
    'product_status_change' => 'Product Status Changed',
    'category_create' => 'Category Created',
    'category_update' => 'Category Updated',
    'category_delete' => 'Category Deleted',
    'pricing_update' => 'Pricing Updated',
    'stock_adjustment' => 'Stock Adjusted',
    'stock_reservation' => 'Stock Reserved',
    'stock_confirmation' => 'Stock Confirmed',
    'purchase_update' => 'Purchase Updated',
    'bulk_operation' => 'Bulk Operation'
];

$severityLevels = [
    'low' => 'Low',
    'medium' => 'Medium', 
    'high' => 'High',
    'critical' => 'Critical'
];

// Get products for filter
$sql = "SELECT id, name FROM products ORDER BY name";
$stmt = $conn->prepare($sql);
$stmt->execute();
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get users for filter
$sql = "SELECT id, full_name as name FROM admin_users ORDER BY full_name";
$stmt = $conn->prepare($sql);
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Product Activity Log - XChange 2025</title>
    <?php include '../includes/favicon.php'; ?>
    <link rel="stylesheet" href="../styles.css">
    <link rel="stylesheet" href="admin.css">
    <style>
        .activity-log-container {
            max-width: 1600px;
            margin: 0 auto;
            padding: 2rem;
        }
        
        .log-filters {
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .filter-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin-bottom: 1rem;
        }
        
        .filter-actions {
            display: flex;
            gap: 1rem;
            justify-content: flex-end;
        }
        
        .activity-table {
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            overflow: hidden;
        }
        
        .activity-row {
            display: grid;
            grid-template-columns: 120px 150px 200px 1fr 120px 100px 150px;
            gap: 1rem;
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
            align-items: start;
        }
        
        .activity-row:hover {
            background: #f8fafc;
        }
        
        .activity-header {
            background: #f8fafc;
            font-weight: 600;
            color: #475569;
            border-bottom: 2px solid #e2e8f0;
        }
        
        .activity-type {
            font-weight: 500;
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.875rem;
        }
        
        .type-product { background: #dbeafe; color: #1e40af; }
        .type-category { background: #dcfce7; color: #166534; }
        .type-pricing { background: #fef3c7; color: #92400e; }
        .type-stock { background: #e0e7ff; color: #3730a3; }
        .type-purchase { background: #fce7f3; color: #be185d; }
        .type-bulk { background: #f3e8ff; color: #7c3aed; }
        
        .severity-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 500;
        }
        
        .severity-low { background: #f0f9ff; color: #0369a1; }
        .severity-medium { background: #fef3c7; color: #92400e; }
        .severity-high { background: #fed7d7; color: #c53030; }
        .severity-critical { background: #fecaca; color: #dc2626; }
        
        .activity-description {
            font-size: 0.875rem;
            line-height: 1.4;
        }
        
        .activity-details {
            font-size: 0.75rem;
            color: #64748b;
        }
        
        .json-data {
            background: #f1f5f9;
            padding: 0.5rem;
            border-radius: 4px;
            font-family: monospace;
            font-size: 0.75rem;
            max-height: 100px;
            overflow-y: auto;
            margin-top: 0.5rem;
        }
        
        .expand-btn {
            background: none;
            border: none;
            color: #6366f1;
            cursor: pointer;
            font-size: 0.75rem;
            text-decoration: underline;
        }
        
        .time-category {
            font-size: 0.75rem;
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
        }
        
        .time-just_now { background: #dcfce7; color: #166534; }
        .time-today { background: #dbeafe; color: #1e40af; }
        .time-this_week { background: #fef3c7; color: #92400e; }
        .time-older { background: #f1f5f9; color: #64748b; }
        
        .empty-state {
            text-align: center;
            padding: 3rem;
            color: #64748b;
        }
    </style>
</head>
<body>
    <?php include 'includes/admin_nav.php'; ?>
    
    <div class="activity-log-container">
        <div class="page-header">
            <h1>Product Activity Log</h1>
            <p>Comprehensive audit trail of all product-related activities</p>
        </div>
        
        <!-- Filters -->
        <div class="log-filters">
            <form method="GET" class="filter-form">
                <div class="filter-grid">
                    <div class="form-group">
                        <label class="form-label">Activity Type</label>
                        <select name="activity_type" class="form-control">
                            <option value="">All Activities</option>
                            <?php foreach ($activityTypes as $value => $label): ?>
                                <option value="<?php echo $value; ?>" <?php echo $filters['activity_type'] === $value ? 'selected' : ''; ?>>
                                    <?php echo $label; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Product</label>
                        <select name="product_id" class="form-control">
                            <option value="">All Products</option>
                            <?php foreach ($products as $product): ?>
                                <option value="<?php echo $product['id']; ?>" <?php echo $filters['product_id'] == $product['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($product['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">User</label>
                        <select name="user_id" class="form-control">
                            <option value="">All Users</option>
                            <?php foreach ($users as $user): ?>
                                <option value="<?php echo $user['id']; ?>" <?php echo $filters['user_id'] == $user['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($user['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Severity</label>
                        <select name="severity" class="form-control">
                            <option value="">All Levels</option>
                            <?php foreach ($severityLevels as $value => $label): ?>
                                <option value="<?php echo $value; ?>" <?php echo $filters['severity'] === $value ? 'selected' : ''; ?>>
                                    <?php echo $label; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Date From</label>
                        <input type="date" name="date_from" class="form-control" value="<?php echo $filters['date_from']; ?>">
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Date To</label>
                        <input type="date" name="date_to" class="form-control" value="<?php echo $filters['date_to']; ?>">
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Limit</label>
                        <select name="limit" class="form-control">
                            <option value="25" <?php echo $filters['limit'] == 25 ? 'selected' : ''; ?>>25</option>
                            <option value="50" <?php echo $filters['limit'] == 50 ? 'selected' : ''; ?>>50</option>
                            <option value="100" <?php echo $filters['limit'] == 100 ? 'selected' : ''; ?>>100</option>
                            <option value="200" <?php echo $filters['limit'] == 200 ? 'selected' : ''; ?>>200</option>
                        </select>
                    </div>
                </div>
                
                <div class="filter-actions">
                    <a href="product-activity-log.php" class="btn btn-secondary">Clear Filters</a>
                    <button type="submit" class="btn btn-primary">Apply Filters</button>
                </div>
            </form>
        </div>
        
        <!-- Activity Log Table -->
        <div class="activity-table">
            <div class="activity-row activity-header">
                <div>Type</div>
                <div>User</div>
                <div>Product/Category</div>
                <div>Description</div>
                <div>Severity</div>
                <div>When</div>
                <div>Timestamp</div>
            </div>
            
            <?php if (empty($activities)): ?>
                <div class="empty-state">
                    <p>No activity records found matching your criteria.</p>
                </div>
            <?php else: ?>
                <?php foreach ($activities as $activity): ?>
                    <div class="activity-row">
                        <div>
                            <?php
                            $typeClass = 'type-product';
                            if (strpos($activity['activity_type'], 'category') !== false) $typeClass = 'type-category';
                            elseif (strpos($activity['activity_type'], 'pricing') !== false) $typeClass = 'type-pricing';
                            elseif (strpos($activity['activity_type'], 'stock') !== false) $typeClass = 'type-stock';
                            elseif (strpos($activity['activity_type'], 'purchase') !== false) $typeClass = 'type-purchase';
                            elseif (strpos($activity['activity_type'], 'bulk') !== false) $typeClass = 'type-bulk';
                            ?>
                            <span class="activity-type <?php echo $typeClass; ?>">
                                <?php echo $activityTypes[$activity['activity_type']] ?? ucfirst(str_replace('_', ' ', $activity['activity_type'])); ?>
                            </span>
                        </div>
                        
                        <div>
                            <div class="font-medium"><?php echo htmlspecialchars($activity['user_name']); ?></div>
                            <div class="activity-details"><?php echo htmlspecialchars($activity['user_role']); ?></div>
                        </div>
                        
                        <div>
                            <?php if ($activity['product_name']): ?>
                                <div class="font-medium"><?php echo htmlspecialchars($activity['product_name']); ?></div>
                                <?php if ($activity['product_code']): ?>
                                    <div class="activity-details"><?php echo htmlspecialchars($activity['product_code']); ?></div>
                                <?php endif; ?>
                            <?php elseif ($activity['category_name']): ?>
                                <div class="font-medium"><?php echo htmlspecialchars($activity['category_name']); ?></div>
                                <div class="activity-details">Category</div>
                            <?php else: ?>
                                <div class="activity-details">N/A</div>
                            <?php endif; ?>
                        </div>
                        
                        <div>
                            <div class="activity-description"><?php echo htmlspecialchars($activity['action_description']); ?></div>
                            <?php if ($activity['old_values'] || $activity['new_values']): ?>
                                <button class="expand-btn" onclick="toggleDetails(<?php echo $activity['id']; ?>)">
                                    Show Details
                                </button>
                                <div id="details-<?php echo $activity['id']; ?>" style="display: none;">
                                    <?php if ($activity['old_values']): ?>
                                        <div class="activity-details" style="margin-top: 0.5rem;">Old Values:</div>
                                        <div class="json-data"><?php echo htmlspecialchars($activity['old_values']); ?></div>
                                    <?php endif; ?>
                                    <?php if ($activity['new_values']): ?>
                                        <div class="activity-details" style="margin-top: 0.5rem;">New Values:</div>
                                        <div class="json-data"><?php echo htmlspecialchars($activity['new_values']); ?></div>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <div>
                            <span class="severity-badge severity-<?php echo $activity['severity']; ?>">
                                <?php echo ucfirst($activity['severity']); ?>
                            </span>
                        </div>
                        
                        <div>
                            <span class="time-category time-<?php echo $activity['time_category']; ?>">
                                <?php 
                                switch($activity['time_category']) {
                                    case 'just_now': echo 'Just now'; break;
                                    case 'today': echo 'Today'; break;
                                    case 'this_week': echo 'This week'; break;
                                    default: echo 'Older'; break;
                                }
                                ?>
                            </span>
                        </div>
                        
                        <div>
                            <div class="activity-details">
                                <?php echo date('M j, Y', strtotime($activity['created_at'])); ?>
                            </div>
                            <div class="activity-details">
                                <?php echo date('g:i A', strtotime($activity['created_at'])); ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
        
        <?php if (count($activities) >= $filters['limit']): ?>
            <div style="text-align: center; margin-top: 1rem; color: #64748b;">
                Showing latest <?php echo $filters['limit']; ?> records. Use filters to narrow down results.
            </div>
        <?php endif; ?>
    </div>
    
    <script>
        function toggleDetails(activityId) {
            const details = document.getElementById('details-' + activityId);
            const button = details.previousElementSibling;
            
            if (details.style.display === 'none') {
                details.style.display = 'block';
                button.textContent = 'Hide Details';
            } else {
                details.style.display = 'none';
                button.textContent = 'Show Details';
            }
        }
    </script>
</body>
</html>
