<?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');

$email_id = $_GET['id'] ?? '';

if (empty($email_id)) {
    http_response_code(400);
    die('Email ID is required');
}

try {
    $pdo = getDBConnection();
    
    // Get email details with registration info
    $stmt = $pdo->prepare("
        SELECT 
            en.*,
            r.registration_number,
            r.contact_full_name,
            r.contact_email as reg_email,
            r.university_name,
            r.payment_method,
            r.payment_status,
            r.total_amount
        FROM email_notifications en
        LEFT JOIN registrations r ON en.registration_id = r.id
        WHERE en.id = ?
    ");
    $stmt->execute([$email_id]);
    $email = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$email) {
        http_response_code(404);
        die('Email not found');
    }
    
} catch (Exception $e) {
    http_response_code(500);
    die('Error loading email details: ' . $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));
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Email Details - 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>
        body {
            font-family: 'Poppins', sans-serif;
            background: #f9fafb;
            margin: 0;
            padding: 20px;
        }
        
        .email-details-container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 8px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }
        
        .email-header {
            background: #2563eb;
            color: white;
            padding: 20px;
            border-radius: 8px 8px 0 0;
        }
        
        .email-content {
            padding: 20px;
        }
        
        .detail-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .detail-section {
            background: #f9fafb;
            border: 1px solid #e5e7eb;
            border-radius: 6px;
            padding: 15px;
        }
        
        .detail-section h4 {
            margin: 0 0 15px 0;
            color: #374151;
            font-size: 1rem;
            font-weight: 600;
        }
        
        .detail-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            font-size: 0.875rem;
        }
        
        .detail-label {
            font-weight: 500;
            color: #6b7280;
        }
        
        .detail-value {
            color: #374151;
            font-weight: 400;
        }
        
        .status-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 500;
        }
        
        .status-sent { background: #d1fae5; color: #059669; }
        .status-failed { background: #fee2e2; color: #dc2626; }
        .status-pending { background: #fef3c7; color: #d97706; }
        
        .email-type-badge {
            background: #e0f2fe;
            color: #0284c7;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 500;
        }
        
        .error-section {
            background: #fef2f2;
            border: 1px solid #fecaca;
            border-radius: 6px;
            padding: 15px;
            margin-bottom: 20px;
        }
        
        .error-section h4 {
            color: #dc2626;
            margin: 0 0 10px 0;
        }
        
        .error-message {
            color: #7f1d1d;
            font-family: monospace;
            font-size: 0.875rem;
            background: white;
            padding: 10px;
            border-radius: 4px;
            border: 1px solid #fecaca;
        }
        
        .actions {
            text-align: center;
            padding: 20px;
            border-top: 1px solid #e5e7eb;
        }
        
        .btn {
            display: inline-block;
            padding: 8px 16px;
            border-radius: 6px;
            text-decoration: none;
            font-weight: 500;
            font-size: 0.875rem;
            margin: 0 5px;
            cursor: pointer;
            border: none;
        }
        
        .btn-primary {
            background: #2563eb;
            color: white;
        }
        
        .btn-secondary {
            background: #6b7280;
            color: white;
        }
        
        .btn-warning {
            background: #f59e0b;
            color: white;
        }
        
        .btn:hover {
            opacity: 0.9;
        }
    </style>
</head>
<body>
    <div class="email-details-container">
        <div class="email-header">
            <h2>📧 Email Details</h2>
            <p style="margin: 5px 0 0 0; opacity: 0.9;">
                Sent on <?php echo date('F j, Y \a\t g:i A', strtotime($email['sent_at'])); ?>
            </p>
        </div>
        
        <div class="email-content">
            <!-- Email Information -->
            <div class="detail-grid">
                <div class="detail-section">
                    <h4>📨 Email Information</h4>
                    <div class="detail-row">
                        <span class="detail-label">Type:</span>
                        <span class="email-type-badge"><?php echo formatEmailType($email['email_type']); ?></span>
                    </div>
                    <div class="detail-row">
                        <span class="detail-label">Status:</span>
                        <span class="status-badge status-<?php echo $email['status']; ?>">
                            <?php echo ucfirst($email['status']); ?>
                        </span>
                    </div>
                    <div class="detail-row">
                        <span class="detail-label">Subject:</span>
                        <span class="detail-value"><?php echo htmlspecialchars($email['subject']); ?></span>
                    </div>
                    <div class="detail-row">
                        <span class="detail-label">Sent At:</span>
                        <span class="detail-value"><?php echo date('M j, Y H:i:s', strtotime($email['sent_at'])); ?></span>
                    </div>
                    <?php if ($email['brevo_message_id']): ?>
                    <div class="detail-row">
                        <span class="detail-label">Message ID:</span>
                        <span class="detail-value"><?php echo htmlspecialchars($email['brevo_message_id']); ?></span>
                    </div>
                    <?php endif; ?>
                </div>
                
                <div class="detail-section">
                    <h4>👤 Recipient Information</h4>
                    <div class="detail-row">
                        <span class="detail-label">Name:</span>
                        <span class="detail-value"><?php echo htmlspecialchars($email['recipient_name'] ?: 'N/A'); ?></span>
                    </div>
                    <div class="detail-row">
                        <span class="detail-label">Email:</span>
                        <span class="detail-value"><?php echo htmlspecialchars($email['recipient_email']); ?></span>
                    </div>
                </div>
            </div>
            
            <!-- Registration Information (if available) -->
            <?php if ($email['registration_number']): ?>
            <div class="detail-section" style="margin-bottom: 20px;">
                <h4>📋 Related Registration</h4>
                <div class="detail-grid" style="margin-bottom: 0;">
                    <div>
                        <div class="detail-row">
                            <span class="detail-label">Registration #:</span>
                            <span class="detail-value">
                                <a href="registration-details.php?id=<?php echo urlencode($email['registration_number']); ?>" 
                                   target="_blank" style="color: #2563eb; text-decoration: none;">
                                    <?php echo htmlspecialchars($email['registration_number']); ?>
                                </a>
                            </span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">Contact Name:</span>
                            <span class="detail-value"><?php echo htmlspecialchars($email['contact_full_name'] ?: 'N/A'); ?></span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">University:</span>
                            <span class="detail-value"><?php echo htmlspecialchars($email['university_name'] ?: 'N/A'); ?></span>
                        </div>
                    </div>
                    <div>
                        <div class="detail-row">
                            <span class="detail-label">Payment Method:</span>
                            <span class="detail-value">
                                <?php echo $email['payment_method'] === 'gateway' ? '💳 Online Payment' : '🏦 Bank Transfer'; ?>
                            </span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">Payment Status:</span>
                            <span class="status-badge status-<?php echo $email['payment_status']; ?>">
                                <?php echo ucfirst($email['payment_status']); ?>
                            </span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">Amount:</span>
                            <span class="detail-value">USD $<?php echo number_format($email['total_amount'], 2); ?></span>
                        </div>
                    </div>
                </div>
            </div>
            <?php endif; ?>
            
            <!-- Error Information (if failed) -->
            <?php if ($email['status'] === 'failed' && $email['error_message']): ?>
            <div class="error-section">
                <h4>❌ Error Information</h4>
                <div class="error-message">
                    <?php echo htmlspecialchars($email['error_message']); ?>
                </div>
            </div>
            <?php endif; ?>
        </div>
        
        <div class="actions">
            <button onclick="window.close()" class="btn btn-secondary">
                ✕ Close
            </button>
            
            <?php if ($email['status'] === 'failed' && $email['registration_id']): ?>
            <button onclick="resendEmail(<?php echo $email['id']; ?>)" class="btn btn-warning">
                🔄 Retry Send
            </button>
            <?php endif; ?>
            
            <?php if ($email['registration_number']): ?>
            <a href="registration-details.php?id=<?php echo urlencode($email['registration_number']); ?>" 
               target="_blank" class="btn btn-primary">
                📋 View Registration
            </a>
            <?php endif; ?>
        </div>
    </div>

    <script>
        function resendEmail(emailId) {
            if (confirm('Are you sure you want to retry sending this email?')) {
                fetch('email_actions.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        action: 'resend',
                        email_id: emailId
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('Email resent successfully!');
                        if (window.opener) {
                            window.opener.location.reload();
                        }
                        window.close();
                    } else {
                        alert('Failed to resend email: ' + data.error);
                    }
                })
                .catch(error => {
                    alert('Error: ' + error);
                });
            }
        }
    </script>
</body>
</html>
