<?php
require_once 'auth_rbac.php';
require_once '../db_config.php';
require_once 'RegistrationLogger.php';

// Require admin login with view permission
requirePermission('registrations', 'view');

$currentPage = 'registrations';

// Get filter parameters
$registrationIdParam = $_GET['registration_id'] ?? '';
$activityType = $_GET['activity_type'] ?? '';
$severity = $_GET['severity'] ?? '';
$dateFrom = $_GET['date_from'] ?? '';
$dateTo = $_GET['date_to'] ?? '';
$limit = min((int)($_GET['limit'] ?? 50), 200); // Max 200 records

$numericRegistrationId = null;
$registration = null;

try {
    $pdo = getDBConnection();
    $logger = new RegistrationLogger($pdo, $_SESSION['admin_user'] ?? null);

    // If a registration identifier is provided, find its numeric ID
    if ($registrationIdParam) {
        if (!is_numeric($registrationIdParam)) {
            // It's a registration number, so fetch the numeric ID and details
            $stmt = $pdo->prepare("SELECT id, registration_number, contact_full_name, contact_email, payment_status, total_amount FROM registrations WHERE registration_number = ?");
            $stmt->execute([$registrationIdParam]);
            $registration = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($registration) {
                $numericRegistrationId = $registration['id'];
            }
        } else {
            // It's a numeric ID, fetch details
            $numericRegistrationId = $registrationIdParam;
            $stmt = $pdo->prepare("SELECT id, registration_number, contact_full_name, contact_email, payment_status, total_amount FROM registrations WHERE id = ?");
            $stmt->execute([$numericRegistrationId]);
            $registration = $stmt->fetch(PDO::FETCH_ASSOC);
        }
    }

    // Build filters
    $filters = [];
    if ($numericRegistrationId) $filters['registration_id'] = $numericRegistrationId;
    if ($activityType) $filters['activity_type'] = $activityType;
    if ($severity) $filters['severity'] = $severity;
    if ($dateFrom) $filters['date_from'] = $dateFrom . ' 00:00:00';
    if ($dateTo) $filters['date_to'] = $dateTo . ' 23:59:59';

    // Get activities
    $activities = $logger->getRecentActivities($limit, $filters);

    // Get activity statistics
    $stats = $logger->getActivityStats($numericRegistrationId);  
} catch (Exception $e) {
    $error = "Error loading activity log: " . $e->getMessage();
}

