<?php
/**
 * Inbox — Universal messaging. All staff & admin can message anyone.
 */
require_auth();
$method = $_SERVER['REQUEST_METHOD'];
$d = input();
$user = current_user();
$pdo = db();

// Auto-ensure the user is in the message_thread_users table if they open a thread
function ensure_thread_access(PDO $pdo, int $threadId, int $userId): void {
    $pdo->prepare('INSERT IGNORE INTO message_thread_users (thread_id, user_id) VALUES (?,?)')
        ->execute([$threadId, $userId]);
}

if ($method === 'GET') {
    // ALL authenticated users can view inbox — no special permission required
    if (!hv4_table_exists('message_threads')) {
        json_ok(['threads' => [], 'migration_required' => true]);
    }

    // If viewing a specific thread, auto-add the user so they can see it
    if (!empty($d['thread_id'])) {
        $tid = (int)$d['thread_id'];
        ensure_thread_access($pdo, $tid, (int)$user['id']);
        $msgs = $pdo->prepare('SELECT m.*, u.name AS user_name, u.role_id FROM messages m LEFT JOIN users u ON u.id=m.user_id WHERE m.thread_id=? ORDER BY m.id ASC LIMIT 200');
        $msgs->execute([$tid]);
        $pdo->prepare('UPDATE message_thread_users SET last_read_at=NOW() WHERE thread_id=? AND user_id=?')->execute([$tid, $user['id']]);
        json_ok(['thread' => $tid, 'messages' => $msgs->fetchAll()]);
    }

    // List threads this user belongs to, or ALL threads if admin
    $isAdmin = has_permission('users.manage') || in_array($user['role_name'] ?? '', ['super_admin', 'admin'], true);
    if ($isAdmin) {
        // Admins see all threads
        $threads = $pdo->prepare('
            SELECT t.*, 
                (SELECT body FROM messages m WHERE m.thread_id=t.id ORDER BY m.id DESC LIMIT 1) AS last_message,
                (SELECT COUNT(*) FROM messages m WHERE m.thread_id=t.id) AS message_count,
                (SELECT u.name FROM users u WHERE u.id=t.created_by) AS created_by_name
            FROM message_threads t
            ORDER BY t.created_at DESC LIMIT 100');
        $threads->execute([]);
    } else {
        // Staff see only threads they are part of
        $threads = $pdo->prepare('
            SELECT t.*, 
                (SELECT body FROM messages m WHERE m.thread_id=t.id ORDER BY m.id DESC LIMIT 1) AS last_message,
                (SELECT COUNT(*) FROM messages m WHERE m.thread_id=t.id) AS message_count,
                (SELECT u.name FROM users u WHERE u.id=t.created_by) AS created_by_name
            FROM message_threads t
            LEFT JOIN message_thread_users tu ON tu.thread_id=t.id AND tu.user_id=?
            WHERE tu.user_id IS NOT NULL
            ORDER BY t.created_at DESC LIMIT 100');
        $threads->execute([$user['id']]);
    }
    $list = $threads->fetchAll();

    // Get all users (for "New Message" recipient selector on frontend)
    $allUsers = $pdo->query('SELECT id, name, email, role_id FROM users WHERE deleted_at IS NULL AND status="active" ORDER BY name')->fetchAll();
    json_ok(['threads' => $list, 'users' => $allUsers]);
}

csrf_check();

if ($method === 'POST') {
    // ALL authenticated users can send messages
    if (!hv4_table_exists('message_threads')) json_error('Messaging not ready. Run migrations.', 503);

    // Reply to an existing thread
    if (!empty($d['thread_id'])) {
        $tid = (int)$d['thread_id'];
        $body = trim((string)($d['body'] ?? ''));
        if ($body === '') json_error('Message body is required', 422);
        ensure_thread_access($pdo, $tid, (int)$user['id']);
        $pdo->prepare('INSERT INTO messages (thread_id, user_id, body) VALUES (?,?,?)')->execute([$tid, $user['id'], $body]);
        $mid = (int)$pdo->lastInsertId();
        if (function_exists('hv4_emit_event')) hv4_emit_event('message.sent', ['thread_id' => $tid, 'message_id' => $mid], 'message', $mid);
        if (function_exists('hv4_queue_outbound_sync')) hv4_queue_outbound_sync('message.sent', ['thread_id' => $tid, 'message_id' => $mid]);
        json_ok(['id' => $mid], 'Sent');
    }

    // Create new thread
    $subject = v_str($d, 'subject', 190) ?: 'New conversation';
    $type = v_enum($d['thread_type'] ?? 'staff', ['staff', 'guest', 'maintenance', 'ops'], 'thread_type');
    $pdo->prepare('INSERT INTO message_threads (thread_type, subject, property_id, created_by) VALUES (?,?,?,?)')
        ->execute([$type, $subject, !empty($d['property_id']) ? (int)$d['property_id'] : null, $user['id']]);
    $tid = (int)$pdo->lastInsertId();

    // Auto-add the creator
    $pdo->prepare('INSERT IGNORE INTO message_thread_users (thread_id, user_id) VALUES (?,?)')->execute([$tid, $user['id']]);

    // Add recipients — everyone in the recipients array
    $recipients = $d['recipients'] ?? [];
    if (!is_array($recipients)) $recipients = [];
    foreach ($recipients as $rid) {
        $rid = (int)$rid;
        if ($rid && $rid !== (int)$user['id']) {
            $pdo->prepare('INSERT IGNORE INTO message_thread_users (thread_id, user_id) VALUES (?,?)')->execute([$tid, $rid]);
        }
    }

    // Send the first message if provided
    if (!empty($d['body'])) {
        $pdo->prepare('INSERT INTO messages (thread_id, user_id, body) VALUES (?,?,?)')->execute([$tid, $user['id'], trim($d['body'])]);
        $mid = (int)$pdo->lastInsertId();
        if (function_exists('hv4_emit_event')) hv4_emit_event('message.sent', ['thread_id' => $tid, 'message_id' => $mid], 'message', $mid);
    }

    json_ok(['thread_id' => $tid], 'Thread created');
}

json_error('Method not allowed', 405);
