<?php
// email_logs.php - View sent email logs
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once 'php/adminconfig.php';

// Pagination settings
$records_per_page = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $records_per_page;

// Get total count
$count_stmt = $conn->prepare("SELECT COUNT(*) FROM email_logs");
$count_stmt->execute();
$total_records = $count_stmt->fetchColumn();
$total_pages = ceil($total_records / $records_per_page);

// Get email logs
$stmt = $conn->prepare("
    SELECT el.*, a.username as admin_name
    FROM email_logs el 
    LEFT JOIN admins a ON el.admin_id = a.id 
    ORDER BY el.sent_at DESC 
    LIMIT ? OFFSET ?
");
$stmt->bindParam(1, $records_per_page, PDO::PARAM_INT);
$stmt->bindParam(2, $offset, PDO::PARAM_INT);
$stmt->execute();
$logs = $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>Email Campaign Logs - Tradewave Admin</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        
        .tw_logs_container {
            max-width: 1400px;
            margin: 0 auto;
        }

        .tw_logs_header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 15px;
            margin-bottom: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .tw_back_btn {
            background: rgba(255,255,255,0.2);
            color: white;
            padding: 10px 20px;
            border: 2px solid rgba(255,255,255,0.3);
            border-radius: 8px;
            text-decoration: none;
            transition: all 0.3s ease;
        }

        .tw_back_btn:hover {
            background: rgba(255,255,255,0.3);
            transform: translateY(-2px);
        }

        .tw_logs_table_wrapper {
            background: white;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 5px 20px rgba(0,0,0,0.08);
            margin-bottom: 30px;
        }

        .tw_logs_table {
            width: 100%;
            border-collapse: collapse;
        }

        .tw_logs_table th {
            background: #f8f9fa;
            padding: 20px 15px;
            text-align: left;
            font-weight: 600;
            color: #2d3748;
            border-bottom: 1px solid #e2e8f0;
            font-size: 14px;
        }

        .tw_logs_table td {
            padding: 15px;
            border-bottom: 1px solid #f1f3f4;
            font-size: 14px;
            vertical-align: top;
        }

        .tw_logs_table tr:hover {
            background-color: #f8f9ff;
        }

        .tw_status_badge {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            text-transform: uppercase;
        }

        .tw_status_success {
            background: #d4edda;
            color: #155724;
        }

        .tw_status_partial {
            background: #fff3cd;
            color: #856404;
        }

        .tw_status_failed {
            background: #f8d7da;
            color: #721c24;
        }

        .tw_email_type {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            padding: 4px 10px;
            border-radius: 15px;
            font-size: 12px;
            font-weight: 600;
        }

        .tw_recipient_count {
            font-weight: 600;
            color: #4a5568;
        }

        .tw_timestamp {
            color: #718096;
            font-size: 12px;
        }

        .tw_details_btn {
            background: #4299e1;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.3s ease;
        }

        .tw_details_btn:hover {
            background: #3182ce;
        }

        .tw_pagination {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin-top: 30px;
        }

        .tw_page_btn {
            padding: 10px 15px;
            border: 1px solid #e2e8f0;
            background: white;
            color: #4a5568;
            text-decoration: none;
            border-radius: 6px;
            transition: all 0.3s ease;
        }

        .tw_page_btn:hover {
            background: #f7fafc;
            border-color: #cbd5e0;
        }

        .tw_page_btn.tw_active {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }

        .tw_modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.7);
            z-index: 1000;
        }

        .tw_modal_content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            width: 90%;
            max-width: 800px;
            max-height: 90vh;
            overflow-y: auto;
            border-radius: 15px;
            padding: 30px;
        }

        .tw_modal_header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #e2e8f0;
        }

        .tw_close_modal {
            background: #f56565;
            color: white;
            border: none;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            cursor: pointer;
            font-size: 18px;
        }

        .tw_detail_section {
            margin-bottom: 20px;
        }

        .tw_detail_label {
            font-weight: 600;
            color: #2d3748;
            margin-bottom: 5px;
        }

        .tw_detail_value {
            color: #4a5568;
            background: #f7fafc;
            padding: 10px;
            border-radius: 6px;
            border-left: 4px solid #667eea;
        }

        .tw_recipients_list {
            max-height: 200px;
            overflow-y: auto;
            background: #f7fafc;
            padding: 15px;
            border-radius: 6px;
        }

        .tw_no_data {
            text-align: center;
            padding: 50px;
            color: #718096;
        }

        @media (max-width: 768px) {
            .tw_logs_table {
                font-size: 12px;
            }
            
            .tw_logs_table th,
            .tw_logs_table td {
                padding: 10px 8px;
            }
            
            .tw_modal_content {
                width: 95%;
                padding: 20px;
            }
        }
    </style>