// Get unique activity types for filter dropdown
$activityTypes = [
    'payment_status_update' => 'Payment Status Update',
    'stock_confirmation' => 'Stock Confirmation',
    'contact_update' => 'Contact Update',
    'admin_notes_update' => 'Admin Notes Update',
    'email_sent' => 'Email Sent',
    'email_resent' => 'Email Resent',
    'email_failure' => 'Email Failure',
    'invoice_generation' => 'Invoice Generation',
    'data_export' => 'Data Export',
    'delegate_update' => 'Delegate Update',
    'bulk_operation' => 'Bulk Operation',
    'system_event' => 'System Event'
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Registration Activity Log - XChange Admin</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700;800;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="../styles.css">
    <link rel="stylesheet" href="admin.css">
    <style>
        .activity-log-container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 0 20px 60px 20px;
        }
        
        .filters-card {
            background: white;
            padding: 24px;
            border-radius: 12px;
            box-shadow: var(--shadow);
            margin-bottom: 24px;
        }
        
        .filters-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 16px;
            margin-bottom: 20px;
        }
        
        .filter-group {
            display: flex;
            flex-direction: column;
        }
        
        .filter-group label {
            font-weight: 600;
            color: var(--slate-700);
            margin-bottom: 6px;
            font-size: 14px;
        }
        
        .filter-group input,
        .filter-group select {
            padding: 8px 12px;
            border: 1px solid var(--slate-300);
            border-radius: 6px;
            font-size: 14px;
        }
        
        .filter-actions {
            display: flex;
            gap: 12px;
            justify-content: flex-end;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 16px;
            margin-bottom: 24px;
        }
        
        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: var(--shadow);
            text-align: center;
        }
        
        .stat-number {
            font-size: 2rem;
            font-weight: 700;
            color: var(--indigo-600);
            margin-bottom: 8px;
        }
        
        .stat-label {
            color: var(--slate-600);
            font-size: 14px;
            font-weight: 500;
        }
        
        .activities-card {
            background: white;
            border-radius: 12px;
            box-shadow: var(--shadow);
            overflow: hidden;
        }
        
        .activities-header {
            padding: 24px;
            border-bottom: 1px solid var(--slate-200);
            background: var(--slate-50);
        }
        
        .activity-item {
            padding: 20px 24px;
            border-bottom: 1px solid var(--slate-100);
            display: flex;
            align-items: flex-start;
            gap: 16px;
            transition: background-color 0.2s;
        }
        
        .activity-item:hover {
            background: var(--slate-50);
        }
        
        .activity-item:last-child {
            border-bottom: none;
        }
        
        .activity-icon {
            font-size: 24px;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
        }
        
        .activity-content {
            flex: 1;
            min-width: 0;
        }
        
        .activity-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 8px;
            gap: 16px;
        }
        
        .activity-description {
            font-weight: 600;
            color: var(--slate-800);
            line-height: 1.4;
        }
        
        .activity-meta {
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 13px;
            color: var(--slate-500);
            flex-wrap: wrap;
        }
        
        .activity-time {
            font-weight: 500;
        }
        
        .severity-badge {
            padding: 3px 8px;
            border-radius: 4px;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .severity-low {
            background: var(--green-100);
            color: var(--green-700);
        }
        
        .severity-medium {
            background: var(--yellow-100);
            color: var(--yellow-700);
        }
        
        .severity-high {
            background: var(--red-100);
            color: var(--red-700);
        }
        
        .severity-critical {
            background: var(--red-200);
            color: var(--red-800);
        }
        
        .activity-details {
            margin-top: 12px;
            padding: 12px;
            background: var(--slate-50);
            border-radius: 6px;
            font-size: 13px;
        }
        
        .activity-changes {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 12px;
            margin-top: 8px;
        }
        
        .change-section {
            padding: 8px;
            border-radius: 4px;
        }
        
        .change-old {
            background: var(--red-50);
            border-left: 3px solid var(--red-400);
        }
        
        .change-new {
            background: var(--green-50);
            border-left: 3px solid var(--green-400);
        }
        
        .change-label {
            font-weight: 600;
            font-size: 11px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-bottom: 4px;
        }
        
        .change-old .change-label {
            color: var(--red-700);
        }
        
        .change-new .change-label {
            color: var(--green-700);
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: var(--slate-500);
        }
        
        .empty-state-icon {
            font-size: 48px;
            margin-bottom: 16px;
            opacity: 0.5;
        }
        
        .registration-info {
            background: var(--indigo-50);
            border: 1px solid var(--indigo-200);
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 24px;
        }
        
        .registration-info h3 {
            margin: 0 0 16px 0;
            color: var(--indigo-800);
            font-size: 18px;
            font-weight: 600;
        }
        
        .registration-details {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 16px;
            font-size: 14px;
        }
        
        .registration-detail {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0;
            border-bottom: 1px solid var(--indigo-100);
        }
        
        .registration-detail:last-child {
            border-bottom: none;
        }
        
        .registration-detail-label {
            font-weight: 600;
            color: var(--indigo-700);
            min-width: 80px;
            flex-shrink: 0;
        }
        
        .registration-detail-value {
            color: var(--indigo-600);
            font-weight: 500;
            text-align: right;
            word-break: break-word;
        }
        
        .pagination-section {
            margin-top: 40px;
            padding-top: 32px;
            border-top: 1px solid var(--slate-200);
            text-align: center;
            margin-bottom: 20px;
        }
        
        @media (max-width: 768px) {
            .filters-grid {
                grid-template-columns: 1fr;
            }
            
            .filter-actions {
                justify-content: stretch;
            }
            
            .filter-actions .btn {
                flex: 1;
            }
            
            .activity-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 8px;
            }
            
            .activity-changes {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <?php include 'includes/admin_nav.php'; ?>

    <div class="activity-log-container">
        <div class="breadcrumb">
            <a href="dashboard.php">Dashboard</a> / 
            <a href="registrations.php">Registrations</a> / 
            Activity Log
        </div>
        
        <div class="page-header">
            <h1 class="page-title">📋 Registration Activity Log</h1>
            <div class="page-actions">
                <button onclick="exportLog()" class="btn btn-secondary">📊 Export Log</button>
                <button onclick="refreshLog()" class="btn btn-primary">🔄 Refresh</button>
            </div>
        </div>
        
        <?php if (isset($error)): ?>
            <div class="alert alert-error mb-4"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>
        
        <!-- Registration Info (if filtering by specific registration) -->
        <?php if ($registration): ?>
        <div class="registration-info">
            <h3>📄 Registration: <?php echo htmlspecialchars($registration['registration_number']); ?></h3>
            <div class="registration-details">
                <div class="registration-detail">
                    <span class="registration-detail-label">Contact:</span>
                    <span class="registration-detail-value"><?php echo htmlspecialchars($registration['contact_full_name']); ?></span>
                </div>
                <div class="registration-detail">
                    <span class="registration-detail-label">Email:</span>
                    <span class="registration-detail-value"><?php echo htmlspecialchars($registration['contact_email']); ?></span>
                </div>
                <div class="registration-detail">
                    <span class="registration-detail-label">Status:</span>
                    <span class="registration-detail-value"><?php echo ucfirst($registration['payment_status']); ?></span>
                </div>
                <div class="registration-detail">
                    <span class="registration-detail-label">Amount:</span>
                    <span class="registration-detail-value">$<?php echo number_format($registration['total_amount']); ?></span>
                </div>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- Filters -->
        <div class="filters-card">
            <h3 style="margin: 0 0 20px 0; color: var(--slate-800);">🔍 Filters</h3>
            <form method="GET" id="filtersForm">
                <div class="filters-grid">
                    <div class="filter-group">
                        <label for="registration_id">Registration ID/Number</label>
                        <input type="text" id="registration_id" name="registration_id" 
                               value="<?php echo htmlspecialchars($registrationIdParam); ?>" 
                               placeholder="Enter ID or number">
                    </div>
                    
                    <div class="filter-group">
                        <label for="activity_type">Activity Type</label>
                        <select id="activity_type" name="activity_type">
                            <option value="">All Activities</option>
                            <?php foreach ($activityTypes as $type => $label): ?>
                                <option value="<?php echo $type; ?>" <?php echo $activityType === $type ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($label); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="filter-group">
                        <label for="severity">Severity</label>
                        <select id="severity" name="severity">
                            <option value="">All Severities</option>
                            <option value="low" <?php echo $severity === 'low' ? 'selected' : ''; ?>>Low</option>
                            <option value="medium" <?php echo $severity === 'medium' ? 'selected' : ''; ?>>Medium</option>
                            <option value="high" <?php echo $severity === 'high' ? 'selected' : ''; ?>>High</option>
                            <option value="critical" <?php echo $severity === 'critical' ? 'selected' : ''; ?>>Critical</option>
                        </select>
                    </div>
                    
                    <div class="filter-group">
                        <label for="date_from">From Date</label>
                        <input type="date" id="date_from" name="date_from" value="<?php echo htmlspecialchars($dateFrom); ?>">
                    </div>
                    
                    <div class="filter-group">
                        <label for="date_to">To Date</label>
                        <input type="date" id="date_to" name="date_to" value="<?php echo htmlspecialchars($dateTo); ?>">
                    </div>
                    
                    <div class="filter-group">
                        <label for="limit">Limit</label>
                        <select id="limit" name="limit">
                            <option value="25" <?php echo $limit === 25 ? 'selected' : ''; ?>>25 records</option>
                            <option value="50" <?php echo $limit === 50 ? 'selected' : ''; ?>>50 records</option>
                            <option value="100" <?php echo $limit === 100 ? 'selected' : ''; ?>>100 records</option>
                            <option value="200" <?php echo $limit === 200 ? 'selected' : ''; ?>>200 records</option>
                        </select>
                    </div>
                </div>
                
                <div class="filter-actions">
                    <button type="button" onclick="clearFilters()" class="btn btn-secondary">Clear Filters</button>
                    <button type="submit" class="btn btn-primary">Apply Filters</button>
                </div>
            </form>
        </div>
        
        <!-- Statistics -->
        <?php if (!empty($stats)): ?>
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-number"><?php echo count($activities); ?></div>
                <div class="stat-label">Activities Shown</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo count($stats); ?></div>
                <div class="stat-label">Activity Types</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo array_sum(array_column($stats, 'count')); ?></div>
                <div class="stat-label">Total Activities (30 days)</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo $stats[0]['count'] ?? 0; ?></div>
                <div class="stat-label">Most Common: <?php echo ucwords(str_replace('_', ' ', $stats[0]['activity_type'] ?? 'N/A')); ?></div>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- Activities List -->
        <div class="activities-card">
            <div class="activities-header">
                <h3 style="margin: 0; color: var(--slate-800);">Activity Timeline</h3>
            </div>
            
            <?php if (empty($activities)): ?>
                <div class="empty-state">
                    <div class="empty-state-icon">📋</div>
                    <h4>No activities found</h4>
                    <p>Try adjusting your filters or check back later.</p>
                </div>
            <?php else: ?>
                <?php foreach ($activities as $activity): ?>
                    <div class="activity-item">
                        <div class="activity-icon" style="background: <?php echo $activity['severity_color'] ?? '#6b7280'; ?>20;">
                            <?php echo $activity['activity_icon'] ?? '🔄'; ?>
                        </div>
                        
                        <div class="activity-content">
                            <div class="activity-header">
                                <div class="activity-description">
                                    <?php echo htmlspecialchars($activity['action_description']); ?>
                                </div>
                                <span class="severity-badge severity-<?php echo $activity['severity']; ?>">
                                    <?php echo ucfirst($activity['severity']); ?>
                                </span>
                            </div>
                            
                            <div class="activity-meta">
                                <span class="activity-time">
                                    <?php echo date('M j, Y H:i:s', strtotime($activity['created_at'])); ?>
                                </span>
                                <?php if ($activity['user_name']): ?>
                                    <span>👤 <?php echo htmlspecialchars($activity['user_name']); ?></span>
                                <?php endif; ?>
                                <?php if ($activity['registration_number']): ?>
                                    <span>📄 <?php echo htmlspecialchars($activity['registration_number']); ?></span>
                                <?php endif; ?>
                                <?php if ($activity['affected_count'] > 1): ?>
                                    <span>📊 <?php echo $activity['affected_count']; ?> items</span>
                                <?php endif; ?>
                            </div>
                            
                            <?php if ($activity['old_values'] || $activity['new_values']): ?>
                                <div class="activity-details">
                                    <strong>Changes:</strong>
                                    <div class="activity-changes">
                                        <?php if ($activity['old_values']): ?>
                                            <div class="change-section change-old">
                                                <div class="change-label">Before</div>
                                                <pre style="margin: 0; font-size: 12px; white-space: pre-wrap;"><?php echo htmlspecialchars(json_encode(json_decode($activity['old_values']), JSON_PRETTY_PRINT)); ?></pre>
                                            </div>
                                        <?php endif; ?>
                                        <?php if ($activity['new_values']): ?>
                                            <div class="change-section change-new">
                                                <div class="change-label">After</div>
                                                <pre style="margin: 0; font-size: 12px; white-space: pre-wrap;"><?php echo htmlspecialchars(json_encode(json_decode($activity['new_values']), JSON_PRETTY_PRINT)); ?></pre>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
        
        <div class="pagination-section">
            <a href="registrations.php" class="btn btn-secondary">← Back to Registrations</a>
        </div>
    </div>

    <script>
        function clearFilters() {
            document.getElementById('filtersForm').reset();
            window.location.href = 'registration-activity-log.php';
        }
        
        function refreshLog() {
            window.location.reload();
        }
        
        function exportLog() {
            const params = new URLSearchParams(window.location.search);
            params.set('export', 'csv');
            window.open('?' + params.toString());
        }
        
        // Auto-refresh every 30 seconds if no filters are applied
        <?php if (empty(array_filter([$registrationId, $activityType, $severity, $dateFrom, $dateTo]))): ?>
        setInterval(function() {
            const lastActivity = document.querySelector('.activity-item');
            if (lastActivity) {
                fetch(window.location.href + '&ajax=1')
                    .then(response => response.json())
                    .then(data => {
                        if (data.hasNewActivity) {
                            const refreshBtn = document.querySelector('[onclick="refreshLog()"]');
                            if (refreshBtn) {
                                refreshBtn.style.background = '#ef4444';
                                refreshBtn.innerHTML = '🔄 New Activity - Refresh';
                            }
                        }
                    })
                    .catch(() => {});
            }
        }, 30000);
        <?php endif; ?>
    </script>
</body>
</html>
