<?php
/**
 * ADMIN MESSAGE CENTER
 * File: admin/messages.php
 * Display list of previously sent messages
 */

require_once '../app/Core/init.php';

// Check admin authentication
Auth::requireAdmin();

$page_title = "Message Center";
$active_menu = "messages";

// Initialize models
$message_model = new Message();

// Handle message actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Delete message
    if (isset($_POST['delete_message'])) {
        $message_id = (int)($_POST['message_id'] ?? 0);
        if ($message_id > 0) {
            if ($message_model->delete($message_id)) {
                flash('success', 'Message deleted successfully', 'success');
            } else {
                flash('error', 'Failed to delete message', 'danger');
            }
            redirect('messages.php');
        }
    }
}

// Get filters from URL parameters
$filters = [];
if (!empty($_GET['recipient_type'])) {
    $filters['recipient_type'] = $_GET['recipient_type'];
}
if (!empty($_GET['search'])) {
    $filters['search'] = $_GET['search'];
}
if (!empty($_GET['date_from'])) {
    $filters['date_from'] = $_GET['date_from'];
}
if (!empty($_GET['date_to'])) {
    $filters['date_to'] = $_GET['date_to'];
}

// Pagination
$page = (int)($_GET['page'] ?? 1);
$limit = 20;
$offset = ($page - 1) * $limit;

// Get messages and total count
$messages = $message_model->getAll($limit, $offset, $filters);
$total_messages = $message_model->getCount($filters);
$total_pages = ceil($total_messages / $limit);

// Get statistics
$stats = $message_model->getStatistics();

// Handle flash messages
$flash_message = flash('message');

include '../templates/layouts/admin/head.php';

?>

