<?php
/**
 * Chat/Messaging API
 * Handles real-time messaging operations
 */

header('Content-Type: application/json');
require_once '../config/config.php';

// Check if user is logged in
if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$userId = getCurrentUserId();
$method = $_SERVER['REQUEST_METHOD'];

try {
    $db = getDB();
    
    switch ($method) {
        case 'GET':
            // Fetch messages or chat rooms
            if (isset($_GET['room_id'])) {
                // Get messages in a chat room
                $roomId = (int)$_GET['room_id'];
                $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 50;
                $offset = isset($_GET['offset']) ? (int)$_GET['offset'] : 0;

                // Verify user is part of chat room
                $stmt = $db->prepare("SELECT id FROM chat_participants WHERE room_id = ? AND user_id = ?");
                $stmt->execute([$roomId, $userId]);
                if (!$stmt->fetch()) {
                    http_response_code(403);
                    echo json_encode(['success' => false, 'message' => 'Access denied']);
                    exit;
                }

                // Get messages
                $sinceId = isset($_GET['since_id']) ? (int)$_GET['since_id'] : null;
                $whereClause = $sinceId ? "AND m.id > ?" : "";
                $params = $sinceId ? [$roomId, $sinceId, $limit] : [$roomId, $limit];
                
                $stmt = $db->prepare("
                    SELECT m.*, CONCAT(u.first_name, ' ', u.last_name) as sender_name, 
                           CASE WHEN rp.photo IS NOT NULL AND rp.photo != '' 
                                THEN CONCAT('" . SITE_URL . "/', rp.photo) 
                                ELSE NULL END as sender_photo
                    FROM messages m
                    JOIN users u ON m.sender_id = u.id
                    LEFT JOIN researcher_profiles rp ON u.id = rp.user_id
                    WHERE m.room_id = ? {$whereClause}
                    ORDER BY m.id DESC
                    LIMIT ?
                ");
                $stmt->execute($params);
                $messages = $stmt->fetchAll();

                echo json_encode([
                    'success' => true,
                    'messages' => array_reverse($messages),
                    'room_id' => $roomId
                ]);

            } else {
                // Get all chat rooms for the user
                $stmt = $db->prepare("
                    SELECT r.*, 
                        (SELECT COUNT(*) FROM messages WHERE room_id = r.id AND is_read = 0 AND sender_id != ?) as unread_count,
                        (SELECT message FROM messages WHERE room_id = r.id ORDER BY created_at DESC LIMIT 1) as last_message,
                        COALESCE((SELECT created_at FROM messages WHERE room_id = r.id ORDER BY created_at DESC LIMIT 1), r.created_at) as last_message_time
                    FROM chat_rooms r
                    JOIN chat_participants cp ON r.id = cp.room_id
                    WHERE cp.user_id = ?
                    ORDER BY COALESCE((SELECT created_at FROM messages WHERE room_id = r.id ORDER BY created_at DESC LIMIT 1), r.created_at) DESC
                ");
                $stmt->execute([$userId, $userId]);
                $rooms = $stmt->fetchAll();

                // Get participants for each room
                foreach ($rooms as &$room) {
                    $stmt = $db->prepare("
                        SELECT u.id, u.first_name, u.last_name,
                               CASE WHEN rp.photo IS NOT NULL AND rp.photo != '' 
                                    THEN CONCAT('" . UPLOADS_URL . "/', rp.photo) 
                                    ELSE NULL END as photo
                        FROM users u
                        JOIN chat_participants cp ON u.id = cp.user_id
                        LEFT JOIN researcher_profiles rp ON u.id = rp.user_id
                        WHERE cp.room_id = ? AND u.id != ?
                    ");
                    $stmt->execute([$room['id'], $userId]);
                    $room['participants'] = $stmt->fetchAll();
                }

                echo json_encode([
                    'success' => true,
                    'rooms' => $rooms
                ]);
            }
            break;
            
        case 'POST':
            $data = json_decode(file_get_contents('php://input'), true);
            // Handle different actions: send_message, start_conversation, mark_read
            $action = isset($data['action']) ? $data['action'] : 'send_message';

            if ($action === 'send_message') {
                if (!isset($data['room_id']) || !isset($data['message'])) {
                    http_response_code(400);
                    echo json_encode(['success' => false, 'message' => 'Room ID and message required']);
                    exit;
                }
                $roomId = (int)$data['room_id'];
                $message = sanitize($data['message']);

                // Verify user is part of chat room
                $stmt = $db->prepare("SELECT id FROM chat_participants WHERE room_id = ? AND user_id = ?");
                $stmt->execute([$roomId, $userId]);
                if (!$stmt->fetch()) {
                    http_response_code(403);
                    echo json_encode(['success' => false, 'message' => 'Access denied']);
                    exit;
                }

                // Insert message
                $stmt = $db->prepare("INSERT INTO messages (room_id, sender_id, message) VALUES (?, ?, ?)");
                $stmt->execute([$roomId, $userId, $message]);
                $messageId = $db->lastInsertId();

                echo json_encode([
                    'success' => true,
                    'message_id' => $messageId,
                    'message' => 'Message sent successfully'
                ]);
                break;
            }

            if ($action === 'start_conversation') {
                // Start a new chat room (direct message)
                if (!isset($data['user_id']) || !isset($data['message'])) {
                    http_response_code(400);
                    echo json_encode(['success' => false, 'message' => 'User ID and message required']);
                    exit;
                }
                $otherUserId = (int)$data['user_id'];
                $message = sanitize($data['message']);

                // Get other user's name
                $stmt = $db->prepare("SELECT CONCAT(first_name, ' ', last_name) as name FROM users WHERE id = ?");
                $stmt->execute([$otherUserId]);
                $otherUser = $stmt->fetch();
                if (!$otherUser) {
                    http_response_code(404);
                    echo json_encode(['success' => false, 'message' => 'User not found']);
                    exit;
                }
                $otherName = $otherUser['name'];

                // Check if a direct chat room already exists
                $stmt = $db->prepare("SELECT r.id FROM chat_rooms r
                    JOIN chat_participants cp1 ON r.id = cp1.room_id AND cp1.user_id = ?
                    JOIN chat_participants cp2 ON r.id = cp2.room_id AND cp2.user_id = ?
                    WHERE r.type = 'direct'");
                $stmt->execute([$userId, $otherUserId]);
                $existingRoom = $stmt->fetch();
                if ($existingRoom) {
                    $roomId = $existingRoom['id'];
                } else {
                    // Create new chat room
                    $stmt = $db->prepare("INSERT INTO chat_rooms (type, name, created_by) VALUES ('direct', ?, ?)");
                    $stmt->execute([$otherName, $userId]);
                    $roomId = $db->lastInsertId();
                    // Add both users as participants
                    $stmt = $db->prepare("INSERT INTO chat_participants (room_id, user_id) VALUES (?, ?), (?, ?)");
                    $stmt->execute([$roomId, $userId, $roomId, $otherUserId]);
                }
                // Insert initial message
                $stmt = $db->prepare("INSERT INTO messages (room_id, sender_id, message) VALUES (?, ?, ?)");
                $stmt->execute([$roomId, $userId, $message]);
                $messageId = $db->lastInsertId();

                echo json_encode([
                    'success' => true,
                    'room_id' => $roomId,
                    'message_id' => $messageId,
                    'message' => 'Message sent successfully'
                ]);
                break;
            }

            if ($action === 'mark_read') {
                if (!isset($data['room_id'])) {
                    http_response_code(400);
                    echo json_encode(['success' => false, 'message' => 'Room ID required']);
                    exit;
                }
                $roomId = (int)$data['room_id'];
                // Mark all messages as read for this user (messages not sent by this user)
                $stmt = $db->prepare("UPDATE messages SET is_read = 1 WHERE room_id = ? AND sender_id != ? AND is_read = 0");
                $stmt->execute([$roomId, $userId]);
                echo json_encode(['success' => true]);
                break;
            }

            if ($action === 'add_participant') {
                if (!isset($data['room_id']) || !isset($data['user_id'])) {
                    http_response_code(400);
                    echo json_encode(['success' => false, 'message' => 'Room ID and User ID required']);
                    exit;
                }
                $roomId = (int)$data['room_id'];
                $newUserId = (int)$data['user_id'];

                // Verify current user is admin or creator of the room
                $stmt = $db->prepare("SELECT created_by FROM chat_rooms WHERE id = ?");
                $stmt->execute([$roomId]);
                $room = $stmt->fetch();
                if (!$room) {
                    http_response_code(404);
                    echo json_encode(['success' => false, 'message' => 'Chat room not found']);
                    exit;
                }

                // Check if current user is admin or creator
                $stmt = $db->prepare("SELECT role FROM chat_participants WHERE room_id = ? AND user_id = ?");
                $stmt->execute([$roomId, $userId]);
                $participant = $stmt->fetch();
                if (!$participant || ($participant['role'] !== 'admin' && $room['created_by'] != $userId)) {
                    http_response_code(403);
                    echo json_encode(['success' => false, 'message' => 'Permission denied']);
                    exit;
                }

                // Check if user is already in the room
                $stmt = $db->prepare("SELECT id FROM chat_participants WHERE room_id = ? AND user_id = ?");
                $stmt->execute([$roomId, $newUserId]);
                if ($stmt->fetch()) {
                    http_response_code(400);
                    echo json_encode(['success' => false, 'message' => 'User is already in this chat']);
                    exit;
                }

                // Add user to room
                $stmt = $db->prepare("INSERT INTO chat_participants (room_id, user_id) VALUES (?, ?)");
                $stmt->execute([$roomId, $newUserId]);

                // If room was direct, convert to group
                $stmt = $db->prepare("SELECT COUNT(*) as count FROM chat_participants WHERE room_id = ?");
                $stmt->execute([$roomId]);
                $participantCount = $stmt->fetch()['count'];
                if ($participantCount > 2) {
                    $stmt = $db->prepare("UPDATE chat_rooms SET type = 'group' WHERE id = ?");
                    $stmt->execute([$roomId]);
                }

                // Get the added user's name
                $stmt = $db->prepare("SELECT CONCAT(first_name, ' ', last_name) as name FROM users WHERE id = ?");
                $stmt->execute([$newUserId]);
                $addedUser = $stmt->fetch();

                echo json_encode([
                    'success' => true, 
                    'message' => 'Participant added successfully',
                    'participant_name' => $addedUser['name']
                ]);
                break;
            }

            // Default: unknown action
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Unknown action']);
            break;
            
        case 'DELETE':
            // Delete a message
            $data = json_decode(file_get_contents('php://input'), true);
            
            if (!isset($data['message_id'])) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Message ID required']);
                exit;
            }
            
            $messageId = (int)$data['message_id'];
            
            // Verify message belongs to user
            $stmt = $db->prepare("SELECT id FROM messages WHERE id = ? AND sender_id = ?");
            $stmt->execute([$messageId, $userId]);
            
            if (!$stmt->fetch()) {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Message not found']);
                exit;
            }
            
            // Delete message
            $stmt = $db->prepare("DELETE FROM messages WHERE id = ?");
            $stmt->execute([$messageId]);
            
            echo json_encode(['success' => true, 'message' => 'Message deleted']);
            break;
            
        default:
            http_response_code(405);
            echo json_encode(['success' => false, 'message' => 'Method not allowed']);
            break;
    }
    
} catch (Exception $e) {
    error_log("Chat API error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Internal server error']);
}
?>