</head>
<body>
    <div class="tw_logs_container">
        

        <?php if (empty($logs)): ?>
            <div class="tw_logs_table_wrapper">
                <div class="tw_no_data">
                    <h3>📭 No Email Campaigns Found</h3>
                    <p>Start creating email campaigns to see them here.</p>
                </div>
            </div>
        <?php else: ?>
            <div class="tw_logs_table_wrapper">
                <table class="tw_logs_table">
                    <thead>
                        <tr>
                            <th>Campaign ID</th>
                            <th>Email Type</th>
                            <th>Recipients</th>
                            <th>Success Rate</th>
                            <th>Status</th>
                            <th>Sent Date</th>
                            <th>Admin</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($logs as $log): ?>
                            <?php
                            $user_ids = json_decode($log['user_ids'], true);
                            $failed_emails = json_decode($log['failed_emails'], true) ?: [];
                            $total_recipients = count($user_ids);
                            $success_rate = $total_recipients > 0 ? round(($log['success_count'] / $total_recipients) * 100, 1) : 0;
                            
                            // Determine status
                            if ($log['success_count'] == $total_recipients) {
                                $status = 'success';
                                $status_text = 'Complete';
                            } elseif ($log['success_count'] > 0) {
                                $status = 'partial';
                                $status_text = 'Partial';
                            } else {
                                $status = 'failed';
                                $status_text = 'Failed';
                            }
                            ?>
                            <tr>
                                <td><strong>#<?= $log['id'] ?></strong></td>
                                <td><span class="tw_email_type"><?= htmlspecialchars($log['email_type']) ?></span></td>
                                <td><span class="tw_recipient_count"><?= $total_recipients ?></span> recipients</td>
                                <td>
                                    <strong><?= $log['success_count'] ?>/<?= $total_recipients ?></strong>
                                    <br><small>(<?= $success_rate ?>%)</small>
                                </td>
                                <td><span class="tw_status_badge tw_status_<?= $status ?>"><?= $status_text ?></span></td>
                                <td>
                                    <div><?= date('M d, Y', strtotime($log['sent_at'])) ?></div>
                                    <div class="tw_timestamp"><?= date('H:i:s', strtotime($log['sent_at'])) ?></div>
                                </td>
                                <td><?= htmlspecialchars($log['admin_name'] ?: 'Unknown') ?></td>
                                <td>
                                    <button class="tw_details_btn" onclick="tw_showLogDetails(<?= htmlspecialchars(json_encode($log)) ?>)">
                                        View Details
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
                <div class="tw_pagination">
                    <?php if ($page > 1): ?>
                        <a href="?page=<?= $page - 1 ?>" class="tw_page_btn">← Previous</a>
                    <?php endif; ?>

                    <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                        <a href="?page=<?= $i ?>" class="tw_page_btn <?= $i == $page ? 'tw_active' : '' ?>">
                            <?= $i ?>
                        </a>
                    <?php endfor; ?>

                    <?php if ($page < $total_pages): ?>
                        <a href="?page=<?= $page + 1 ?>" class="tw_page_btn">Next →</a>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>

    <!-- Modal for log details -->
    <div id="tw_log_modal" class="tw_modal">
        <div class="tw_modal_content">
            <div class="tw_modal_header">
                <h3>📧 Email Campaign Details</h3>
                <button class="tw_close_modal" onclick="tw_closeModal()">&times;</button>
            </div>
            <div id="tw_modal_body">
                <!-- Content will be populated by JavaScript -->
            </div>
        </div>
    </div>

    <script>
        function tw_showLogDetails(log) {
    const modal = document.getElementById('tw_log_modal');
    const modalBody = document.getElementById('tw_modal_body');
    
    const userIds = JSON.parse(log.user_ids || '[]');
    const failedEmails = JSON.parse(log.failed_emails || '[]');
    const tableData = log.table_data ? JSON.parse(log.table_data) : null;
    
    let logoSection = '';
    if (log.logo_1 || log.logo_2 || log.logo_3) {
        logoSection = '<div class="tw_detail_section"><div class="tw_detail_label">🎨 Brand Logos:</div><div class="tw_detail_value">';
        if (log.logo_1) logoSection += `<img src="uploads/${log.logo_1}" style="width: 40px; height: 40px; border-radius: 50%; margin: 5px;" alt="Logo 1">`;
        if (log.logo_2) logoSection += `<img src="uploads/${log.logo_2}" style="width: 40px; height: 40px; border-radius: 50%; margin: 5px;" alt="Logo 2">`;
        if (log.logo_3) logoSection += `<img src="uploads/${log.logo_3}" style="width: 40px; height: 40px; border-radius: 50%; margin: 5px;" alt="Logo 3">`;
        logoSection += '</div></div>';
    }
    
    let priceSection = '';
    if (log.price_amount) {
        const currency = log.price_currency === 'USD' ? '$' : 
                        (log.price_currency === 'EUR' ? '€' : 
                        (log.price_currency === 'GBP' ? '£' : 
                        (log.price_currency === 'NGN' ? '₦' : '$')));
        priceSection = `<div class="tw_detail_section">
            <div class="tw_detail_label">💰 Price Information:</div>
            <div class="tw_detail_value">
                <strong>${currency}${parseFloat(log.price_amount).toFixed(2)}</strong> 
                (Style: ${log.price_style || 'pending'})
            </div>
        </div>`;
    }
    
    let attachmentSection = '';
    if (log.attachment_file) {
        attachmentSection = `<div class="tw_detail_section">
            <div class="tw_detail_label">📎 Attachment:</div>
            <div class="tw_detail_value">
                <a href="uploads/${log.attachment_file}" target="_blank">${log.attachment_file}</a>
            </div>
        </div>`;
    }
    
    let tableSection = '';
    if (tableData && tableData.headers) {
        tableSection = '<div class="tw_detail_section"><div class="tw_detail_label">📊 Data Table:</div><div class="tw_detail_value">';
        tableSection += '<table style="width: 100%; border-collapse: collapse; margin-top: 10px;">';
        tableSection += '<thead><tr>';
        tableData.headers.forEach(header => {
            tableSection += `<th style="border: 1px solid #ddd; padding: 8px; background: #f5f5f5;">${header}</th>`;
        });
        tableSection += '</tr></thead><tbody>';
        if (tableData.rows) {
            tableData.rows.forEach(row => {
                tableSection += '<tr>';
                row.forEach(cell => {
                    tableSection += `<td style="border: 1px solid #ddd; padding: 8px;">${cell}</td>`;
                });
                tableSection += '</tr>';
            });
        }
        tableSection += '</tbody></table></div></div>';
    }
    
    let failedEmailsSection = '';
    if (failedEmails.length > 0) {
        failedEmailsSection = '<div class="tw_detail_section"><div class="tw_detail_label">❌ Failed Recipients:</div><div class="tw_recipients_list">';
        failedEmails.forEach(failed => {
            failedEmailsSection += `<div style="margin: 5px 0; padding: 5px; background: #ffebee; border-radius: 4px;">
                <strong>${failed.name}</strong> - ${failed.email}
            </div>`;
        });
        failedEmailsSection += '</div></div>';
    }
    
    modalBody.innerHTML = `
        <div class="tw_detail_section">
            <div class="tw_detail_label">📧 Campaign ID:</div>
            <div class="tw_detail_value">#${log.id}</div>
        </div>
        
        <div class="tw_detail_section">
            <div class="tw_detail_label">📋 Email Title:</div>
            <div class="tw_detail_value">${log.custom_title}</div>
        </div>
        
        <div class="tw_detail_section">
            <div class="tw_detail_label">🏷️ Email Type/Subject:</div>
            <div class="tw_detail_value">${log.email_type}</div>
        </div>
        
        ${logoSection}
        
        <div class="tw_detail_section">
            <div class="tw_detail_label">✉️ Message Content:</div>
            <div class="tw_detail_value">${log.message_body.replace(/\n/g, '<br>')}</div>
        </div>
        
        ${priceSection}
        ${attachmentSection}
        ${tableSection}
        
        <div class="tw_detail_section">
            <div class="tw_detail_label">🔗 Button Settings:</div>
            <div class="tw_detail_value">
                Know More Button: ${log.include_know_more_btn ? '✅ Enabled' : '❌ Disabled'}<br>
                Tradewave Button: ${log.include_tradewave_btn ? '✅ Enabled' : '❌ Disabled'}
            </div>
        </div>
        
        <div class="tw_detail_section">
            <div class="tw_detail_label">📊 Campaign Statistics:</div>
            <div class="tw_detail_value">
                <strong>Total Recipients:</strong> ${userIds.length}<br>
                <strong>Successful Sends:</strong> ${log.success_count}<br>
                <strong>Failed Sends:</strong> ${userIds.length - log.success_count}<br>
                <strong>Success Rate:</strong> ${userIds.length > 0 ? Math.round((log.success_count / userIds.length) * 100) : 0}%
            </div>
        </div>
        
        ${failedEmailsSection}
        
        <div class="tw_detail_section">
            <div class="tw_detail_label">📅 Sent Date:</div>
            <div class="tw_detail_value">${new Date(log.sent_at).toLocaleString()}</div>
        </div>
    `;
    
    modal.style.display = 'block';
}

function tw_closeModal() {
    document.getElementById('tw_log_modal').style.display = 'none';
}

// Close modal when clicking outside
window.onclick = function(event) {
    const modal = document.getElementById('tw_log_modal');
    if (event.target === modal) {
        tw_closeModal();
    }
}

// Close modal with Escape key
document.addEventListener('keydown', function(event) {
    if (event.key === 'Escape') {
        tw_closeModal();
    }
});
    </script>
</body>
</html>