Path : /home/vishqocm/pcib.in/admin/
File Upload :
Current File : /home/vishqocm//pcib.in/admin/contact-messages.php

<?php
// Include header
include_once 'includes/header.php';

// Check if user has admin privileges
if (!isset($_SESSION['role']) || ($_SESSION['role'] !== 'admin' && $_SESSION['role'] !== 'director')) {
    header('Location: ../login.php');
    exit;
}

// Mark a message as read
if (isset($_GET['mark_read']) && is_numeric($_GET['mark_read'])) {
    $message_id = (int)$_GET['mark_read'];
    $stmt = $conn->prepare("UPDATE contact_messages SET status = 'read', updated_at = NOW() WHERE id = ?");
    $stmt->bind_param("i", $message_id);
    $stmt->execute();
    
    // Also mark related notification as read
    $stmt = $conn->prepare("UPDATE notifications SET is_read = 1 WHERE reference_id = ? AND reference_type = 'contact_message'");
    $stmt->bind_param("i", $message_id);
    $stmt->execute();
    
    header('Location: contact-messages.php?status=read_success');
    exit;
}

// Delete a message
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $message_id = (int)$_GET['delete'];
    $stmt = $conn->prepare("DELETE FROM contact_messages WHERE id = ?");
    $stmt->bind_param("i", $message_id);
    $stmt->execute();
    
    // Also delete related notification
    $stmt = $conn->prepare("DELETE FROM notifications WHERE reference_id = ? AND reference_type = 'contact_message'");
    $stmt->bind_param("i", $message_id);
    $stmt->execute();
    
    header('Location: contact-messages.php?status=delete_success');
    exit;
}

// Get all messages with pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

// Check if table exists
$table_check = $conn->query("SHOW TABLES LIKE 'contact_messages'");
if ($table_check->num_rows == 0) {
    // Create contact_messages table if it doesn't exist
    $create_table = "CREATE TABLE contact_messages (
        id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100) NOT NULL,
        email VARCHAR(100) NOT NULL,
        subject VARCHAR(200) NOT NULL,
        message TEXT NOT NULL,
        status ENUM('new', 'read', 'replied') DEFAULT 'new',
        created_at DATETIME NOT NULL,
        updated_at DATETIME NULL
    )";
    $conn->query($create_table);
}

// Filter by status if provided
$status_filter = isset($_GET['filter']) ? $_GET['filter'] : '';
$where_clause = '';
$params = [];
$types = '';

if ($status_filter && in_array($status_filter, ['new', 'read', 'replied'])) {
    $where_clause = " WHERE status = ? ";
    $params[] = $status_filter;
    $types .= 's';
}

// Get total messages count for pagination
$count_query = "SELECT COUNT(*) as total FROM contact_messages" . $where_clause;
$stmt = $conn->prepare($count_query);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$total_result = $stmt->get_result()->fetch_assoc();
$total_messages = $total_result['total'];
$total_pages = ceil($total_messages / $limit);

