<?php
include '../includes/conn.php';

// Start session
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Unauthorized access protection
if ($_SERVER['REQUEST_METHOD'] === 'POST' || $_SERVER['REQUEST_METHOD'] === 'GET') {
    $action = $_GET['action'] ?? $_POST['action'] ?? '';
    if ($action && !isset($_SESSION['user_id'])) {
        header('Content-Type: application/json');
        http_response_code(401);
        echo json_encode(['error' => 'Unauthorized']);
        exit();
    }
}

// Get current user
function current_user() {
    global $pdo;
    if (isset($_SESSION['user_id'])) {
        $stmt = $pdo->prepare("SELECT id, username, first_name, last_name, email, role, photo FROM users WHERE id = ?");
        $stmt->execute([$_SESSION['user_id']]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }
    return null;
}

// Render threaded messages
function render_threaded_messages($messages, $is_sent = false) {
    if (empty($messages)) {
        echo '<div class="p-5 text-center text-muted"><i class="fas fa-envelope-open fa-5x mb-4"></i><h4>No messages found</h4></div>';
        return;
    }

    $threads = [];
    foreach ($messages as $msg) {
        $thread_key = $msg['thread_id'] ?: $msg['id'];
        $threads[$thread_key][] = $msg;
    }

    // Sort threads by latest message
    uasort($threads, fn($a, $b) => strtotime(end($b)['timestamp']) <=> strtotime(end($a)['timestamp']));

    foreach ($threads as $thread_key => $thread_msgs) {
        usort($thread_msgs, fn($a, $b) => strtotime($a['timestamp']) <=> strtotime($b['timestamp']));

        $latest = end($thread_msgs);
        $count = count($thread_msgs);
        $sender_name = trim($latest['first_name'] . ' ' . $latest['last_name']);
        $initials = strtoupper(substr($latest['first_name'], 0, 1) . substr($latest['last_name'], 0, 1));
        $snippet = substr(strip_tags($latest['body']), 0, 100) . (strlen(strip_tags($latest['body'])) > 100 ? '...' : '');
        $unread_class = $latest['is_read'] ? '' : 'unread';
        $star_class = $latest['is_starred'] ? 'fas fa-star text-warning' : 'far fa-star text-muted';
        $label = $is_sent ? "To: $sender_name" : $sender_name;

        echo "
        <div class='thread-header message-row p-3 $unread_class position-relative' data-thread-id='$thread_key'>
            <input type='checkbox' class='form-check-input message-checkbox position-sticky top-50 start-0 translate-middle-y ms-3'>
            <div class='avatar-placeholder me-3'>$initials</div>
            <div class='flex-grow-1'>
                <strong>$label</strong>&nbsp;&nbsp;
                <span class='text-dark'>{$latest['subject']}</span>&nbsp;&nbsp;
                <span class='text-muted'>- $snippet</span>
                " . ($count > 1 ? "<span class='badge bg-secondary ms-2'>($count)</span>" : "") . "
            </div>
            <div class='text-muted small'>{$latest['timestamp']}</div>
            <i class='$star_class star-btn me-3' style='cursor:pointer;' data-msg-id='$thread_key'></i>
        </div>

        <div class='thread-body bg-light' style='display:none;'>
            <div class='p-4'>";

        foreach ($thread_msgs as $msg) {
            $msg_sender = trim($msg['first_name'] . ' ' . $msg['last_name']);
            $msg_time = $msg['timestamp'];

            echo "
            <div class='card mb-3 border-0 shadow-sm'>
                <div class='card-body'>
                    <div class='d-flex justify-content-between align-items-start mb-3'>
                        <div>
                            <strong>From: $msg_sender</strong>
                            <small class='text-muted ms-3'>$msg_time</small>
                        </div>
                        <button class='btn btn-sm btn-outline-primary reply-btn' 
                                data-id='{$msg['id']}' 
                                data-sender='{$msg['sender_id']}'
                                data-subject='" . htmlspecialchars($msg['subject'], ENT_QUOTES) . "'
                                data-sender-name='" . htmlspecialchars($msg_sender, ENT_QUOTES) . "'>
                            <i class='fas fa-reply'></i> Reply
                        </button>
                    </div>
                    <h6>{$msg['subject']}</h6>
                    <div class='mt-3'>{$msg['body']}</div>
                </div>
            </div>";
        }

        echo "</div></div>";
    }
}
// AJAX Handler
if ($_SERVER['REQUEST_METHOD'] === 'POST' || $_SERVER['REQUEST_METHOD'] === 'GET') {
    $action = $_GET['action'] ?? $_POST['action'] ?? '';

    switch ($action) {
        case 'send_message':
            $sender = current_user();
            $sender_id = $sender['id'];

            $receiver_id = (int)($_POST['receiver_id'] ?? 0);
            $subject = trim($_POST['subject'] ?? '');
            $body = trim($_POST['body'] ?? '');
            $reply_to = !empty($_POST['reply_to']) ? (int)$_POST['reply_to'] : null;

            if (!$receiver_id || !$subject || !$body) {
                echo json_encode(['success' => false, 'message' => 'Missing required fields']);
                exit();
            }

            // Save internal message
            $stmt = $pdo->prepare("INSERT INTO messages (sender_id, receiver_id, subject, body, parent_id, timestamp) VALUES (?, ?, ?, ?, ?, NOW())");
            $stmt->execute([$sender_id, $receiver_id, $subject, $body, $reply_to]);
            $new_id = $pdo->lastInsertId();

            // Threading
            if ($reply_to) {
                $stmt = $pdo->prepare("SELECT thread_id FROM messages WHERE id = ?");
                $stmt->execute([$reply_to]);
                $parent = $stmt->fetch(PDO::FETCH_ASSOC);
                $thread_id = $parent['thread_id'] ?? $reply_to;
            } else {
                $thread_id = $new_id;
            }
            $pdo->prepare("UPDATE messages SET thread_id = ? WHERE id = ?")->execute([$thread_id, $new_id]);

            echo json_encode(['success' => true]);
            exit();    

        case 'mark_read':
            $msg_id = (int)($_POST['msg_id'] ?? 0);
            if ($msg_id > 0) {
                $stmt = $pdo->prepare("UPDATE messages SET is_read = 1 WHERE id = ? AND receiver_id = ?");
                $stmt->execute([$msg_id, $_SESSION['user_id']]);
            }
            echo json_encode(['success' => true]);
            exit();

        case 'get_unread_count':
            $stmt = $pdo->prepare("SELECT COUNT(*) AS count FROM messages WHERE receiver_id = ? AND is_read = 0 AND is_deleted = 0");
            $stmt->execute([$_SESSION['user_id']]);
            $row = $stmt->fetch();
            echo json_encode(['count' => (int)$row['count']]);
            exit();

        case 'get_inbox':
            header('Content-Type: text/html');
            $stmt = $pdo->prepare("
                SELECT m.id, m.thread_id, m.parent_id, m.subject, m.body, m.timestamp, m.is_read, m.is_starred,
                       u.first_name, u.last_name, m.sender_id
                FROM messages m
                JOIN users u ON m.sender_id = u.id
                WHERE m.receiver_id = ? AND m.is_deleted = 0
                ORDER BY m.thread_id DESC, m.timestamp ASC
            ");
            $stmt->execute([$_SESSION['user_id']]);
            render_threaded_messages($stmt->fetchAll());
            exit();

        case 'get_sent':
            header('Content-Type: text/html');
            $stmt = $pdo->prepare("
                SELECT m.id, m.thread_id, m.parent_id, m.subject, m.body, m.timestamp, m.is_read, m.is_starred,
                       u.first_name, u.last_name, m.sender_id
                FROM messages m
                JOIN users u ON m.receiver_id = u.id
                WHERE m.sender_id = ? AND m.is_deleted = 0
                ORDER BY m.thread_id DESC, m.timestamp ASC
            ");
            $stmt->execute([$_SESSION['user_id']]);
            render_threaded_messages($stmt->fetchAll(), true);
            exit();

        case 'get_starred':
            header('Content-Type: text/html');
            $stmt = $pdo->prepare("
                SELECT m.id, m.thread_id, m.parent_id, m.subject, m.body, m.timestamp, m.is_read, m.is_starred,
                       u.first_name, u.last_name, m.sender_id
                FROM messages m
                JOIN users u ON m.sender_id = u.id
                WHERE (m.receiver_id = ? OR m.sender_id = ?)
                  AND m.is_starred = 1 AND m.is_deleted = 0
                ORDER BY m.thread_id DESC, m.timestamp ASC
            ");
            $stmt->execute([$_SESSION['user_id'], $_SESSION['user_id']]);
            render_threaded_messages($stmt->fetchAll());
            exit();

        case 'get_trash':
            header('Content-Type: text/html');
            $stmt = $pdo->prepare("
                SELECT m.id, m.thread_id, m.parent_id, m.subject, m.body, m.timestamp, m.is_read, m.is_starred,
                       u.first_name, u.last_name, m.sender_id
                FROM messages m
                JOIN users u ON m.sender_id = u.id
                WHERE (m.receiver_id = ? OR m.sender_id = ?)
                  AND m.is_deleted = 1
                ORDER BY m.timestamp DESC
            ");
            $stmt->execute([$_SESSION['user_id'], $_SESSION['user_id']]);
            render_threaded_messages($stmt->fetchAll());
            exit();

        case 'toggle_star':
            $msg_id = (int)($_POST['msg_id'] ?? 0);
            if ($msg_id > 0) {
                $stmt = $pdo->prepare("UPDATE messages SET is_starred = NOT is_starred WHERE id = ? AND (sender_id = ? OR receiver_id = ?)");
                $stmt->execute([$msg_id, $_SESSION['user_id'], $_SESSION['user_id']]);
                echo json_encode(['success' => true]);
            } else {
                echo json_encode(['success' => false]);
            }
            exit();

        case 'move_to_trash':
        case 'permanent_delete':
        case 'restore_from_trash':
            $msg_ids = $_POST['msg_ids'] ?? [$_POST['msg_id'] ?? 0];
            if (!is_array($msg_ids)) $msg_ids = [$msg_ids];
            $msg_ids = array_filter(array_map('intval', $msg_ids));

            if (!empty($msg_ids)) {
                $placeholders = str_repeat('?,', count($msg_ids) - 1) . '?';

                if ($action === 'move_to_trash') {
                    $sql = "UPDATE messages SET is_deleted = 1 WHERE id IN ($placeholders) AND (sender_id = ? OR receiver_id = ?)";
                } elseif ($action === 'permanent_delete') {
                    $sql = "DELETE FROM messages WHERE id IN ($placeholders) AND is_deleted = 1 AND (sender_id = ? OR receiver_id = ?)";
                } elseif ($action === 'restore_from_trash') {
                    $sql = "UPDATE messages SET is_deleted = 0 WHERE id IN ($placeholders) AND (sender_id = ? OR receiver_id = ?)";
                }

                $params = array_merge($msg_ids, [$_SESSION['user_id'], $_SESSION['user_id']]);
                $pdo->prepare($sql)->execute($params);
            }
            echo json_encode(['success' => true]);
            exit();

        case 'search':
            header('Content-Type: text/html');
            $q = trim($_GET['q'] ?? '');
            if (strlen($q) < 2) {
                echo '<div class="p-5 text-center text-muted">Type at least 2 characters to search</div>';
                exit();
            }
            $query = '%' . $q . '%';
            $stmt = $pdo->prepare("
                SELECT m.id, m.thread_id, m.parent_id, m.subject, m.body, m.timestamp, m.is_read, m.is_starred,
                       u.first_name, u.last_name, m.sender_id
                FROM messages m
                JOIN users u ON m.sender_id = u.id
                WHERE m.receiver_id = ? AND m.is_deleted = 0
                  AND (m.subject LIKE ? OR m.body LIKE ? OR CONCAT(u.first_name,' ',u.last_name) LIKE ?)
                ORDER BY m.thread_id DESC, m.timestamp ASC
            ");
            $stmt->execute([$_SESSION['user_id'], $query, $query, $query]);
            render_threaded_messages($stmt->fetchAll());
            exit();

        case 'search_users':
            header('Content-Type: application/json');
            $q = trim($_GET['q'] ?? '');
            if (strlen($q) < 2) {
                echo json_encode([]);
                exit();
            }
            $query = '%' . $q . '%';
            $stmt = $pdo->prepare("
                SELECT id, first_name, last_name, email, role
                FROM users
                WHERE id != ?
                  AND (email LIKE ? OR CONCAT(first_name,' ',last_name) LIKE ? OR first_name LIKE ? OR last_name LIKE ?)
                ORDER BY first_name
                LIMIT 10
            ");
            $stmt->execute([$_SESSION['user_id'], $query, $query, $query, $query]);
            echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
            exit();


    }
}
?>