<?php
define('ROVO_APP', true);
require_once '../config.php';
require_once '../Auth.php';

$page_title = 'Contact Messages';

if (!$auth->isAdmin()) {
    $_SESSION['error'] = "You don't have permission to access this page";
    header('Location: dashboard.php');
    exit;
}

$current_user = $auth->getCurrentUser();

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if (!Security::validateCSRFToken($_POST['csrf_token'])) {
        die('Invalid CSRF token');
    }
    
    $action = $_POST['action'];
    $msg_id = (int)$_POST['msg_id'];
    
    if ($action === 'mark_read') {
        $sql = "UPDATE contact_messages SET status = 'read' WHERE id = ?";
        $db->execute($sql, [$msg_id]);
        echo json_encode(['success' => true, 'message' => 'Marked as read']);
        exit;
    }
    
    if ($action === 'mark_replied') {
        $sql = "UPDATE contact_messages SET 
                status = 'replied',
                replied_by = ?,
                replied_at = NOW()
                WHERE id = ?";
        $db->execute($sql, [$current_user['id'], $msg_id]);
        echo json_encode(['success' => true, 'message' => 'Marked as replied']);
        exit;
    }
    
    if ($action === 'archive') {
        $sql = "UPDATE contact_messages SET status = 'archived' WHERE id = ?";
        $db->execute($sql, [$msg_id]);
        echo json_encode(['success' => true, 'message' => 'Message archived']);
        exit;
    }
    
    if ($action === 'delete' && $auth->hasRole('super_admin')) {
        $sql = "DELETE FROM contact_messages WHERE id = ?";
        $db->execute($sql, [$msg_id]);
        $_SESSION['success'] = "Message deleted successfully";
        header('Location: contact-messages.php');
        exit;
    }
}

