<?php
// Email queue manager with manual sending capability
session_start();

if (!isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'admin') {
    die('Admin access required');
}

require_once 'config/db.php';

$message = '';
$alert_type = '';

// Create email queue table if it doesn't exist
$create_table_sql = "
CREATE TABLE IF NOT EXISTS email_queue (
    id INT PRIMARY KEY AUTO_INCREMENT,
    consultation_id INT,
    recipient_email VARCHAR(255) NOT NULL,
    subject VARCHAR(255) NOT NULL,
    body LONGTEXT NOT NULL,
    email_type VARCHAR(50),
    status VARCHAR(20) DEFAULT 'pending',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    sent_at TIMESTAMP NULL,
    attempts INT DEFAULT 0,
    last_attempt TIMESTAMP NULL,
    error_message TEXT
)
";
$connection->query($create_table_sql);

// Handle resend email
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'resend_email') {
        $email_id = intval($_POST['email_id']);
        
        // Get email from queue
        $stmt = $connection->prepare("SELECT recipient_email, subject, body FROM email_queue WHERE id = ?");
        $stmt->bind_param("i", $email_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $email_record = $result->fetch_assoc();
        
        if ($email_record) {
            $headers = "MIME-Version: 1.0\r\n";
            $headers .= "Content-type: text/html; charset=UTF-8\r\n";
            $headers .= "From: mohamedhalith117@gmail.com\r\n";
            $headers .= "Reply-To: mohamedhalith117@gmail.com\r\n";
            
            $sent = @mail($email_record['recipient_email'], $email_record['subject'], $email_record['body'], $headers);
            
            // Update queue status
            $update_stmt = $connection->prepare("UPDATE email_queue SET status = ?, sent_at = NOW(), attempts = attempts + 1, last_attempt = NOW() WHERE id = ?");
            $status = $sent ? 'sent' : 'failed';
            $update_stmt->bind_param("si", $status, $email_id);
            $update_stmt->execute();
            
            if ($sent) {
                $message = "✓ Email sent successfully to " . htmlspecialchars($email_record['recipient_email']);
                $alert_type = 'success';
            } else {
                $message = "✗ Email send failed - your mail server may not be configured";
                $alert_type = 'error';
            }
        }
    } elseif ($_POST['action'] === 'resend_all_pending') {
        // Resend all pending emails
        $pending_result = $connection->query("SELECT id, recipient_email, subject, body FROM email_queue WHERE status = 'pending'");
        $sent_count = 0;
        $failed_count = 0;
        
        if ($pending_result && $pending_result->num_rows > 0) {
            while ($email = $pending_result->fetch_assoc()) {
                $headers = "MIME-Version: 1.0\r\n";
                $headers .= "Content-type: text/html; charset=UTF-8\r\n";
                $headers .= "From: info@zemaraimgroups.com\r\n";
                $headers .= "Reply-To: iiidsumma@gmail.com\r\n";
                
                if (@mail($email['recipient_email'], $email['subject'], $email['body'], $headers)) {
                    $update = $connection->prepare("UPDATE email_queue SET status = 'sent', sent_at = NOW(), attempts = attempts + 1, last_attempt = NOW() WHERE id = ?");
                    $update->bind_param("i", $email['id']);
                    $update->execute();
                    $sent_count++;
                } else {
                    $update = $connection->prepare("UPDATE email_queue SET attempts = attempts + 1, last_attempt = NOW() WHERE id = ?");
                    $update->bind_param("i", $email['id']);
                    $update->execute();
                    $failed_count++;
                }
            }
        }
        
        $message = "Results: $sent_count sent, $failed_count failed";
        $alert_type = $failed_count > 0 ? 'warning' : 'success';
    }
}

