<?php
// api/messages.php
require_once __DIR__ . '/db.php';
session_start();

header('Content-Type: application/json');

function sendResponse($data, $statusCode = 200) {
    http_response_code($statusCode);
    echo json_encode($data);
    exit;
}

if (!isset($_SESSION['user_id'])) {
    sendResponse(['error' => 'Unauthorized.'], 401);
}

$db = Database::getInstance()->getConnection();
$method = $_SERVER['REQUEST_METHOD'];
$userId = $_SESSION['user_id'];
$input = json_decode(file_get_contents('php://input'), true);
$action = isset($_GET['action']) ? $_GET['action'] : ($input['action'] ?? '');

if ($method === 'GET') {
    if ($action === 'contacts') {
        // Return a list of users the current user can talk to.
        // For a small team Kanban app, we'll return all active users except the current user.
        // We'll also count unread messages from each.
        
        $stmt = $db->prepare('
            SELECT u.id, u.username, u.email,
                   (SELECT COUNT(*) FROM direct_messages m WHERE m.sender_id = u.id AND m.receiver_id = ? AND m.is_read = 0) as unread_count
            FROM users u
            WHERE u.is_active = 1 AND u.id != ?
              AND EXISTS (
                  SELECT 1 FROM direct_messages dm
                  WHERE (dm.sender_id = u.id AND dm.receiver_id = ?)
                     OR (dm.sender_id = ? AND dm.receiver_id = u.id)
              )
            ORDER BY u.username ASC
        ');
        $stmt->execute([$userId, $userId, $userId, $userId]);
        $contacts = $stmt->fetchAll();
        sendResponse(['contacts' => $contacts]);
    }
    elseif ($action === 'conversation') {
        $otherUserId = intval($_GET['with_user_id'] ?? 0);
        if (!$otherUserId) sendResponse(['error' => 'Missing with_user_id parameters.'], 400);

        // Mark messages from this user as read
        $stmtRead = $db->prepare('UPDATE direct_messages SET is_read = 1 WHERE sender_id = ? AND receiver_id = ?');
        $stmtRead->execute([$otherUserId, $userId]);

        // Fetch chronological conversation
        $stmt = $db->prepare('
            SELECT m.id, m.sender_id, m.receiver_id, m.content, m.created_at, u.username as sender_name
            FROM direct_messages m
            JOIN users u ON m.sender_id = u.id
            WHERE (m.sender_id = ? AND m.receiver_id = ?) 
               OR (m.sender_id = ? AND m.receiver_id = ?)
            ORDER BY m.created_at ASC
        ');
        $stmt->execute([$userId, $otherUserId, $otherUserId, $userId]);
        $messages = $stmt->fetchAll();
        sendResponse(['messages' => $messages]);
    }
    elseif ($action === 'unread_count') {
        // Global count for the nav badge
        $stmt = $db->prepare('SELECT COUNT(*) as count FROM direct_messages WHERE receiver_id = ? AND is_read = 0');
        $stmt->execute([$userId]);
        $res = $stmt->fetch();
        sendResponse(['unread_count' => $res['count']]);
    }
    else {
        sendResponse(['error' => 'Invalid GET action.'], 400);
    }
}
elseif ($method === 'POST') {
    $receiverId = $input['receiver_id'] ?? 0;
    $content = trim($input['content'] ?? '');

    if (!$receiverId || empty($content)) {
        sendResponse(['error' => 'Receiver ID and content are required.'], 400);
    }

    // Optional: Check if receiver exists and is active
    $stmtCheck = $db->prepare('SELECT id FROM users WHERE id = ? AND is_active = 1');
    $stmtCheck->execute([$receiverId]);
    if (!$stmtCheck->fetch()) {
        sendResponse(['error' => 'Receiver not found.'], 404);
    }

    $stmt = $db->prepare('INSERT INTO direct_messages (sender_id, receiver_id, content) VALUES (?, ?, ?)');
    $stmt->execute([$userId, $receiverId, $content]);

    sendResponse(['message' => 'Message sent.']);
}
elseif ($method === 'DELETE') {
    if ($action === 'delete_chat') {
        $otherUserId = intval($_GET['with_user_id'] ?? 0);
        if (!$otherUserId) sendResponse(['error' => 'Missing with_user_id parameter.'], 400);

        $stmt = $db->prepare('DELETE FROM direct_messages WHERE (sender_id = ? AND receiver_id = ?) OR (sender_id = ? AND receiver_id = ?)');
        $stmt->execute([$userId, $otherUserId, $otherUserId, $userId]);

        sendResponse(['message' => 'Chat deleted.']);
    } else {
        sendResponse(['error' => 'Invalid DELETE action.'], 400);
    }
}
else {
    sendResponse(['error' => 'Invalid method.'], 405);
}