// Get filter parameters
$search = $_GET['search'] ?? '';
$status_filter = $_GET['status'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 15;
$offset = ($page - 1) * $limit;

// Build query
$where = [];
$params = [];

if ($search) {
    $where[] = "(name LIKE ? OR email LIKE ? OR subject LIKE ? OR message LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($status_filter) {
    $where[] = "status = ?";
    $params[] = $status_filter;
}

$where_sql = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';

$count_sql = "SELECT COUNT(*) as total FROM contact_messages $where_sql";
$total = $db->fetchOne($count_sql, $params)['total'];
$total_pages = ceil($total / $limit);

$sql = "SELECT cm.*, CONCAT(u.first_name, ' ', u.last_name) as replied_by_name
        FROM contact_messages cm
        LEFT JOIN users u ON cm.replied_by = u.id
        $where_sql
        ORDER BY cm.created_at DESC
        LIMIT $limit OFFSET $offset";

$messages = $db->fetchAll($sql, $params);

// Get statistics
$stats = [
    'new' => $db->fetchOne("SELECT COUNT(*) as count FROM contact_messages WHERE status = 'new'")['count'],
    'read' => $db->fetchOne("SELECT COUNT(*) as count FROM contact_messages WHERE status = 'read'")['count'],
    'replied' => $db->fetchOne("SELECT COUNT(*) as count FROM contact_messages WHERE status = 'replied'")['count'],
    'archived' => $db->fetchOne("SELECT COUNT(*) as count FROM contact_messages WHERE status = 'archived'")['count']
];

include 'includes/header.php';
?>

<div class="page-header">
    <h1>Contact Messages</h1>
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
            <li class="breadcrumb-item active">Contact Messages</li>
        </ol>
    </nav>
</div>

<?php if (isset($_SESSION['success'])): ?>
<div class="alert alert-success alert-dismissible fade show">
    <i class="fas fa-check-circle"></i> <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<!-- Statistics -->
<div class="row mb-4">
    <div class="col-md-3">
        <div class="card">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="flex-shrink-0">
                        <i class="fas fa-envelope fa-2x text-primary"></i>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <h3 class="mb-0"><?php echo $stats['new']; ?></h3>
                        <p class="text-muted mb-0">New Messages</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="flex-shrink-0">
                        <i class="fas fa-eye fa-2x text-info"></i>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <h3 class="mb-0"><?php echo $stats['read']; ?></h3>
                        <p class="text-muted mb-0">Read</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="flex-shrink-0">
                        <i class="fas fa-reply fa-2x text-success"></i>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <h3 class="mb-0"><?php echo $stats['replied']; ?></h3>
                        <p class="text-muted mb-0">Replied</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="flex-shrink-0">
                        <i class="fas fa-archive fa-2x text-secondary"></i>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <h3 class="mb-0"><?php echo $stats['archived']; ?></h3>
                        <p class="text-muted mb-0">Archived</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <h5 class="mb-0">
            <i class="fas fa-envelope"></i> All Messages
            <span class="badge bg-primary"><?php echo number_format($total); ?></span>
        </h5>
    </div>
    
    <div class="card-body">
        <!-- Filters -->
        <form method="GET" class="mb-4">
            <div class="row g-3">
                <div class="col-md-6">
                    <div class="input-group">
                        <span class="input-group-text"><i class="fas fa-search"></i></span>
                        <input type="text" name="search" class="form-control" placeholder="Search messages..." 
                               value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                </div>
                
                <div class="col-md-4">
                    <select name="status" class="form-select">
                        <option value="">All Status</option>
                        <option value="new" <?php echo $status_filter === 'new' ? 'selected' : ''; ?>>New</option>
                        <option value="read" <?php echo $status_filter === 'read' ? 'selected' : ''; ?>>Read</option>
                        <option value="replied" <?php echo $status_filter === 'replied' ? 'selected' : ''; ?>>Replied</option>
                        <option value="archived" <?php echo $status_filter === 'archived' ? 'selected' : ''; ?>>Archived</option>
                    </select>
                </div>
                
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-filter"></i> Filter
                    </button>
                </div>
            </div>
        </form>
        
        <!-- Messages Table -->
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th style="width: 30px;"></th>
                        <th>From</th>
                        <th>Subject</th>
                        <th>Message Preview</th>
                        <th>Status</th>
                        <th>Date</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($messages)): ?>
                    <tr>
                        <td colspan="7" class="text-center py-4">
                            <i class="fas fa-inbox fa-3x text-muted mb-3 d-block"></i>
                            <p class="text-muted">No messages found</p>
                        </td>
                    </tr>
                    <?php else: ?>
                        <?php foreach ($messages as $msg): ?>
                        <tr class="<?php echo $msg['status'] === 'new' ? 'table-primary' : ''; ?>">
                            <td>
                                <?php if ($msg['status'] === 'new'): ?>
                                <i class="fas fa-circle text-primary" style="font-size: 0.5rem;"></i>
                                <?php endif; ?>
                            </td>
                            <td>
                                <strong><?php echo htmlspecialchars($msg['name']); ?></strong>
                                <br>
                                <small class="text-muted">
                                    <i class="fas fa-envelope"></i> <?php echo htmlspecialchars($msg['email']); ?>
                                </small>
                                <?php if ($msg['phone']): ?>
                                <br>
                                <small class="text-muted">
                                    <i class="fas fa-phone"></i> <?php echo htmlspecialchars($msg['phone']); ?>
                                </small>
                                <?php endif; ?>
                            </td>
                            <td>
                                <strong><?php echo htmlspecialchars($msg['subject'] ?? 'No Subject'); ?></strong>
                            </td>
                            <td>
                                <small><?php echo htmlspecialchars(substr($msg['message'], 0, 100)); ?>...</small>
                            </td>
                            <td>
                                <?php
                                $badge_class = [
                                    'new' => 'primary',
                                    'read' => 'info',
                                    'replied' => 'success',
                                    'archived' => 'secondary'
                                ][$msg['status']] ?? 'secondary';
                                ?>
                                <span class="badge bg-<?php echo $badge_class; ?>">
                                    <?php echo ucfirst($msg['status']); ?>
                                </span>
                            </td>
                            <td>
                                <?php echo date('M d, Y', strtotime($msg['created_at'])); ?>
                                <br>
                                <small class="text-muted"><?php echo date('H:i', strtotime($msg['created_at'])); ?></small>
                            </td>
                            <td>
                                <div class="btn-group btn-group-sm">
                                    <button type="button" class="btn btn-outline-primary view-message" 
                                            data-id="<?php echo $msg['id']; ?>">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                    
                                    <?php if ($msg['status'] === 'new'): ?>
                                    <button type="button" class="btn btn-outline-info mark-read" 
                                            data-id="<?php echo $msg['id']; ?>">
                                        <i class="fas fa-check"></i>
                                    </button>
                                    <?php endif; ?>
                                    
                                    <?php if ($msg['status'] !== 'replied'): ?>
                                    <button type="button" class="btn btn-outline-success mark-replied" 
                                            data-id="<?php echo $msg['id']; ?>">
                                        <i class="fas fa-reply"></i>
                                    </button>
                                    <?php endif; ?>
                                    
                                    <button type="button" class="btn btn-outline-secondary archive-msg" 
                                            data-id="<?php echo $msg['id']; ?>">
                                        <i class="fas fa-archive"></i>
                                    </button>
                                    
                                    <?php if ($auth->hasRole('super_admin')): ?>
                                    <button type="button" class="btn btn-outline-danger delete-msg" 
                                            data-id="<?php echo $msg['id']; ?>">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <nav>
            <ul class="pagination justify-content-center">
                <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>">Previous</a>
                </li>
                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>"><?php echo $i; ?></a>
                </li>
                <?php endfor; ?>
                <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>">Next</a>
                </li>
            </ul>
        </nav>
        <?php endif; ?>
    </div>