// Get email statistics
$stats = [];
$stats_result = $connection->query("
    SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
        SUM(CASE WHEN status = 'sent' THEN 1 ELSE 0 END) as sent,
        SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed
    FROM email_queue
");

if ($stats_result) {
    $stats = $stats_result->fetch_assoc();
}

// Get all emails with pagination
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$per_page = 20;
$offset = ($page - 1) * $per_page;

$emails = $connection->query("
    SELECT * FROM email_queue 
    ORDER BY created_at DESC 
    LIMIT $offset, $per_page
");

$total_result = $connection->query("SELECT COUNT(*) as count FROM email_queue");
$total_count = $total_result->fetch_assoc()['count'];
$total_pages = ceil($total_count / $per_page);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Email Queue Manager - Admin</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #f5f5f5;
            padding: 20px;
            color: #333;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 30px;
        }
        
        h1 {
            color: #8b6f47;
            margin-bottom: 30px;
            border-bottom: 3px solid #d4a574;
            padding-bottom: 15px;
        }
        
        .alert {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: none;
        }
        
        .alert.show {
            display: block;
        }
        
        .alert.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .alert.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .alert.warning {
            background: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            margin-bottom: 30px;
        }
        
        .stat-box {
            background: linear-gradient(135deg, #8b6f47, #6b5738);
            color: white;
            padding: 20px;
            border-radius: 8px;
            text-align: center;
        }
        
        .stat-number {
            font-size: 32px;
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .stat-label {
            font-size: 12px;
            opacity: 0.9;
            text-transform: uppercase;
        }
        
        .controls {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        
        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
        }
        
        .btn-primary {
            background: #8b6f47;
            color: white;
        }
        
        .btn-primary:hover {
            background: #6b5738;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(139, 111, 71, 0.3);
        }
        
        .btn-success {
            background: #10b981;
            color: white;
        }
        
        .btn-success:hover {
            background: #059669;
        }
        
        .btn-sm {
            padding: 6px 12px;
            font-size: 12px;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        
        thead {
            background: #f9f7f4;
            border-bottom: 2px solid #d4a574;
        }
        
        th {
            padding: 12px;
            text-align: left;
            font-weight: 600;
            color: #8b6f47;
            text-transform: uppercase;
            font-size: 12px;
        }
        
        td {
            padding: 12px;
            border-bottom: 1px solid #e8e3dd;
        }
        
        tr:hover {
            background: #f9f7f4;
        }
        
        .status-badge {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
            display: inline-block;
        }
        
        .status-pending {
            background: #fef3c7;
            color: #92400e;
        }
        
        .status-sent {
            background: #d1fae5;
            color: #065f46;
        }
        
        .status-failed {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .pagination {
            display: flex;
            gap: 5px;
            justify-content: center;
            margin-top: 20px;
        }
        
        .pagination a, .pagination span {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            text-decoration: none;
            color: #8b6f47;
        }
        
        .pagination a:hover {
            background: #f9f7f4;
        }
        
        .pagination .active {
            background: #8b6f47;
            color: white;
        }
        
        .back-link {
            display: inline-block;
            margin-bottom: 20px;
            color: #8b6f47;
            text-decoration: none;
            font-weight: 600;
        }
        
        .back-link:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="container">
        <a href="admin-dashboard.php" class="back-link">← Back to Dashboard</a>
        
        <h1>📧 Email Queue Manager</h1>
        
        <?php if ($message): ?>
            <div class="alert show <?php echo $alert_type; ?>">
                <?php echo $message; ?>
            </div>
        <?php endif; ?>
        
        <!-- Statistics -->
        <div class="stats-grid">
            <div class="stat-box">
                <div class="stat-number"><?php echo $stats['total'] ?? 0; ?></div>
                <div class="stat-label">Total Emails</div>
            </div>
            <div class="stat-box">
                <div class="stat-number" style="color: #fef3c7;"><?php echo $stats['pending'] ?? 0; ?></div>
                <div class="stat-label">Pending</div>
            </div>
            <div class="stat-box">
                <div class="stat-number" style="color: #d1fae5;"><?php echo $stats['sent'] ?? 0; ?></div>
                <div class="stat-label">Sent</div>
            </div>
            <div class="stat-box">
                <div class="stat-number" style="color: #fee2e2;"><?php echo $stats['failed'] ?? 0; ?></div>
                <div class="stat-label">Failed</div>
            </div>
        </div>
        
        <!-- Controls -->
        <div class="controls">
            <form method="POST" style="display: inline;">
                <input type="hidden" name="action" value="resend_all_pending">
                <button type="submit" class="btn btn-success" onclick="return confirm('Retry sending all pending emails?');">
                    🔄 Resend All Pending
                </button>
            </form>
        </div>
        
        <!-- Email Table -->
        <?php if ($emails && $emails->num_rows > 0): ?>
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Recipient</th>
                        <th>Type</th>
                        <th>Subject</th>
                        <th>Status</th>
                        <th>Created</th>
                        <th>Attempts</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php while ($row = $emails->fetch_assoc()): ?>
                        <tr>
                            <td><?php echo $row['id']; ?></td>
                            <td><?php echo htmlspecialchars($row['recipient_email']); ?></td>
                            <td><?php echo htmlspecialchars($row['email_type']); ?></td>
                            <td><?php echo htmlspecialchars(substr($row['subject'], 0, 50)); ?></td>
                            <td>
                                <span class="status-badge status-<?php echo $row['status']; ?>">
                                    <?php echo strtoupper($row['status']); ?>
                                </span>
                            </td>
                            <td><?php echo date('M d, Y H:i', strtotime($row['created_at'])); ?></td>
                            <td><?php echo $row['attempts']; ?></td>
                            <td>
                                <?php if ($row['status'] === 'pending' || $row['status'] === 'failed'): ?>
                                    <form method="POST" style="display: inline;">
                                        <input type="hidden" name="action" value="resend_email">
                                        <input type="hidden" name="email_id" value="<?php echo $row['id']; ?>">
                                        <button type="submit" class="btn btn-success btn-sm">Resend</button>
                                    </form>
                                <?php else: ?>
                                    <span style="color: #888;">-</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        <?php else: ?>
            <div style="text-align: center; padding: 40px; color: #666;">
                <p>No emails in queue</p>
            </div>
        <?php endif; ?>
        
        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
            <div class="pagination">
                <?php if ($page > 1): ?>
                    <a href="?page=1">« First</a>
                    <a href="?page=<?php echo $page - 1; ?>">← Previous</a>
                <?php endif; ?>
                
                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                    <?php if ($i === $page): ?>
                        <span class="active"><?php echo $i; ?></span>
                    <?php else: ?>
                        <a href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                    <?php endif; ?>
                <?php endfor; ?>
                
                <?php if ($page < $total_pages): ?>
                    <a href="?page=<?php echo $page + 1; ?>">Next →</a>
                    <a href="?page=<?php echo $total_pages; ?>">Last »</a>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>
</body>
</html>
