<?php
session_start();
require_once __DIR__ . '/../includes/config.php';
requireAdminLogin();

$adminPageTitle = 'Contact Messages';
$db = getDB();
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 20;
$offset = ($page - 1) * $perPage;

// Mark as read
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['mark_read'])) {
    $id = intval($_POST['message_id']);
    $stmt = $db->prepare("UPDATE contact_messages SET is_read = 1 WHERE id = ?");
    $stmt->execute([$id]);
}

// Delete message
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $stmt = $db->prepare("DELETE FROM contact_messages WHERE id = ?");
    $stmt->execute([$id]);
}

$stmt = $db->query("SELECT COUNT(*) as total FROM contact_messages");
$totalMessages = $stmt->fetch()['total'];
$totalPages = ceil($totalMessages / $perPage);

$stmt = $db->prepare("SELECT * FROM contact_messages ORDER BY created_at DESC LIMIT ? OFFSET ?");
$stmt->execute([$perPage, $offset]);
$messages = $stmt->fetchAll();

include __DIR__ . '/partials/admin_header.php';
?>

<div class="row mb-4">
    <div class="col-12">
        <h2 class="fw-bold mb-1"><i class="fas fa-envelope text-primary me-2"></i>Contact Messages</h2>
        <p class="text-muted mb-0">Manage customer inquiries and messages</p>
    </div>
</div>

<?php if (empty($messages)): ?>
    <div class="alert alert-info text-center py-5">
        <i class="fas fa-inbox fa-3x mb-3 text-muted"></i>
        <h5>No messages yet</h5>
        <p>Contact messages from customers will appear here.</p>
    </div>
<?php else: ?>
    <div class="table-card">
        <table class="table table-hover mb-0">
            <thead class="table-light">
                <tr>
                    <th width="10%">Status</th>
                    <th width="20%">Name</th>
                    <th width="20%">Email</th>
                    <th width="25%">Subject</th>
                    <th width="15%">Date</th>
                    <th width="10%">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($messages as $msg): ?>
                <tr class="<?= $msg['is_read'] ? '' : 'table-warning' ?>">
                    <td>
                        <?php if (!$msg['is_read']): ?>
                            <span class="badge bg-danger">New</span>
                        <?php else: ?>
                            <span class="badge bg-secondary">Read</span>
                        <?php endif; ?>
                    </td>
                    <td class="fw-semibold"><?= sanitize($msg['name']) ?></td>
                    <td><a href="mailto:<?= sanitize($msg['email']) ?>"><?= sanitize($msg['email']) ?></a></td>
                    <td><?= sanitize(substr($msg['subject'], 0, 40)) ?></td>
                    <td><small class="text-muted"><?= date('M d, Y', strtotime($msg['created_at'])) ?></small></td>
                    <td>
                        <a href="#msgModal<?= $msg['id'] ?>" class="btn btn-sm btn-info" data-bs-toggle="modal" title="View message">
                            <i class="fas fa-eye"></i>
                        </a>
                        <a href="?delete=<?= $msg['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Delete this message?')" title="Delete">
                            <i class="fas fa-trash"></i>
                        </a>
                    </td>
                </tr>

                <!-- Message Modal -->
                <div class="modal fade" id="msgModal<?= $msg['id'] ?>" tabindex="-1">
                    <div class="modal-dialog modal-lg">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">Message from <?= sanitize($msg['name']) ?></h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body">
                                <div class="mb-3">
                                    <label class="form-label fw-semibold">From:</label>
                                    <p><?= sanitize($msg['name']) ?> (<?= sanitize($msg['email']) ?>)</p>
                                </div>
                                <?php if (!empty($msg['phone'])): ?>
                                <div class="mb-3">
                                    <label class="form-label fw-semibold">Phone:</label>
                                    <p><a href="tel:<?= sanitize($msg['phone']) ?>"><?= sanitize($msg['phone']) ?></a></p>
                                </div>
                                <?php endif; ?>
                                <div class="mb-3">
                                    <label class="form-label fw-semibold">Subject:</label>
                                    <p><?= sanitize($msg['subject']) ?></p>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label fw-semibold">Message:</label>
                                    <div class="p-3 bg-light rounded border">
                                        <?= nl2br(sanitize($msg['message'])) ?>
                                    </div>
                                </div>
                                <div class="text-muted small">
                                    Received: <?= date('F d, Y \a\t g:i A', strtotime($msg['created_at'])) ?>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <a href="mailto:<?= sanitize($msg['email']) ?>" class="btn btn-primary">
                                    <i class="fas fa-reply me-2"></i>Reply via Email
                                </a>
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <!-- Pagination -->
    <?php if ($totalPages > 1): ?>
    <nav class="mt-4">
        <ul class="pagination justify-content-center">
            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                <li class="page-item <?= $i === $page ? 'active' : '' ?>">
                    <a class="page-link" href="?page=<?= $i ?>"><?= $i ?></a>
                </li>
            <?php endfor; ?>
        </ul>
    </nav>
    <?php endif; ?>
<?php endif; ?>

<?php include __DIR__ . '/partials/admin_footer.php'; ?>