</div>

<!-- View Message Modal -->
<div class="modal fade" id="viewMessageModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Message Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="messageContent">
                <div class="text-center py-4">
                    <div class="spinner-border" role="status"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<form method="POST" id="deleteForm" style="display: none;">
    <input type="hidden" name="action" value="delete">
    <input type="hidden" name="msg_id" id="deleteId">
    <input type="hidden" name="csrf_token" value="<?php echo Security::generateCSRFToken(); ?>">
</form>

<script>
    // View message
    $('.view-message').click(function() {
        const msgId = $(this).data('id');
        $('#messageContent').html('<div class="text-center py-4"><div class="spinner-border"></div></div>');
        $('#viewMessageModal').modal('show');
        
        $.get('ajax/get-contact-message.php', { id: msgId }, function(data) {
            $('#messageContent').html(data);
        });
    });
    
    // Mark as read
    $('.mark-read').click(function() {
        const msgId = $(this).data('id');
        
        $.post('contact-messages.php', {
            action: 'mark_read',
            msg_id: msgId,
            csrf_token: '<?php echo Security::generateCSRFToken(); ?>'
        }, function(response) {
            if (response.success) {
                location.reload();
            }
        }, 'json');
    });
    
    // Mark as replied
    $('.mark-replied').click(function() {
        const msgId = $(this).data('id');
        
        Swal.fire({
            title: 'Mark as Replied?',
            text: 'Have you replied to this message?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Yes, mark it'
        }).then((result) => {
            if (result.isConfirmed) {
                $.post('contact-messages.php', {
                    action: 'mark_replied',
                    msg_id: msgId,
                    csrf_token: '<?php echo Security::generateCSRFToken(); ?>'
                }, function(response) {
                    if (response.success) {
                        location.reload();
                    }
                }, 'json');
            }
        });
    });
    
    // Archive
    $('.archive-msg').click(function() {
        const msgId = $(this).data('id');
        
        $.post('contact-messages.php', {
            action: 'archive',
            msg_id: msgId,
            csrf_token: '<?php echo Security::generateCSRFToken(); ?>'
        }, function(response) {
            if (response.success) {
                location.reload();
            }
        }, 'json');
    });
    
    // Delete
    $('.delete-msg').click(function() {
        const msgId = $(this).data('id');
        
        Swal.fire({
            title: 'Delete Message?',
            text: 'This action cannot be undone!',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!'
        }).then((result) => {
            if (result.isConfirmed) {
                $('#deleteId').val(msgId);
                $('#deleteForm').submit();
            }
        });
    });
</script>

<?php include 'includes/footer.php'; ?>