<div class="main-content">
    <?php include '../templates/layouts/admin/header.php'; ?>
    
    <!-- Page Header -->
    <div style="padding: 30px; background: white; border-bottom: 1px solid #eee;">
        <h1 style="font-size: 28px; font-weight: 700; color: var(--dark); margin-bottom: 5px;">
            <i class="fas fa-envelope"></i> Message Center
        </h1>
        <div style="display: flex; gap: 8px; font-size: 14px; color: #666;">
            <a href="index.php" style="color: var(--primary); text-decoration: none;">Home</a>
            <span>/</span>
            <span>Message Center</span>
        </div>
    </div>
    
    <!-- Content -->
    <div style="padding: 30px;">
        
        <!-- Flash Messages -->
        <?php if ($flash_message): ?>
            <div class="alert alert-<?= $flash_message['type'] ?>">
                <?= Security::escapeOutput($flash_message['message']) ?>
            </div>
        <?php endif; ?>
        
        <div class="row">
            <div class="col-lg-12">
                <!-- Messages List Header -->
                <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); margin-bottom: 20px;">
                    <div style="display: flex; justify-content: between; align-items: center; margin-bottom: 20px;">
                        <div>
                            <h2 style="font-size: 24px; font-weight: 600; margin-bottom: 5px; color: var(--dark);">
                                <i class="fas fa-envelope"></i> Messages
                            </h2>
                            <p style="color: #666; margin: 0;">View and manage all sent messages</p>
                        </div>
                        <div>
                            <a href="messages-compose.php" class="btn btn-primary" style="padding: 12px 24px;">
                                <i class="fas fa-plus"></i> Compose Message
                            </a>
                        </div>
                    </div>
                    
                    <!-- Filters -->
                    <form method="GET" style="margin-bottom: 20px;">
                        <div class="row">
                            <div class="col-md-3">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: var(--dark);">Recipient Type</label>
                                <select name="recipient_type" class="form-control" onchange="this.form.submit()">
                                    <option value="">All Recipients</option>
                                    <option value="individual_vendor" <?= ($filters['recipient_type'] ?? '') === 'individual_vendor' ? 'selected' : '' ?>>Individual Vendor</option>
                                    <option value="individual_customer" <?= ($filters['recipient_type'] ?? '') === 'individual_customer' ? 'selected' : '' ?>>Individual Customer</option>
                                    <option value="all_vendors" <?= ($filters['recipient_type'] ?? '') === 'all_vendors' ? 'selected' : '' ?>>All Vendors</option>
                                    <option value="all_customers" <?= ($filters['recipient_type'] ?? '') === 'all_customers' ? 'selected' : '' ?>>All Customers</option>
                                    <option value="all_admins" <?= ($filters['recipient_type'] ?? '') === 'all_admins' ? 'selected' : '' ?>>All Administrators</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: var(--dark);">Search</label>
                                <input type="text" name="search" class="form-control" placeholder="Search subject, content, or recipient..." 
                                       value="<?= Security::escapeOutput($filters['search'] ?? '') ?>">
                            </div>
                            <div class="col-md-2">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: var(--dark);">From Date</label>
                                <input type="date" name="date_from" class="form-control" value="<?= Security::escapeOutput($filters['date_from'] ?? '') ?>">
                            </div>
                            <div class="col-md-2">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: var(--dark);">To Date</label>
                                <input type="date" name="date_to" class="form-control" value="<?= Security::escapeOutput($filters['date_to'] ?? '') ?>">
                            </div>
                            <div class="col-md-2">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: var(--dark);">&nbsp;</label>
                                <div style="display: flex; gap: 10px;">
                                    <button type="submit" class="btn btn-primary" style="padding: 8px 16px;">
                                        <i class="fas fa-search"></i> Filter
                                    </button>
                                    <a href="messages.php" class="btn btn-outline-secondary" style="padding: 8px 16px;">
                                        <i class="fas fa-times"></i> Clear
                                    </a>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                
                <!-- Messages List -->
                <div style="background: white; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); overflow: hidden;">
                    <?php if (empty($messages)): ?>
                        <div style="padding: 40px; text-align: center; color: #666;">
                            <i class="fas fa-inbox" style="font-size: 48px; margin-bottom: 20px; color: #ddd;"></i>
                            <h3 style="color: var(--dark); margin-bottom: 10px;">No Messages Found</h3>
                            <p>No messages have been sent yet. Start by composing your first message.</p>
                            <a href="messages-compose.php" class="btn btn-primary" style="margin-top: 20px;">
                                <i class="fas fa-plus"></i> Compose First Message
                            </a>
                        </div>
                    <?php else: ?>
                        <div style="overflow-x: auto;">
                            <table style="width: 100%; border-collapse: collapse;">
                                <thead>
                                    <tr style="background: #f8f9fa; border-bottom: 1px solid #e9ecef;">
                                        <th style="padding: 15px; text-align: left; font-weight: 600; color: var(--dark);">Subject</th>
                                        <th style="padding: 15px; text-align: left; font-weight: 600; color: var(--dark);">Recipient Type</th>
                                        <th style="padding: 15px; text-align: left; font-weight: 600; color: var(--dark);">Recipient</th>
                                        <th style="padding: 15px; text-align: left; font-weight: 600; color: var(--dark);">Sent By</th>
                                        <th style="padding: 15px; text-align: left; font-weight: 600; color: var(--dark);">Date Sent</th>
                                        <th style="padding: 15px; text-align: center; font-weight: 600; color: var(--dark);">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($messages as $message): ?>
                                        <tr style="border-bottom: 1px solid #f0f0f0; transition: background-color 0.2s;" 
                                            onmouseover="this.style.backgroundColor='#f8f9fa'" 
                                            onmouseout="this.style.backgroundColor='white'">
                                            <td style="padding: 15px;">
                                                <div style="font-weight: 600; color: var(--dark); margin-bottom: 5px;">
                                                    <?= Security::escapeOutput($message['subject']) ?>
                                                </div>
                                                <div style="font-size: 13px; color: #666; max-width: 300px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                                                    <?= Security::escapeOutput(substr($message['content'], 0, 100)) ?>...
                                                </div>
                                            </td>
                                            <td style="padding: 15px;">
                                                <span class="<?= $message_model->getRecipientTypeBadgeClass($message['recipient_type']) ?>">
                                                    <?= $message_model->getRecipientTypeDisplay($message['recipient_type']) ?>
                                                </span>
                                            </td>
                                            <td style="padding: 15px; font-size: 13px; color: #666;">
                                                <?php if ($message['recipient_name']): ?>
                                                    <?= Security::escapeOutput($message['recipient_name']) ?>
                                                <?php else: ?>
                                                    <span style="color: #999;">All recipients</span>
                                                <?php endif; ?>
                                            </td>
                                            <td style="padding: 15px; font-size: 13px; color: #666;">
                                                <?= Security::escapeOutput($message['sender_name'] ?? 'Unknown') ?>
                                            </td>
                                            <td style="padding: 15px; font-size: 13px; color: #666;">
                                                <?= date('M j, Y g:i A', strtotime($message['sent_at'])) ?>
                                            </td>
                                            <td style="padding: 15px; text-align: center;">
                                                <div style="display: flex; gap: 8px; justify-content: center;">
                                                    <button type="button" class="btn btn-sm btn-outline-primary" 
                                                            onclick="viewMessage(<?= $message['id'] ?>)"
                                                            title="View Details">
                                                        <i class="fas fa-eye"></i>
                                                    </button>
                                                    <form method="POST" style="display: inline;" onsubmit="return confirm('Are you sure you want to delete this message?')">
                                                        <input type="hidden" name="message_id" value="<?= $message['id'] ?>">
                                                        <button type="submit" name="delete_message" class="btn btn-sm btn-outline-danger" title="Delete">
                                                            <i class="fas fa-trash"></i>
                                                        </button>
                                                    </form>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        
                        <!-- Pagination -->
                        <?php if ($total_pages > 1): ?>
                            <div style="padding: 20px; border-top: 1px solid #e9ecef; display: flex; justify-content: between; align-items: center;">
                                <div style="font-size: 14px; color: #666;">
                                    Showing <?= (($page - 1) * $limit + 1) ?> to <?= min($page * $limit, $total_messages) ?> of <?= $total_messages ?> messages
                                </div>
                                <div style="display: flex; gap: 5px;">
                                    <?php if ($page > 1): ?>
                                        <a href="?page=<?= $page - 1 ?><?= !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['page' => ''])) : '' ?>" 
                                           class="btn btn-sm btn-outline-secondary">Previous</a>
                                    <?php endif; ?>
                                    
                                    <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                                        <a href="?page=<?= $i ?><?= !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['page' => ''])) : '' ?>" 
                                           class="btn btn-sm <?= $i === $page ? 'btn-primary' : 'btn-outline-secondary' ?>">
                                            <?= $i ?>
                                        </a>
                                    <?php endfor; ?>
                                    
                                    <?php if ($page < $total_pages): ?>
                                        <a href="?page=<?= $page + 1 ?><?= !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['page' => ''])) : '' ?>" 
                                           class="btn btn-sm btn-outline-secondary">Next</a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Sidebar -->
            <div class="col-lg-4" style="margin-top: 20px;">
                <!-- Message Statistics -->
                <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); margin-bottom: 20px;">
                    <h3 style="font-size: 18px; font-weight: 600; margin-bottom: 20px; color: var(--dark);">
                        <i class="fas fa-chart-bar"></i> Message Statistics
                    </h3>
                    
                    <div style="display: grid; gap: 15px;">
                        <div style="padding: 15px; background: var(--light); border-radius: 8px;">
                            <div style="font-size: 24px; font-weight: 700; color: var(--primary);">
                                <?= $stats['total'] ?>
                            </div>
                            <div style="font-size: 14px; color: #666;">Total Messages</div>
                        </div>
                        
                        <div style="padding: 15px; background: var(--light); border-radius: 8px;">
                            <div style="font-size: 24px; font-weight: 700; color: var(--success);">
                                <?= $stats['today'] ?>
                            </div>
                            <div style="font-size: 14px; color: #666;">Sent Today</div>
                        </div>
                        
                        <div style="padding: 15px; background: var(--light); border-radius: 8px;">
                            <div style="font-size: 24px; font-weight: 700; color: var(--info);">
                                <?= $stats['this_week'] ?>
                            </div>
                            <div style="font-size: 14px; color: #666;">This Week</div>
                        </div>
                    </div>
                </div>

                <!-- Quick Actions -->
                <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05);">
                    <h3 style="font-size: 18px; font-weight: 600; margin-bottom: 20px; color: var(--dark);">
                        <i class="fas fa-bolt"></i> Quick Actions
                    </h3>
                    
                    <div style="display: grid; gap: 10px;">
                        <a href="messages-compose.php" class="btn btn-primary" style="text-align: left; padding: 12px 15px;">
                            <i class="fas fa-plus"></i> Compose New Message
                        </a>
                        <a href="messages.php" class="btn btn-outline-secondary" style="text-align: left; padding: 12px 15px;">
                            <i class="fas fa-refresh"></i> Refresh List
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// View message details in modal
function viewMessage(messageId) {
    // Fetch message details via AJAX
    fetch(`messages-details.php?id=${messageId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showMessageModal(data.message);
            } else {
                alert('Failed to load message details');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('An error occurred while loading message details');
        });
}

// Show message details in modal
function showMessageModal(message) {
    // Create modal if it doesn't exist
    let modal = document.getElementById('messageModal');
    if (!modal) {
        modal = createMessageModal();
    }
    
    // Populate modal content
    document.getElementById('modalSubject').textContent = message.subject;
    document.getElementById('modalRecipientType').textContent = message.recipient_type_display;
    document.getElementById('modalRecipient').textContent = message.recipient_name || 'All recipients';
    document.getElementById('modalSender').textContent = message.sender_name || 'Unknown';
    document.getElementById('modalDate').textContent = new Date(message.sent_at).toLocaleString();
    document.getElementById('modalContent').textContent = message.content;
    
    // Show modal
    modal.style.display = 'block';
}

// Create message modal
function createMessageModal() {
    const modal = document.createElement('div');
    modal.id = 'messageModal';
    modal.style.cssText = `
        display: none;
        position: fixed;
        z-index: 1000;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0,0,0,0.5);
        animation: fadeIn 0.3s;
    `;
    
    modal.innerHTML = `
        <div style="
            background-color: white;
            margin: 5% auto;
            padding: 0;
            border-radius: 12px;
            width: 90%;
            max-width: 600px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.3);
            animation: slideIn 0.3s;
        ">
            <div style="padding: 20px 25px; border-bottom: 1px solid #eee; display: flex; justify-content: between; align-items: center;">
                <h3 style="margin: 0; color: var(--dark);" id="modalSubject">Message Subject</h3>
                <button onclick="closeMessageModal()" style="
                    background: none;
                    border: none;
                    font-size: 24px;
                    cursor: pointer;
                    color: #666;
                    padding: 0;
                    width: 30px;
                    height: 30px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                ">&times;</button>
            </div>
            <div style="padding: 25px;">
                <div style="margin-bottom: 15px;">
                    <strong style="color: var(--dark);">Recipient Type:</strong>
                    <span id="modalRecipientType" style="margin-left: 10px; color: #666;"></span>
                </div>
                <div style="margin-bottom: 15px;">
                    <strong style="color: var(--dark);">Recipient:</strong>
                    <span id="modalRecipient" style="margin-left: 10px; color: #666;"></span>
                </div>
                <div style="margin-bottom: 15px;">
                    <strong style="color: var(--dark);">Sent By:</strong>
                    <span id="modalSender" style="margin-left: 10px; color: #666;"></span>
                </div>
                <div style="margin-bottom: 20px;">
                    <strong style="color: var(--dark);">Date Sent:</strong>
                    <span id="modalDate" style="margin-left: 10px; color: #666;"></span>
                </div>
                <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; border-left: 4px solid var(--primary);">
                    <div id="modalContent" style="white-space: pre-wrap; color: var(--dark); line-height: 1.6;"></div>
                </div>
            </div>
            <div style="padding: 20px 25px; border-top: 1px solid #eee; text-align: right;">
                <button onclick="closeMessageModal()" class="btn btn-secondary">Close</button>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    // Close modal when clicking outside
    modal.addEventListener('click', function(e) {
        if (e.target === modal) {
            closeMessageModal();
        }
    });
    
    return modal;
}

