<?php
// Admin page to view and manage email queue
session_start();

require_once 'config/db.php';

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

// Handle resend all pending
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'resend_all') {
    // Get all pending AND failed emails
    $stmt = $connection->prepare("SELECT id, recipient_email, subject, body FROM email_queue WHERE status IN ('pending', 'failed') LIMIT 50");
    $stmt->execute();
    $result = $stmt->get_result();
    
    $sent_count = 0;
    $failed_count = 0;
    
    while ($email_record = $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";
        
        $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 WHERE id = ?");
        $status = $sent ? 'sent' : 'failed';
        $update_stmt->bind_param("si", $status, $email_record['id']);
        $update_stmt->execute();
        
        if ($sent) {
            $sent_count++;
            error_log("✓ Resent email to: {$email_record['recipient_email']}");
        } else {
            $failed_count++;
            error_log("✗ Failed to resend email to: {$email_record['recipient_email']}");
        }
    }
    
    $message = "Resent $sent_count emails successfully. Failed: $failed_count.";
}

// Handle resend single email
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'resend') {
    $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: noreply@interiordesign.com\r\n";
        $headers .= "Reply-To: admin@interiordesign.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 WHERE id = ?");
        $status = $sent ? 'sent' : 'failed';
        $update_stmt->bind_param("si", $status, $email_id);
        $update_stmt->execute();
        
        $message = $sent ? "✓ Email sent successfully to " . htmlspecialchars($email_record['recipient_email']) : "✗ Email send failed. Check server mail configuration.";
    }
}

// Get stats
$stats = $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
")->fetch_assoc();

// Get all queued emails
$query = "SELECT id, recipient_email, subject, email_type, status, attempts, sent_at, created_at FROM email_queue ORDER BY created_at DESC LIMIT 100";
$result = $connection->query($query);
?>
<!DOCTYPE html>
<html>
<head>
    <title>Email Queue - Admin</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #8b6f47 0%, #6b5738 100%);
            color: white;
            padding: 30px;
        }
        
        .header h1 {
            font-size: 28px;
            margin-bottom: 5px;
        }
        
        .header p {
            opacity: 0.9;
        }
        
        .content {
            padding: 30px;
        }
        
        .message {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-weight: 600;
        }
        
        .message.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .stats {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 15px;
            margin-bottom: 30px;
        }
        
        .stat {
            background: #f9f7f4;
            padding: 20px;
            border-radius: 8px;
            border-left: 4px solid #8b6f47;
        }
        
        .stat-number {
            font-size: 32px;
            font-weight: bold;
            color: #8b6f47;
        }
        
        .stat-label {
            color: #666;
            font-size: 14px;
            margin-top: 5px;
        }
        
        .buttons {
            display: flex;
            gap: 10px;
            margin-bottom: 30px;
        }
        
        button {
            padding: 12px 24px;
            background: linear-gradient(135deg, #8b6f47 0%, #6b5738 100%);
            color: white;
            border: none;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(139, 111, 71, 0.3);
        }
        
        .btn-small {
            padding: 8px 16px;
            font-size: 12px;
        }
        
        .table-wrapper {
            overflow-x: auto;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
        }
        
        th {
            background: #f9f7f4;
            padding: 15px;
            text-align: left;
            font-weight: 600;
            color: #8b6f47;
            border-bottom: 2px solid #e0e0e0;
        }
        
        td {
            padding: 12px 15px;
            border-bottom: 1px solid #e0e0e0;
        }
        
        tr:hover {
            background: #f9f7f4;
        }
        
        .status-badge {
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            display: inline-block;
        }
        
        .status-pending {
            background: #fff3cd;
            color: #856404;
        }
        
        .status-sent {
            background: #d4edda;
            color: #155724;
        }
        
        .status-failed {
            background: #f8d7da;
            color: #721c24;
        }
        
        .type-badge {
            background: #cce5ff;
            color: #004085;
            padding: 4px 10px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #999;
        }
        
        .back-btn {
            background: #6c757d;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📧 Email Queue Manager</h1>
            <p>Manage and resend pending consultation confirmation emails</p>
        </div>
        
        <div class="content">
            <?php if (isset($message)): ?>
                <div class="message success">
                    <?php echo $message; ?>
                </div>
            <?php endif; ?>
            
            <div class="stats">
                <div class="stat">
                    <div class="stat-number"><?php echo $stats['total']; ?></div>
                    <div class="stat-label">Total Emails</div>
                </div>
                <div class="stat">
                    <div class="stat-number"><?php echo $stats['pending']; ?></div>
                    <div class="stat-label">Pending</div>
                </div>
                <div class="stat">
                    <div class="stat-number"><?php echo $stats['sent']; ?></div>
                    <div class="stat-label">Sent</div>
                </div>
                <div class="stat">
                    <div class="stat-number"><?php echo $stats['failed']; ?></div>
                    <div class="stat-label">Failed</div>
                </div>
            </div>
            
            <div class="buttons">
                <form method="POST" style="display: inline;">
                    <input type="hidden" name="action" value="resend_all">
                    <button type="submit">🔄 Retry All Failed/Pending (<?php echo ($stats['pending'] + $stats['failed']); ?>)</button>
                </form>
                <a href="admin-dashboard.php" class="back-btn">← Back to Dashboard</a>
            </div>
            
            <?php if ($result->num_rows === 0): ?>
                <div class="empty-state">
                    <h3>✓ All Caught Up!</h3>
                    <p>No emails in the queue.</p>
                </div>
            <?php else: ?>
                <div class="table-wrapper">
                    <table>
                        <thead>
                            <tr>
                                <th>Recipient Email</th>
                                <th>Type</th>
                                <th>Subject</th>
                                <th>Status</th>
                                <th>Created</th>
                                <th>Attempts</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while ($row = $result->fetch_assoc()): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($row['recipient_email']); ?></td>
                                    <td><span class="type-badge"><?php echo ucfirst($row['email_type']); ?></span></td>
                                    <td><?php echo htmlspecialchars(substr($row['subject'], 0, 60)); ?></td>
                                    <td><span class="status-badge status-<?php echo $row['status']; ?>"><?php echo ucfirst($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>
                                        <form method="POST" style="display: inline;">
                                            <input type="hidden" name="action" value="resend">
                                            <input type="hidden" name="email_id" value="<?php echo $row['id']; ?>">
                                            <button type="submit" class="btn-small">Resend</button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>
