<?php
session_start();
if (!isset($_SESSION['nurse_id'])) {
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Unauthorized']);
    exit();
}
include '../include/config.php';

$nurse_id = $_SESSION['nurse_id'];
$action = $_POST['action'] ?? $_GET['action'] ?? '';

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

switch($action) {
    case 'send':
        $other_id = $_POST['other_id'];
        $other_type = $_POST['other_type'];
        $message = $conn->real_escape_string($_POST['message']);
        
        $query = "INSERT INTO chat_messages (sender_id, sender_type, receiver_id, receiver_type, message, created_at, is_read) 
                  VALUES ('$nurse_id', 'nurse', '$other_id', '$other_type', '$message', NOW(), 0)";
        
        if ($conn->query($query)) {
            echo json_encode(['success' => true, 'message_id' => $conn->insert_id]);
        } else {
            echo json_encode(['success' => false, 'error' => $conn->error]);
        }
        break;
        
    case 'get_messages':
        $other_id = $_POST['other_id'];
        $other_type = $_POST['other_type'];
        $last_id = intval($_POST['last_id'] ?? 0);
        
        $query = "SELECT * FROM chat_messages 
                  WHERE ((sender_id = '$nurse_id' AND sender_type = 'nurse' AND receiver_id = '$other_id' AND receiver_type = '$other_type')
                     OR (sender_id = '$other_id' AND sender_type = '$other_type' AND receiver_id = '$nurse_id' AND receiver_type = 'nurse'))
                  AND id > $last_id
                  ORDER BY created_at ASC";
        
        $result = $conn->query($query);
        $messages = [];
        while($row = $result->fetch_assoc()) {
            $messages[] = $row;
        }
        
        echo json_encode(['success' => true, 'messages' => $messages]);
        break;
        
    case 'mark_read':
        $other_id = $_POST['other_id'];
        $other_type = $_POST['other_type'];
        
        $query = "UPDATE chat_messages 
                  SET is_read = 1 
                  WHERE sender_id = '$other_id' 
                  AND sender_type = '$other_type' 
                  AND receiver_id = '$nurse_id' 
                  AND receiver_type = 'nurse' 
                  AND is_read = 0";
        
        $conn->query($query);
        echo json_encode(['success' => true]);
        break;
        
    case 'typing':
        $other_id = $_POST['other_id'];
        $other_type = $_POST['other_type'];
        
        // Store typing status in session or cache (simplified - use a cache table for production)
        $_SESSION['typing_' . $other_id . '_' . $other_type] = time();
        echo json_encode(['success' => true]);
        break;
        
    case 'check_typing':
        $other_id = $_POST['other_id'];
        $other_type = $_POST['other_type'];
        
        $is_typing = false;
        if (isset($_SESSION['typing_' . $other_id . '_' . $other_type])) {
            $last_typing = $_SESSION['typing_' . $other_id . '_' . $other_type];
            if (time() - $last_typing < 3) { // Typing indicator lasts 3 seconds
                $is_typing = true;
            }
        }
        
        echo json_encode(['is_typing' => $is_typing]);
        break;
        
    default:
        echo json_encode(['error' => 'Invalid action']);
}
?>