// Close message modal
function closeMessageModal() {
    const modal = document.getElementById('messageModal');
    if (modal) {
        modal.style.display = 'none';
    }
}

// Add CSS animations
const style = document.createElement('style');
style.textContent = `
    @keyframes fadeIn {
        from { opacity: 0; }
        to { opacity: 1; }
    }
    @keyframes slideIn {
        from { 
            opacity: 0;
            transform: translateY(-50px);
        }
        to { 
            opacity: 1;
            transform: translateY(0);
        }
    }
`;
document.head.appendChild(style);
</script>

<style>
.form-control {
    border: 1px solid #ddd;
    border-radius: 6px;
    padding: 10px 12px;
    font-size: 14px;
    transition: border-color 0.3s;
    width: 100%;
    box-sizing: border-box;
}

.form-control:focus {
    outline: none;
    border-color: var(--primary);
    box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}

.btn {
    border: none;
    border-radius: 6px;
    padding: 10px 20px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
    text-decoration: none;
    display: inline-block;
    font-size: 14px;
}

.btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.btn-primary {
    background: var(--primary);
    color: white;
}

.btn-primary:hover {
    background: #0056b3;
}

.btn-secondary {
    background: #6c757d;
    color: white;
}

.btn-secondary:hover {
    background: #545b62;
}

