<?php
define('SECURE_ACCESS', true);

$pageTitle = "Contact Inquiries Manager";
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/auth.php';

requireAdmin();

$currentUser = getCurrentUser();

$error = '';
$success = '';

// Handle mark as read
if (isset($_GET['action']) && $_GET['action'] === 'read' && isset($_GET['id'])) {
    if (!verifyCSRFToken($_GET['csrf_token'] ?? '')) {
        $_SESSION['flash_error'] = "Security check failed (CSRF). Please try again.";
    } else {
        $id = (int)$_GET['id'];
        try {
            $stmt = $pdo->prepare("UPDATE contact_messages SET is_read = TRUE WHERE id = ?");
            $stmt->execute([$id]);
            $_SESSION['flash_success'] = "Message marked as read.";
        } catch (PDOException $e) {
            $_SESSION['flash_error'] = "Failed to update message status.";
        }
    }
    header("Location: contact_messages");
    exit();
}

// Handle delete
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    if (!verifyCSRFToken($_GET['csrf_token'] ?? '')) {
        $_SESSION['flash_error'] = "Security check failed (CSRF). Please try again.";
    } else {
        $id = (int)$_GET['id'];
        try {
            $stmt = $pdo->prepare("DELETE FROM contact_messages WHERE id = ?");
            $stmt->execute([$id]);
            $_SESSION['flash_success'] = "Inquiry deleted successfully.";
        } catch (PDOException $e) {
            $_SESSION['flash_error'] = "Failed to delete message.";
        }
    }
    header("Location: contact_messages");
    exit();
}

// Fetch messages
try {
    $messages = $pdo->query("SELECT * FROM contact_messages ORDER BY created_at DESC")->fetchAll();
} catch (PDOException $e) {
    $messages = [];
    $error = "Failed to load inquiries: " . $e->getMessage();
}

require_once __DIR__ . '/../../includes/header.php';
?>

<div class="container-fluid px-md-5 py-4">
    <!-- Header -->
    <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3 mb-4">
        <div>
            <h1 class="h2 fw-bold text-dark mb-1"><i class="bi bi-chat-left-text text-primary me-2"></i>Contact Inquiries</h1>
            <p class="text-secondary mb-0">View, manage, and respond to incoming user support inquiries.</p>
        </div>
    </div>

    <!-- Error/Success Alerts -->
    <?php if (!empty($error)): ?>
        <div class="alert alert-danger border-0 shadow-sm mb-4" role="alert">
            <i class="bi bi-x-circle-fill me-2"></i><?php echo htmlspecialchars($error); ?>
        </div>
    <?php endif; ?>

    <!-- Inquiries List Table -->
    <div class="card border-0 shadow-sm rounded-3">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0" style="font-size: 0.9rem;">
                    <thead class="table-light text-secondary font-monospace" style="font-size: 0.78rem;">
                        <tr>
                            <th class="ps-4">Sender & Date</th>
                            <th>Subject</th>
                            <th>Message Content</th>
                            <th>Status</th>
                            <th class="text-end pe-4">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($messages)): ?>
                            <tr>
                                <td colspan="5" class="text-center py-5 text-muted">
                                    <i class="bi bi-chat-left-dots fs-2 mb-2"></i>
                                    <p class="mb-0">No contact inquiries received yet.</p>
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($messages as $m): ?>
                                <tr class="<?php echo !$m['is_read'] ? 'bg-light bg-opacity-50' : ''; ?>">
                                    <td class="ps-4 py-3">
                                        <strong class="text-dark d-block"><?php echo htmlspecialchars($m['name']); ?></strong>
                                        <a href="mailto:<?php echo htmlspecialchars($m['email']); ?>" class="text-muted small text-decoration-none"><?php echo htmlspecialchars($m['email']); ?></a>
                                        <div class="text-muted font-monospace mt-1" style="font-size: 0.7rem;"><?php echo date('M d, Y H:i', strtotime($m['created_at'])); ?></div>
                                    </td>
                                    <td>
                                        <span class="<?php echo !$m['is_read'] ? 'fw-bold text-dark' : 'text-secondary'; ?>"><?php echo htmlspecialchars($m['subject']); ?></span>
                                    </td>
                                    <td style="max-width: 400px;">
                                        <p class="text-secondary small mb-0 text-truncate-2" style="white-space: pre-line;"><?php echo htmlspecialchars($m['message']); ?></p>
                                    </td>
                                    <td>
                                        <?php if ($m['is_read']): ?>
                                            <span class="badge bg-secondary bg-opacity-10 text-secondary">Read</span>
                                        <?php else: ?>
                                            <span class="badge bg-warning bg-opacity-10 text-warning border border-warning-subtle">New</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-end pe-4">
                                        <div class="btn-group">
                                            <a href="mailto:<?php echo htmlspecialchars($m['email']); ?>?subject=Re: <?php echo rawurlencode($m['subject']); ?>" class="btn btn-sm btn-outline-primary fw-bold" title="Reply via Email">
                                                <i class="bi bi-reply-fill"></i> Reply
                                            </a>
                                            <?php if (!$m['is_read']): ?>
                                                <a href="contact_messages?action=read&id=<?php echo $m['id']; ?>&csrf_token=<?php echo getCSRFToken(); ?>" class="btn btn-sm btn-outline-success fw-bold" title="Mark as Read">
                                                    <i class="bi bi-check-lg"></i>
                                                </a>
                                            <?php endif; ?>
                                            <a href="contact_messages?action=delete&id=<?php echo $m['id']; ?>&csrf_token=<?php echo getCSRFToken(); ?>" 
                                               class="btn btn-sm btn-outline-danger"
                                               onclick="return confirm('Are you sure you want to delete this message?');"
                                               title="Delete">
                                                <i class="bi bi-trash"></i>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php
require_once __DIR__ . '/../../includes/footer.php';
?>
