<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/layout.php';

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

$id = (int)($_GET['id'] ?? 0);

$allowedStatuses = ['new', 'read', 'responded', 'archived'];

$successMessage = '';
$errorMessage = '';

if ($id <= 0) {
    echo '<div class="admin-message error">Invalid enquiry ID.</div>';
    require_once __DIR__ . '/includes/footer.php';
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $newStatus = trim($_POST['status'] ?? '');

    if (!in_array($newStatus, $allowedStatuses, true)) {
        $errorMessage = 'Please select a valid status.';
    } else {
        try {
            $updateStmt = $pdo->prepare("
                UPDATE contact_enquiries
                SET status = :status
                WHERE id = :id
            ");

            $updateStmt->execute([
                ':status' => $newStatus,
                ':id' => $id
            ]);

            $successMessage = 'Enquiry status updated.';
        } catch (PDOException $e) {
            $errorMessage = 'Unable to update enquiry status.';
        }
    }
}

try {
    $stmt = $pdo->prepare("
        SELECT 
            id,
            name,
            email,
            company,
            enquiry_type,
            subject,
            message,
            status,
            created_at
        FROM contact_enquiries
        WHERE id = :id
        LIMIT 1
    ");

    $stmt->execute([':id' => $id]);
    $enquiry = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$enquiry) {
        echo '<div class="admin-message error">Enquiry not found.</div>';
        require_once __DIR__ . '/includes/footer.php';
        exit;
    }

    if ($enquiry['status'] === 'new' && $_SERVER['REQUEST_METHOD'] !== 'POST') {
        $markReadStmt = $pdo->prepare("
            UPDATE contact_enquiries
            SET status = 'read'
            WHERE id = :id
            AND status = 'new'
        ");

        $markReadStmt->execute([':id' => $id]);
        $enquiry['status'] = 'read';
    }
} catch (PDOException $e) {
    echo '<div class="admin-message error">Unable to load enquiry.</div>';
    require_once __DIR__ . '/includes/footer.php';
    exit;
}

function statusBadgeClass(string $status): string
{
    return match ($status) {
        'new' => 'badge-new',
        'read' => 'badge-read',
        'responded' => 'badge-responded',
        'archived' => 'badge-archived',
        default => 'badge-read'
    };
}
?>

<div class="admin-page-header">
    <div>
        <h1>Contact Enquiry</h1>
        <p>View the full message and update its status.</p>
    </div>

    <a href="contact-enquiries.php" class="admin-back-link">Back to enquiries</a>
</div>

<?php if ($successMessage !== ''): ?>
    <div class="admin-message success">
        <?php echo htmlspecialchars($successMessage, ENT_QUOTES, 'UTF-8'); ?>
    </div>
<?php endif; ?>

<?php if ($errorMessage !== ''): ?>
    <div class="admin-message error">
        <?php echo htmlspecialchars($errorMessage, ENT_QUOTES, 'UTF-8'); ?>
    </div>
<?php endif; ?>

<div class="enquiry-layout">

    <div class="enquiry-card">
        <h2><?php echo htmlspecialchars($enquiry['subject'], ENT_QUOTES, 'UTF-8'); ?></h2>

        <div class="enquiry-message">
            <?php echo nl2br(htmlspecialchars($enquiry['message'], ENT_QUOTES, 'UTF-8')); ?>
        </div>
    </div>

    <aside class="enquiry-card">
        <h2>Details</h2>

        <ul class="meta-list">
            <li>
                <strong>Status</strong>
                <span class="status-badge <?php echo htmlspecialchars(statusBadgeClass($enquiry['status']), ENT_QUOTES, 'UTF-8'); ?>">
                    <?php echo htmlspecialchars($enquiry['status'], ENT_QUOTES, 'UTF-8'); ?>
                </span>
            </li>

            <li>
                <strong>Received</strong>
                <?php echo htmlspecialchars(date('d M Y, H:i', strtotime($enquiry['created_at'])), ENT_QUOTES, 'UTF-8'); ?>
            </li>

            <li>
                <strong>Name</strong>
                <?php echo htmlspecialchars($enquiry['name'], ENT_QUOTES, 'UTF-8'); ?>
            </li>

            <li>
                <strong>Email</strong>
                <a href="mailto:<?php echo htmlspecialchars($enquiry['email'], ENT_QUOTES, 'UTF-8'); ?>">
                    <?php echo htmlspecialchars($enquiry['email'], ENT_QUOTES, 'UTF-8'); ?>
                </a>
            </li>

            <?php if (!empty($enquiry['company'])): ?>
                <li>
                    <strong>Company / Website</strong>
                    <?php echo htmlspecialchars($enquiry['company'], ENT_QUOTES, 'UTF-8'); ?>
                </li>
            <?php endif; ?>

            <li>
                <strong>Enquiry Type</strong>
                <?php echo htmlspecialchars($enquiry['enquiry_type'], ENT_QUOTES, 'UTF-8'); ?>
            </li>

            <li>
                <strong>Subject</strong>
                <?php echo htmlspecialchars($enquiry['subject'], ENT_QUOTES, 'UTF-8'); ?>
            </li>
        </ul>

        <form method="post" action="contact-enquiry.php?id=<?php echo (int)$enquiry['id']; ?>" class="status-form">
            <label for="status">Update status</label>

            <select id="status" name="status">
                <?php foreach ($allowedStatuses as $allowedStatus): ?>
                    <option
                        value="<?php echo htmlspecialchars($allowedStatus, ENT_QUOTES, 'UTF-8'); ?>"
                        <?php echo $enquiry['status'] === $allowedStatus ? 'selected' : ''; ?>
                    >
                        <?php echo ucfirst($allowedStatus); ?>
                    </option>
                <?php endforeach; ?>
            </select>

            <button type="submit" class="admin-btn">Save status</button>
        </form>
    </aside>

</div>

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