.btn-outline-primary {
    background: transparent;
    color: var(--primary);
    border: 1px solid var(--primary);
    padding: 6px 12px;
    font-size: 12px;
}

.btn-outline-primary:hover {
    background: var(--primary);
    color: white;
}

.btn-outline-secondary {
    background: transparent;
    color: #6c757d;
    border: 1px solid #6c757d;
    padding: 8px 16px;
    font-size: 14px;
}

.btn-outline-secondary:hover {
    background: #6c757d;
    color: white;
}

.btn-outline-danger {
    background: transparent;
    color: #05472A;
    border: 1px solid #05472A;
    padding: 6px 12px;
    font-size: 12px;
}

.btn-outline-danger:hover {
    background: #05472A;
    color: white;
}

.btn-sm {
    padding: 6px 12px;
    font-size: 12px;
}

.alert {
    padding: 15px 20px;
    border-radius: 8px;
    margin-bottom: 20px;
}

.alert-success {
    background: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
}

.alert-danger {
    background: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
}

/* Badge styles */
.badge {
    display: inline-block;
    padding: 4px 8px;
    font-size: 11px;
    font-weight: 600;
    line-height: 1;
    text-align: center;
    white-space: nowrap;
    vertical-align: baseline;
    border-radius: 4px;
}

.badge-primary {
    color: #fff;
    background-color: #007bff;
}

.badge-success {
    color: #fff;
    background-color: #28a745;
}

.badge-warning {
    color: #fff;
    background-color: #ffc107;
}

.badge-info {
    color: #fff;
    background-color: #17a2b8;
}

.badge-secondary {
    color: #fff;
    background-color: #6c757d;
}

.badge-light {
    color: #212529;
    background-color: #f8f9fa;
}

/* Table hover effect */
.table tbody tr:hover {
    background-color: rgba(0,0,0,.03);
}

/* Main content responsive */
@media (max-width: 768px) {
    .col-lg-4 {
        margin-top: 20px;
    }
    
    .row > div {
        margin-bottom: 20px;
    }
}
</style>

<?php include '../templates/layouts/admin/footer.php'; ?>
