<?php
// --- LOGIC BLOCK: All PHP processing and potential redirects must happen before any HTML is sent ---
require_once '../includes/db.php';
require_once '../includes/helpers.php'; 

// 1. Initial Security Check & User Data Fetch
if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'customer') {
    header("Location: ../login.php"); exit();
}
$user_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id); $stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
if (!$user) { session_destroy(); header("Location: ../login.php"); exit(); }

// 2. Get URL parameters
$booking_id = intval($_GET['booking_id'] ?? 0);
$booking_type = filter_var($_GET['booking_type'] ?? '', FILTER_SANITIZE_STRING);
$conversation_title = "My Messages";

// 3. Security Check: If a specific conversation is requested, verify it belongs to the user.
if ($booking_id > 0 && !empty($booking_type)) {
    $table_map = ['tour' => 'bookings', 'hotel' => 'hotel_bookings', 'flight' => 'flight_bookings', 'ferry' => 'ferry_bookings'];
    if (array_key_exists($booking_type, $table_map)) {
        $booking_table = $table_map[$booking_type];
        $check_stmt = $conn->prepare("SELECT id FROM `$booking_table` WHERE id = ? AND user_id = ?");
        $check_stmt->bind_param("ii", $booking_id, $user_id);
        $check_stmt->execute();
        if ($check_stmt->get_result()->num_rows === 0) {
            header("Location: index.php"); exit(); // Redirect if not their booking
        }
    } else {
        header("Location: index.php"); exit(); // Redirect if booking type is invalid
    }
}

// 4. CRUD: Handle sending a new message
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['send_message'])) {
    $message_text = trim(strip_tags($_POST['message_text']));
    if (!empty($message_text) && $booking_id > 0) {
        $admin_id = 1; // Assume admin ID is 1
        $stmt = $conn->prepare("INSERT INTO messages (booking_id, booking_type, sender_id, recipient_id, message_text, is_notified) VALUES (?, ?, ?, ?, ?, 0)");
        $stmt->bind_param("issis", $booking_id, $booking_type, $user_id, $admin_id, $message_text);
        $stmt->execute();
        // Redirect to the same page to show the new message and prevent form resubmission
        header("Location: view-messages.php?booking_id=$booking_id&booking_type=$booking_type");
        exit();
    }
}

// 5. Data Fetching for Display
// Mark messages in the current thread as read (only if viewing a specific conversation)
if ($booking_id > 0 && !empty($booking_type)) {
    $conn->query("UPDATE messages SET is_read = 1 WHERE booking_id = $booking_id AND booking_type = '$booking_type' AND recipient_id = $user_id");
    $conversation_title = "Conversation for " . ucfirst($booking_type) . " Booking #" . $booking_id;
}

// Fetch messages for the current view (single conversation or inbox)
$messages_result = null; $conversations = [];
if ($booking_id > 0) {
    $messages_result = $conn->query("SELECT * FROM messages WHERE booking_id = $booking_id AND booking_type = '$booking_type' ORDER BY created_at ASC");
} else {
    $sql_inbox = "SELECT m.*, (SELECT COUNT(*) FROM messages um WHERE um.booking_id = m.booking_id AND um.booking_type = m.booking_type AND um.is_read = 0 AND um.recipient_id = ?) as unread_count, CASE WHEN m.booking_type = 'tour' THEN (SELECT title FROM tours t WHERE t.id = m.booking_id) WHEN m.booking_type = 'hotel' THEN (SELECT name FROM hotels h WHERE h.id = m.booking_id) WHEN m.booking_type = 'flight' THEN 'Flight Request' WHEN m.booking_type = 'ferry' THEN 'Ferry Request' END as conversation_subject FROM messages m WHERE m.id IN (SELECT MAX(id) FROM messages WHERE sender_id = ? OR recipient_id = ? GROUP BY booking_id, booking_type) ORDER BY m.created_at DESC";
    $stmt_inbox = $conn->prepare($sql_inbox);
    $stmt_inbox->bind_param("iii", $user_id, $user_id, $user_id);
    $stmt_inbox->execute();
    $conversations = $stmt_inbox->get_result()->fetch_all(MYSQLI_ASSOC);
}
// --- END OF LOGIC BLOCK ---

// --- PRESENTATION BLOCK STARTS HERE ---
include 'header.php'; 
?>
<style>
    .chat-container { display: flex; flex-direction: column; height: 60vh; }
    .chat-messages { flex-grow: 1; overflow-y: auto; padding: 1rem; }
    .message { margin-bottom: 1rem; display: flex; max-width: 75%; align-items: flex-end; }
    .message-content { padding: 0.75rem 1rem; border-radius: 1rem; word-break: break-word; }
    .message-sent { margin-left: auto; flex-direction: row-reverse; }
    .message-sent .message-content { background-color: var(--primary-color); color: white; border-bottom-right-radius: 0; }
    .message-received { margin-right: auto; }
    .message-received .message-content { background-color: #e9ecef; border-bottom-left-radius: 0; }
    .message-time { font-size: 0.75rem; color: #6c757d; margin-top: 2px; }
</style>

<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"><?php echo $conversation_title; ?></h1>
</div>

<?php if ($booking_id > 0): // Single Conversation View ?>
<div class="card shadow-sm">
    <div class="chat-container">
        <div class="chat-messages" id="chat-box">
            <?php if ($messages_result && $messages_result->num_rows > 0): while ($msg = $messages_result->fetch_assoc()): ?>
                <div class="message <?php echo ($msg['sender_id'] == $user_id) ? 'message-sent' : 'message-received'; ?>">
                    <div class="message-content">
                        <?php echo nl2br(htmlspecialchars($msg['message_text'])); ?>
                        <div class="text-end text-muted mt-1 message-time"><?php echo time_ago($msg['created_at']); ?></div>
                    </div>
                </div>
            <?php endwhile; else: ?>
                <p class="text-center text-muted">No messages in this conversation yet. Send the first message below.</p>
            <?php endif; ?>
        </div>
        <div class="card-footer">
            <form method="POST"><div class="input-group"><textarea name="message_text" class="form-control" placeholder="Type your message..." required></textarea><button type="submit" name="send_message" class="btn btn-primary">Send</button></div></form>
        </div>
    </div>
</div>
<script>
    const chatBox = document.getElementById('chat-box');
    if(chatBox) { chatBox.scrollTop = chatBox.scrollHeight; }
</script>

<?php else: // Main Inbox View ?>
    <div class="card shadow-sm">
        <div class="list-group list-group-flush">
            <?php if (!empty($conversations)): foreach($conversations as $convo): ?>
                <a href="?booking_id=<?php echo $convo['booking_id']; ?>&booking_type=<?php echo $convo['booking_type']; ?>" class="list-group-item list-group-item-action <?php if($convo['unread_count'] > 0) echo 'fw-bold'; ?>">
                    <div class="d-flex w-100 justify-content-between">
                        <h5 class="mb-1"><?php echo htmlspecialchars($convo['conversation_subject'] ?? 'Conversation'); ?></h5>
                        <small><?php echo time_ago($convo['created_at']); ?></small>
                    </div>
                    <p class="mb-1 text-muted"><?php echo htmlspecialchars(substr($convo['message_text'], 0, 100)); ?>...</p>
                </a>
            <?php endforeach; else: ?>
                <div class="list-group-item text-center text-muted p-4">You have no message conversations yet.</div>
            <?php endif; ?>
        </div>
    </div>
<?php endif; ?>

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