<?php

require_once __DIR__ . '/../app/auth.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/../app/contact-messages.php';

$user = sparrow_require_backyard_login();
$message_id = (int) ($_GET['id'] ?? $_POST['message_id'] ?? 0);
$notice = '';
$error = '';

$message = $message_id > 0 ? sparrow_get_contact_message($message_id) : null;

if (!$message) {
    http_response_code(404);
    sparrow_backyard_header('Message Not Found');
    ?>
    <section class="card">
        <h1>Message Not Found</h1>
        <p class="muted">That contact message could not be found.</p>
        <a class="button button-secondary" href="<?php echo sparrow_escape(sparrow_url('/backyard/messages.php')); ?>">Back to Messages</a>
    </section>
    <?php
    sparrow_backyard_footer();
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $new_status = $action === 'mark_new' ? 'New' : ($action === 'mark_read' ? 'Read' : '');

    if ($new_status !== '') {
        try {
            sparrow_update_contact_message_status($message_id, $new_status);
            sparrow_redirect('/backyard/message-view.php?id=' . $message_id . '&updated=1');
        } catch (Throwable $e) {
            error_log('Contact message status could not be updated: ' . $e->getMessage());
            $error = 'The message status could not be updated.';
        }
    }
}

if (($message['status'] ?? 'New') === 'New' && $_SERVER['REQUEST_METHOD'] !== 'POST') {
    try {
        sparrow_update_contact_message_status($message_id, 'Read');
        $message['status'] = 'Read';
    } catch (Throwable $e) {
        error_log('Contact message could not be marked read: ' . $e->getMessage());
    }
}

if (($_GET['updated'] ?? '') === '1') {
    $notice = 'Message status updated.';
    $message = sparrow_get_contact_message($message_id) ?? $message;
}

sparrow_backyard_header('View Message');
?>

<style>
.message-meta {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 16px;
}

.message-body {
    margin-top: 20px;
    padding: 18px;
    border: 1px solid var(--sparrow-border);
    border-radius: 14px;
    background: #fffbfd;
    font-size: 13px;
    line-height: 1.65;
}

.message-actions {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    align-items: center;
}

.message-actions form {
    margin: 0;
}

@media (max-width: 700px) {
    .message-meta {
        grid-template-columns: 1fr;
    }
}
</style>

<?php if ($notice): ?>
    <div class="notice-success"><?php echo sparrow_escape($notice); ?></div>
<?php endif; ?>

<?php if ($error): ?>
    <div class="notice-error"><?php echo sparrow_escape($error); ?></div>
<?php endif; ?>

<section class="card">
    <div class="page-heading-row">
        <div>
            <h1><?php echo sparrow_escape($message['subject'] ?? 'Message'); ?></h1>
            <p class="muted">
                Received <?php echo sparrow_escape(date('M j, Y g:i A', strtotime((string) $message['created_at']))); ?>
            </p>
        </div>

        <div class="message-actions">
            <a class="button button-secondary" href="<?php echo sparrow_escape(sparrow_url('/backyard/messages.php')); ?>">Back to Messages</a>

            <form method="post">
                <input type="hidden" name="message_id" value="<?php echo (int) $message_id; ?>">
                <?php if (($message['status'] ?? '') === 'New'): ?>
                    <input type="hidden" name="action" value="mark_read">
                    <button type="submit" class="button">Mark Read</button>
                <?php else: ?>
                    <input type="hidden" name="action" value="mark_new">
                    <button type="submit" class="button">Mark New</button>
                <?php endif; ?>
            </form>
        </div>
    </div>
</section>

<section class="card">
    <div class="message-meta">
        <div>
            <div class="detail-label">Name</div>
            <div class="detail-value"><?php echo sparrow_escape($message['name'] ?? ''); ?></div>
        </div>

        <div>
            <div class="detail-label">Status</div>
            <div class="detail-value"><?php echo sparrow_escape($message['status'] ?? 'Read'); ?></div>
        </div>

        <div>
            <div class="detail-label">Email</div>
            <div class="detail-value">
                <a href="mailto:<?php echo sparrow_escape($message['email'] ?? ''); ?>"><?php echo sparrow_escape($message['email'] ?? ''); ?></a>
            </div>
        </div>

        <div>
            <div class="detail-label">Phone</div>
            <div class="detail-value">
                <?php if (!empty($message['phone'])): ?>
                    <a href="tel:<?php echo sparrow_escape(preg_replace('/[^0-9+]/', '', (string) $message['phone'])); ?>"><?php echo sparrow_escape($message['phone']); ?></a>
                <?php else: ?>
                    <span class="muted">Not provided</span>
                <?php endif; ?>
            </div>
        </div>

        <div>
            <div class="detail-label">Preferred Contact</div>
            <div class="detail-value"><?php echo sparrow_escape($message['preferred_contact'] ?? 'Email'); ?></div>
        </div>
    </div>

    <div class="message-body"><?php echo nl2br(sparrow_escape($message['message'] ?? '')); ?></div>
</section>

<?php sparrow_backyard_footer(); ?>
