<?php
// STEP 1: Include the header, which handles all security and setup.
require_once 'header.php'; 
$page_title = 'Start New Conversation';

// --- Handle Form Submission ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $subject = trim($_POST['subject'] ?? '');
    $body = trim($_POST['body'] ?? '');

    // Basic validation
    if (!empty($subject) && !empty($body)) {
        // Use a transaction to ensure both queries succeed or neither do.
        $conn->begin_transaction();
        try {
            // 1. Create the new conversation thread
            $stmt_convo = $conn->prepare("INSERT INTO conversations (user_id, subject) VALUES (?, ?)");
            $stmt_convo->bind_param("is", $user_id, $subject);
            $stmt_convo->execute();
            $conversation_id = $conn->insert_id; // Get the ID of the new conversation
            $stmt_convo->close();

            // 2. Insert the first message into that conversation thread
            $stmt_msg = $conn->prepare("INSERT INTO messages (conversation_id, sender_id, sender_type, body) VALUES (?, ?, 'user', ?)");
            $stmt_msg->bind_param("iis", $conversation_id, $user_id, $body);
            $stmt_msg->execute();
            $stmt_msg->close();

            // If both queries were successful, commit the transaction
            $conn->commit();

            // Set a success message and redirect to the new chat view
            $_SESSION['success_message'] = "Your message has been sent successfully.";
            header("Location: view-messages.php?id=" . $conversation_id);
            exit();

        } catch (mysqli_sql_exception $exception) {
            $conn->rollback(); // Roll back the transaction on error
            // You can log the error here if needed
            $error_message = "There was an error sending your message. Please try again.";
        }
    } else {
        $error_message = "Please fill out both the subject and the message fields.";
    }
}
?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2"><i class="bi bi-plus-circle-fill me-2"></i>Start New Conversation</h1>
    <a href="messages.php" class="btn btn-outline-secondary"><i class="bi bi-arrow-left"></i> Back to Messages</a>
</div>

<?php if (isset($error_message)): ?>
<div class="alert alert-danger" role="alert">
    <?php echo $error_message; ?>
</div>
<?php endif; ?>

<div class="row justify-content-center">
    <div class="col-lg-8">
        <div class="card shadow-sm border-0">
            <div class="card-body p-4">
                <form method="POST">
                    <div class="mb-3">
                        <label for="subject" class="form-label">Subject</label>
                        <input type="text" class="form-control" id="subject" name="subject" placeholder="e.g., Question about my booking" required>
                    </div>
                    <div class="mb-3">
                        <label for="body" class="form-label">Your Message</label>
                        <textarea class="form-control" id="body" name="body" rows="8" placeholder="Please provide as much detail as possible..." required></textarea>
                    </div>
                    <div class="d-grid">
                        <button type="submit" class="btn btn-primary btn-lg">
                            <i class="bi bi-send-fill me-2"></i>Submit Inquiry
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>


<?php require_once 'footer.php'; ?>