// Get messages for the current page
$query = "SELECT * FROM contact_messages" . $where_clause . " ORDER BY created_at DESC LIMIT ?, ?";
$stmt = $conn->prepare($query);
if (!empty($params)) {
    $params[] = $offset;
    $params[] = $limit;
    $types .= 'ii';
    $stmt->bind_param($types, ...$params);
} else {
    $stmt->bind_param("ii", $offset, $limit);
}
$stmt->execute();
$result = $stmt->get_result();
$messages = [];
while ($row = $result->fetch_assoc()) {
    $messages[] = $row;
}
?>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">Contact Messages</h1>
    
    <?php if (isset($_GET['status'])): ?>
        <?php if ($_GET['status'] == 'read_success'): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle mr-2"></i> Message marked as read.
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
        <?php elseif ($_GET['status'] == 'delete_success'): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle mr-2"></i> Message deleted successfully.
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
        <?php endif; ?>
    <?php endif; ?>
    
    <div class="card shadow mb-4">
        <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
            <h6 class="m-0 font-weight-bold text-primary">Messages</h6>
            <div class="dropdown no-arrow">
                <a class="dropdown-toggle" href="#" role="button" id="filterDropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                    <i class="fas fa-filter fa-sm fa-fw text-gray-400"></i> Filter
                </a>
                <div class="dropdown-menu dropdown-menu-right shadow animated--fade-in" aria-labelledby="filterDropdown">
                    <a class="dropdown-item <?php echo $status_filter == '' ? 'active' : ''; ?>" href="contact-messages.php">All Messages</a>
                    <a class="dropdown-item <?php echo $status_filter == 'new' ? 'active' : ''; ?>" href="contact-messages.php?filter=new">New</a>
                    <a class="dropdown-item <?php echo $status_filter == 'read' ? 'active' : ''; ?>" href="contact-messages.php?filter=read">Read</a>
                    <a class="dropdown-item <?php echo $status_filter == 'replied' ? 'active' : ''; ?>" href="contact-messages.php?filter=replied">Replied</a>
                </div>
            </div>
        </div>
        <div class="card-body">
            <?php if (empty($messages)): ?>
                <div class="text-center py-4">
                    <i class="fas fa-inbox fa-4x text-gray-300 mb-3"></i>
                    <p class="lead text-gray-800">No messages found</p>
                    <?php if ($status_filter): ?>
                        <a href="contact-messages.php" class="btn btn-primary">
                            <i class="fas fa-sync-alt mr-1"></i> Show All Messages
                        </a>
                    <?php endif; ?>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Email</th>
                                <th>Subject</th>
                                <th>Date</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($messages as $message): ?>
                                <tr class="<?php echo $message['status'] == 'new' ? 'table-primary' : ''; ?>">
                                    <td><?php echo htmlspecialchars($message['name']); ?></td>
                                    <td>
                                        <a href="mailto:<?php echo htmlspecialchars($message['email']); ?>">
                                            <?php echo htmlspecialchars($message['email']); ?>
                                        </a>
                                    </td>
                                    <td><?php echo htmlspecialchars($message['subject']); ?></td>
                                    <td><?php echo date('M d, Y h:i A', strtotime($message['created_at'])); ?></td>
                                    <td>
                                        <?php if ($message['status'] == 'new'): ?>
                                            <span class="badge badge-primary">New</span>
                                        <?php elseif ($message['status'] == 'read'): ?>
                                            <span class="badge badge-info">Read</span>
                                        <?php elseif ($message['status'] == 'replied'): ?>
                                            <span class="badge badge-success">Replied</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <button type="button" class="btn btn-primary btn-sm view-message" 
                                                data-toggle="modal" 
                                                data-target="#messageModal" 
                                                data-id="<?php echo $message['id']; ?>"
                                                data-name="<?php echo htmlspecialchars($message['name']); ?>"
                                                data-email="<?php echo htmlspecialchars($message['email']); ?>"
                                                data-subject="<?php echo htmlspecialchars($message['subject']); ?>"
                                                data-message="<?php echo htmlspecialchars($message['message']); ?>"
                                                data-date="<?php echo date('M d, Y h:i A', strtotime($message['created_at'])); ?>"
                                                data-status="<?php echo $message['status']; ?>">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                        
                                        <?php if ($message['status'] == 'new'): ?>
                                            <a href="contact-messages.php?mark_read=<?php echo $message['id']; ?>" class="btn btn-info btn-sm" title="Mark as Read">
                                                <i class="fas fa-check"></i>
                                            </a>
                                        <?php endif; ?>
                                        
                                        <a href="mailto:<?php echo htmlspecialchars($message['email']); ?>?subject=Re: <?php echo htmlspecialchars($message['subject']); ?>" 
                                           class="btn btn-success btn-sm" title="Reply">
                                            <i class="fas fa-reply"></i>
                                        </a>
                                        
                                        <a href="contact-messages.php?delete=<?php echo $message['id']; ?>" class="btn btn-danger btn-sm" 
                                           onclick="return confirm('Are you sure you want to delete this message?');" title="Delete">
                                            <i class="fas fa-trash"></i>
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                
                <!-- Pagination -->
                <?php if ($total_pages > 1): ?>
                <div class="d-flex justify-content-center mt-4">
                    <nav aria-label="Page navigation">
                        <ul class="pagination">
                            <?php if ($page > 1): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo ($page - 1); ?><?php echo $status_filter ? '&filter=' . $status_filter : ''; ?>" aria-label="Previous">
                                        <span aria-hidden="true">&laquo;</span>
                                    </a>
                                </li>
                            <?php endif; ?>
                            
                            <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $i; ?><?php echo $status_filter ? '&filter=' . $status_filter : ''; ?>">
                                        <?php echo $i; ?>
                                    </a>
                                </li>
                            <?php endfor; ?>
                            
                            <?php if ($page < $total_pages): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo ($page + 1); ?><?php echo $status_filter ? '&filter=' . $status_filter : ''; ?>" aria-label="Next">
                                        <span aria-hidden="true">&raquo;</span>
                                    </a>
                                </li>
                            <?php endif; ?>
                        </ul>
                    </nav>
                </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Message Modal -->
