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

// Require admin login with view permission
$auth = new AdminAuth();
$auth->requireLogin();
$auth->requirePermission('dashboard', 'view');

$currentPage = 'email_logs';

// Get filter parameters
$email_type = $_GET['email_type'] ?? '';
$status = $_GET['status'] ?? '';
$search = $_GET['search'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$page = max(1, intval($_GET['page'] ?? 1));
$per_page = 50;
$offset = ($page - 1) * $per_page;

try {
    $pdo = getDBConnection();
    
    // Build WHERE conditions
    $where_conditions = [];
    $params = [];
    
    if (!empty($email_type)) {
        $where_conditions[] = "en.email_type = ?";
        $params[] = $email_type;
    }
    
    if (!empty($status)) {
        $where_conditions[] = "en.status = ?";
        $params[] = $status;
    }
    
    if (!empty($search)) {
        $where_conditions[] = "(en.recipient_email LIKE ? OR en.recipient_name LIKE ? OR en.subject LIKE ? OR r.registration_number LIKE ?)";
        $searchParam = "%$search%";
        $params[] = $searchParam;
        $params[] = $searchParam;
        $params[] = $searchParam;
        $params[] = $searchParam;
    }
    
    if (!empty($date_from)) {
        $where_conditions[] = "DATE(en.sent_at) >= ?";
        $params[] = $date_from;
    }
    
    if (!empty($date_to)) {
        $where_conditions[] = "DATE(en.sent_at) <= ?";
        $params[] = $date_to;
    }
    
    $where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';
    
    // Get total count
    $count_query = "
        SELECT COUNT(*) 
        FROM email_notifications en
        LEFT JOIN registrations r ON en.registration_id = r.id
        $where_clause
    ";
    $count_stmt = $pdo->prepare($count_query);
    $count_stmt->execute($params);
    $total_records = $count_stmt->fetchColumn();
    $total_pages = ceil($total_records / $per_page);
    
    // Get email logs
    $query = "
        SELECT 
            en.*,
            r.registration_number,
            r.contact_full_name,
            r.university_name,
            r.payment_method,
            r.payment_status
        FROM email_notifications en
        LEFT JOIN registrations r ON en.registration_id = r.id
        $where_clause
        ORDER BY en.sent_at DESC
        LIMIT $per_page OFFSET $offset
    ";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $email_logs = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get summary statistics
    $stats_query = "
        SELECT 
            email_type,
            status,
            COUNT(*) as count
        FROM email_notifications
        GROUP BY email_type, status
        ORDER BY email_type, status
    ";
    $stats_stmt = $pdo->query($stats_query);
    $stats = $stats_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get recent failed emails
    $failed_query = "
        SELECT 
            en.*,
            r.registration_number,
            r.contact_full_name
        FROM email_notifications en
        LEFT JOIN registrations r ON en.registration_id = r.id
        WHERE en.status = 'failed'
        ORDER BY en.sent_at DESC
        LIMIT 10
    ";
    $failed_stmt = $pdo->query($failed_query);
    $failed_emails = $failed_stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (Exception $e) {
    $error = "Error loading email logs: " . $e->getMessage();
}

// Helper function to format email type
function formatEmailType($type) {
    $types = [
        'pending_registration' => 'Pending Registration',
        'registration_confirmation' => 'Registration Confirmation',
        'payment_failure' => 'Payment Failure',
        'payment_reminder_24h' => 'Payment Reminder (24h)',
        'payment_reminder_48h' => 'Payment Reminder (48h)',
        'payment_reminder_7d' => 'Payment Reminder (7d)',
        'admin_notification' => 'Admin Notification'
    ];
    return $types[$type] ?? ucfirst(str_replace('_', ' ', $type));
}

// Helper function to get status badge class
function getStatusBadgeClass($status) {
    switch ($status) {
        case 'sent': return 'status-paid';
        case 'failed': return 'status-failed';
        case 'pending': return 'status-pending';
        default: return 'status-pending';
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Email Logs - 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@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="../styles.css">
    <link rel="stylesheet" href="admin.css">
    <style>
        .email-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: white;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            padding: 20px;
            text-align: center;
        }
        
        .stat-number {
            font-size: 2rem;
            font-weight: 700;
            color: #1f2937;
            margin-bottom: 5px;
        }
        
        .stat-label {
            color: #6b7280;
            font-size: 0.875rem;
        }
        
        .email-log-row {
            border-bottom: 1px solid #f3f4f6;
        }
        
        .email-log-row:hover {
            background-color: #f9fafb;
        }
        
        .email-details {
            width: 100%;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        
        .error-indicator {
            position: relative;
            color: #dc2626;
            font-size: 0.875rem;
            margin-top: 6px;
            padding: 4px 8px;
            background-color: #fff5f5;
            border: 1px solid #fecaca;
            border-radius: 4px;
            cursor: pointer;
        }
        
        .error-icon {
            margin-left: 6px;
            cursor: help;
            vertical-align: middle;
        }
        
        /* Custom tooltip implementation */
        [data-tooltip] {
            position: relative;
            cursor: help;
        }
        
        [data-tooltip]:before,
        [data-tooltip]:after {
            visibility: hidden;
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.3s ease;
        }
        
        /* The actual tooltip */
        [data-tooltip]:after {
            content: attr(data-tooltip);
            position: absolute;
            bottom: 150%;
            left: 50%;
            margin-left: -175px;
            width: 350px;
            padding: 10px;
            background-color: #1f2937;
            color: #fff;
            border-radius: 4px;
            font-size: 0.875rem;
            line-height: 1.5;
            white-space: pre-wrap;
            word-wrap: break-word;
            z-index: 10000;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
            text-align: left;
        }
        
        /* Triangle */
        [data-tooltip]:before {
            content: "";
            position: absolute;
            bottom: 150%;
            left: 50%;
            margin-left: -5px;
            margin-bottom: -5px;
            border-width: 5px;
            border-style: solid;
            border-color: #1f2937 transparent transparent transparent;
            z-index: 10001;
        }
        
        /* Show tooltip on hover */
        [data-tooltip]:hover:before,
        [data-tooltip]:hover:after {
            visibility: visible;
            opacity: 1;
        }
        
        tr.email-log-row.failed-row td {
            background-color: #fff5f5;
        }
        
        .status-badge.status-failed {
            background: #fecaca;
            color: #dc2626;
            font-weight: 600;
        }
        
        .filter-section {
            background: white;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 30px;
        }
        
        .filter-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }
        
        .failed-emails-section {
            background: #fef2f2;
            border: 1px solid #fecaca;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 30px;
        }
        
        .failed-emails-section h3 {
            color: #dc2626;
            margin-bottom: 15px;
        }
        
        .failed-email-item {
            background: white;
            border: 1px solid #fecaca;
            border-radius: 4px;
            padding: 10px;
            margin-bottom: 10px;
            font-size: 0.875rem;
        }
        
        /* Table Styling */
        .table {
            width: 100%;
            table-layout: fixed;
            border-collapse: collapse;
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }
        
        .table thead {
            background: #f8fafc;
            border-bottom: 2px solid #e2e8f0;
        }
        
        .table th {
            padding: 12px 16px;
            text-align: left;
            font-weight: 600;
            color: #374151;
            font-size: 0.875rem;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            border-bottom: 1px solid #e5e7eb;
        }
        
        .table td {
            padding: 12px 16px;
            border-bottom: 1px solid #f3f4f6;
            vertical-align: top;
            word-break: break-word;
        }
        
        .table tbody tr:hover {
            background-color: #f9fafb;
        }
        
        .table tbody tr:last-child td {
            border-bottom: none;
        }
        
        .email-type-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 500;
            background: #e0f2fe;
            color: #0284c7;
        }
        
        .status-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 500;
            text-transform: uppercase;
            min-width: 60px;
            text-align: center;
        }
        
        .status-badge.status-sent {
            background: #dcfce7;
            color: #166534;
        }
        
        .status-badge.status-failed {
            background: #fecaca;
            color: #dc2626;
        }
        
        .status-badge.status-pending {
            background: #fef3c7;
            color: #92400e;
        }
        
        /* Responsive Table Styles */
        @media (max-width: 768px) {
            .table {
                font-size: 0.8rem;
            }
            
            .table th,
            .table td {
                padding: 8px 12px;
            }
            
            .email-details {
                max-width: 150px;
            }
            
            .table th:nth-child(4),
            .table td:nth-child(4) {
                display: none; /* Hide subject column on mobile */
            }
            
            .table th:nth-child(5),
            .table td:nth-child(5) {
                display: none; /* Hide registration column on mobile */
            }
        }
        
        /* Table Header Alignment Fix */
        .data-table {
            background: white;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            overflow: hidden;
        }
        
        .action-buttons {
            display: flex;
            flex-direction: row;
            gap: 5px;
            flex-wrap: nowrap;
            width: 100%;
            justify-content: flex-start;
        }
        
        .action-buttons .btn {
            white-space: nowrap;
            min-width: 70px;
            text-align: center;
            margin: 0;
            padding: 4px 8px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }
        
        .btn-sm {
            padding: 0.25rem 0.5rem;
            font-size: 0.75rem;
        }
        
        .table-header {
            padding: 20px;
            border-bottom: 1px solid #e5e7eb;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: #f8fafc;
        }
        
        .table-header h3 {
            margin: 0;
            color: #1f2937;
            font-size: 1.125rem;
            font-weight: 600;
        }
        
        .table-actions {
            color: #6b7280;
            font-size: 0.875rem;
        }
    </style>
</head>
<body>
    <?php include 'includes/admin_nav.php'; ?>

    <div class="admin-content">
        <div class="page-header">
            <h1>Email Logs</h1>
            <p>Monitor all email notifications sent by the system</p>
        </div>

        <?php if (isset($error)): ?>
            <div class="alert alert-error mb-4">
                <?php echo htmlspecialchars($error); ?>
            </div>
        <?php endif; ?>

        <!-- Email Statistics -->
        <div class="email-stats">
            <?php
            $stat_totals = [];
            foreach ($stats as $stat) {
                $key = $stat['status'];
                $stat_totals[$key] = ($stat_totals[$key] ?? 0) + $stat['count'];
            }
            ?>
            <div class="stat-card">
                <div class="stat-number"><?php echo $stat_totals['sent'] ?? 0; ?></div>
                <div class="stat-label">Emails Sent</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo $stat_totals['failed'] ?? 0; ?></div>
                <div class="stat-label">Failed Emails</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo $stat_totals['pending'] ?? 0; ?></div>
                <div class="stat-label">Pending Emails</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo array_sum($stat_totals); ?></div>
                <div class="stat-label">Total Emails</div>
            </div>
        </div>

        <!-- Recent Failed Emails Alert -->
        <?php if (!empty($failed_emails)): ?>
        <div class="failed-emails-section">
            <h3>⚠️ Recent Failed Emails</h3>
            <?php foreach (array_slice($failed_emails, 0, 5) as $failed): ?>
            <div class="failed-email-item">
                <strong><?php echo htmlspecialchars($failed['subject']); ?></strong><br>
                To: <?php echo htmlspecialchars($failed['recipient_email']); ?> | 
                Type: <?php echo formatEmailType($failed['email_type']); ?> | 
                Time: <?php echo date('M j, Y H:i', strtotime($failed['sent_at'])); ?>
                <?php if ($failed['error_message']): ?>
                <br><span class="error-message">Error: <?php echo htmlspecialchars($failed['error_message']); ?></span>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <!-- Filters -->
        <div class="filter-section">
            <h3>Filter Email Logs</h3>
            <form method="GET" class="filter-form">
                <div class="filter-grid">
                    <div class="form-group">
                        <label for="search" class="form-label">Search</label>
                        <input type="text" id="search" name="search" class="form-control" 
                               placeholder="Email, name, subject, reg#" value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                    
                    <div class="form-group">
                        <label for="email_type" class="form-label">Email Type</label>
                        <select id="email_type" name="email_type" class="form-control">
                            <option value="">All Types</option>
                            <option value="pending_registration" <?php echo $email_type === 'pending_registration' ? 'selected' : ''; ?>>Pending Registration</option>
                            <option value="registration_confirmation" <?php echo $email_type === 'registration_confirmation' ? 'selected' : ''; ?>>Registration Confirmation</option>
                            <option value="payment_failure" <?php echo $email_type === 'payment_failure' ? 'selected' : ''; ?>>Payment Failure</option>
                            <option value="payment_reminder_24h" <?php echo $email_type === 'payment_reminder_24h' ? 'selected' : ''; ?>>Payment Reminder (24h)</option>
                            <option value="payment_reminder_48h" <?php echo $email_type === 'payment_reminder_48h' ? 'selected' : ''; ?>>Payment Reminder (48h)</option>
                            <option value="payment_reminder_7d" <?php echo $email_type === 'payment_reminder_7d' ? 'selected' : ''; ?>>Payment Reminder (7d)</option>
                            <option value="admin_notification" <?php echo $email_type === 'admin_notification' ? 'selected' : ''; ?>>Admin Notification</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="status" class="form-label">Status</label>
                        <select id="status" name="status" class="form-control">
                            <option value="">All Statuses</option>
                            <option value="sent" <?php echo $status === 'sent' ? 'selected' : ''; ?>>Sent</option>
                            <option value="failed" <?php echo $status === 'failed' ? 'selected' : ''; ?>>Failed</option>
                            <option value="pending" <?php echo $status === 'pending' ? 'selected' : ''; ?>>Pending</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="date_from" class="form-label">Date From</label>
                        <input type="date" id="date_from" name="date_from" class="form-control" 
                               value="<?php echo htmlspecialchars($date_from); ?>">
                    </div>
                    
                    <div class="form-group">
                        <label for="date_to" class="form-label">Date To</label>
                        <input type="date" id="date_to" name="date_to" class="form-control" 
                               value="<?php echo htmlspecialchars($date_to); ?>">
                    </div>
                </div>
                
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-search"></i> Filter
                    </button>
                    <a href="email_logs.php" class="btn btn-secondary">
                        <i class="fas fa-undo"></i> Reset
                    </a>
                </div>
            </form>
        </div>

        <!-- Email Logs Table -->
        <div class="data-table">
            <div class="table-header">
                <h3>Email Logs (<?php echo number_format($total_records); ?> total)</h3>
                <div class="table-actions">
                    <span class="text-sm">
                        Page <?php echo $page; ?> of <?php echo $total_pages; ?>
                    </span>
                </div>
            </div>

            <?php if (empty($email_logs)): ?>
                <div class="empty-state">
                    <p>No email logs found matching your criteria.</p>
                </div>
            <?php else: ?>
                <table class="table">
                    <thead>
                        <tr>
                            <th style="width: 10%;">Date/Time</th>
                            <th style="width: 12%;">Type</th>
                            <th style="width: 15%;">Recipient</th>
                            <th style="width: 20%;">Subject</th>
                            <th style="width: 15%;">Registration</th>
                            <th style="width: 15%;">Status</th>
                            <th style="width: 13%;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($email_logs as $log): ?>
                        <tr class="email-log-row <?php echo $log['status'] === 'failed' ? 'failed-row' : ''; ?>">
                            <td>
                                <div class="text-sm">
                                    <?php echo date('M j, Y', strtotime($log['sent_at'])); ?><br>
                                    <span class="text-xs text-slate-600"><?php echo date('H:i:s', strtotime($log['sent_at'])); ?></span>
                                </div>
                            </td>
                            <td>
                                <span class="email-type-badge">
                                    <?php echo formatEmailType($log['email_type']); ?>
                                </span>
                            </td>
                            <td>
                                <div class="email-details">
                                    <div class="text-sm font-medium"><?php echo htmlspecialchars($log['recipient_name'] ?: 'N/A'); ?></div>
                                    <div class="text-xs text-slate-600"><?php echo htmlspecialchars($log['recipient_email']); ?></div>
                                </div>
                            </td>
                            <td>
                                <div class="email-details" title="<?php echo htmlspecialchars($log['subject']); ?>">
                                    <?php echo htmlspecialchars($log['subject']); ?>
                                </div>
                            </td>
                            <td>
                                <?php if ($log['registration_number']): ?>
                                    <a href="registration-details.php?id=<?php echo urlencode($log['registration_number']); ?>" 
                                       class="link link-strong">
                                        <?php echo htmlspecialchars($log['registration_number']); ?>
                                    </a>
                                    <div class="text-xs text-slate-600">
                                        <?php echo htmlspecialchars($log['contact_full_name'] ?: 'N/A'); ?>
                                    </div>
                                <?php else: ?>
                                    <span class="text-slate-500">N/A</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <span class="status-badge <?php echo getStatusBadgeClass($log['status']); ?>">
                                    <?php echo ucfirst($log['status']); ?>
                                </span>
                                <?php if ($log['status'] === 'failed' && $log['error_message']): ?>
                                    <span class="error-icon" data-tooltip="<?php echo htmlspecialchars($log['error_message']); ?>"><i class="fas fa-exclamation-triangle"></i></span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="action-buttons">
                                    <button class="btn btn-sm btn-secondary" onclick="viewEmailDetails(<?php echo $log['id']; ?>)" title="View email details"><i class="fas fa-eye"></i> View</button>
                                    <?php if ($log['registration_id']): ?>
                                        <button class="btn btn-sm btn-primary" onclick="resendEmail(<?php echo $log['id']; ?>, '<?php echo $log['email_type']; ?>')" title="Resend this email"><i class="fas fa-redo"></i> Resend</button>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>

                <!-- Pagination -->
                <?php if ($total_pages > 1): ?>
                <div class="pagination">
                    <?php if ($page > 1): ?>
                        <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>" class="btn btn-secondary">
                            ← Previous
                        </a>
                    <?php endif; ?>
                    
                    <span class="pagination-info">
                        Page <?php echo $page; ?> of <?php echo $total_pages; ?>
                    </span>
                    
                    <?php if ($page < $total_pages): ?>
                        <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>" class="btn btn-secondary">
                            Next →
                        </a>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>

    <script>
        function viewEmailDetails(emailId) {
            // Open modal or new page with email details
            window.open('email_details.php?id=' + emailId, '_blank', 'width=800,height=600');
        }
        
        function resendEmail(emailId, emailType) {
            const emailTypeNames = {
                'pending_registration': 'Pending Registration Email',
                'registration_confirmation': 'Registration Confirmation Email',
                'payment_failure': 'Payment Failure Email',
                'payment_reminder_24h': '24-Hour Payment Reminder',
                'payment_reminder_48h': '48-Hour Payment Reminder',
                'payment_reminder_7d': '7-Day Payment Reminder',
                'admin_notification': 'Admin Notification Email'
            };
            
            const emailTypeName = emailTypeNames[emailType] || emailType;
            
            if (confirm(`Are you sure you want to resend this ${emailTypeName}?\n\nThis will generate a fresh email using current data and send it to the same recipient.`)) {
                const button = event.target;
                const originalText = button.innerHTML;
                button.innerHTML = '<i class="fas fa-clock"></i> Sending...';
                button.disabled = true;
                
                fetch('resend_email.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        email_id: emailId
                    })
                })
                .then(response => response.json())
                .then(data => {
                    button.innerHTML = originalText;
                    button.disabled = false;
                    
                    if (data.success) {
                        alert('Email resent successfully!');
                        // Refresh the page to show the new email log entry
                        location.reload();
                    } else {
                        alert('Failed to resend email: ' + (data.error || 'Unknown error'));
                    }
                })
                .catch(error => {
                    button.innerHTML = originalText;
                    button.disabled = false;
                    alert('Error: ' + error.message);
                });
            }
        }
    </script>
</body>
</html>