<div class="modal fade" id="messageModal" tabindex="-1" role="dialog" aria-labelledby="messageModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="messageModalLabel">Message Details</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="mb-4">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <div>
                            <h6 class="mb-1" id="modalSubject"></h6>
                            <small class="text-muted" id="modalDate"></small>
                        </div>
                        <span class="badge" id="modalStatus"></span>
                    </div>
                </div>
                
                <div class="row mb-4">
                    <div class="col-md-6">
                        <p class="mb-1"><strong>From:</strong> <span id="modalName"></span></p>
                    </div>
                    <div class="col-md-6">
                        <p class="mb-1"><strong>Email:</strong> <span id="modalEmail"></span></p>
                    </div>
                </div>
                
                <div class="card">
                    <div class="card-body">
                        <div id="modalMessage"></div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <a href="#" class="btn btn-info" id="modalMarkRead">Mark as Read</a>
                <a href="#" class="btn btn-success" id="modalReply">Reply</a>
                <a href="#" class="btn btn-danger" id="modalDelete" onclick="return confirm('Are you sure you want to delete this message?');">Delete</a>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Initialize DataTable
    $('#dataTable').DataTable({
        "order": [[3, "desc"]],
        "pageLength": 10,
        "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
        "columnDefs": [
            { "orderable": false, "targets": 5 }
        ]
    });
    
    // Message Modal
    $('.view-message').click(function() {
        var id = $(this).data('id');
        var name = $(this).data('name');
        var email = $(this).data('email');
        var subject = $(this).data('subject');
        var message = $(this).data('message');
        var date = $(this).data('date');
        var status = $(this).data('status');
        
        $('#modalSubject').text(subject);
        $('#modalName').text(name);
        $('#modalEmail').text(email);
        $('#modalDate').text(date);
        $('#modalMessage').html(message.replace(/\n/g, '<br>'));
        
        // Set status badge
        if (status == 'new') {
            $('#modalStatus').text('New').removeClass().addClass('badge badge-primary');
        } else if (status == 'read') {
            $('#modalStatus').text('Read').removeClass().addClass('badge badge-info');
        } else if (status == 'replied') {
            $('#modalStatus').text('Replied').removeClass().addClass('badge badge-success');
        }
        
        // Set action buttons
        $('#modalMarkRead').attr('href', 'contact-messages.php?mark_read=' + id);
        $('#modalReply').attr('href', 'mailto:' + email + '?subject=Re: ' + subject);
        $('#modalDelete').attr('href', 'contact-messages.php?delete=' + id);
        
        // Hide mark as read button if already read
        if (status != 'new') {
            $('#modalMarkRead').hide();
        } else {
            $('#modalMarkRead').show();
        }
        
        // Mark message as read when viewed
        if (status == 'new') {
            $.ajax({
                url: 'contact-messages.php?mark_read=' + id,
                type: 'GET',
                success: function() {
                    // Update UI to show it's been read
                    $(this).closest('tr').removeClass('table-primary');
                    $(this).data('status', 'read');
                }
            });
        }
    });
});
</script>

<?php
// Include footer
include_once 'includes/footer.php';
?>