<?php
/**
 * ============================================================================
 * chat/ajax/send-message.php - Send Message Endpoint (FIXED)
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../../config/config.php';

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

// Check authentication
if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode([
        'success' => false,
        'message' => 'Not authenticated. Please log in again.'
    ]);
    exit;
}

try {
    $userId = getUserId();
    $chatId = isset($_POST['chat_id']) ? (int)$_POST['chat_id'] : 0;
    $content = isset($_POST['content']) ? trim($_POST['content']) : '';
    $messageType = isset($_POST['message_type']) ? $_POST['message_type'] : 'text';
    $mediaUrl = isset($_POST['media_url']) ? $_POST['media_url'] : null;
    $encrypt = isset($_POST['encrypt']) ? filter_var($_POST['encrypt'], FILTER_VALIDATE_BOOLEAN) : false;
    
    // Validate required fields
    if (!$chatId) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'Chat ID is required'
        ]);
        exit;
    }
    
    if (empty($content) && empty($mediaUrl)) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'Message content cannot be empty'
        ]);
        exit;
    }
    
    // Get database connection
    $database = \App\Database::getInstance();
    $db = $database->getConnection();
    
    if (!$db) {
        throw new \Exception('Database connection failed');
    }
    
    $chatClass = new \App\Chat($db);
    $messageClass = new \App\Message($db);
    
    // Verify user is member of chat
    if (!$chatClass->isMember($chatId, $userId)) {
        http_response_code(403);
        echo json_encode([
            'success' => false,
            'message' => 'You are not a member of this chat'
        ]);
        exit;
    }
    
    // Check if user is blocked
    $blockQuery = "SELECT COUNT(*) as blocked_count
                   FROM chat_members cm
                   INNER JOIN user_blocks ub ON (
                       (ub.blocker_id = cm.user_id AND ub.blocked_id = ?) OR
                       (ub.blocker_id = ? AND ub.blocked_id = cm.user_id)
                   )
                   WHERE cm.chat_id = ?";
    
    $stmt = $db->prepare($blockQuery);
    $stmt->execute([$userId, $userId, $chatId]);
    $blockResult = $stmt->fetch(\PDO::FETCH_ASSOC);
    
    if ($blockResult && $blockResult['blocked_count'] > 0) {
        http_response_code(403);
        echo json_encode([
            'success' => false,
            'message' => 'You cannot send messages in this chat'
        ]);
        exit;
    }
    
    // Send message
    $result = $messageClass->send($chatId, $userId, [
        'content' => $content,
        'message_type' => $messageType,
        'media_url' => $mediaUrl
    ], $encrypt);
    
    if ($result['success']) {
        // Get the full message details
        $sql = "SELECT m.*, 
                       u.full_name as sender_name, 
                       u.profile_picture as sender_avatar
                FROM messages m
                JOIN users u ON m.sender_id = u.id
                WHERE m.id = ?";
        
        $stmt = $db->prepare($sql);
        $stmt->execute([$result['message_id']]);
        $message = $stmt->fetch(\PDO::FETCH_ASSOC);
        
        if (!$message) {
            throw new \Exception('Message was sent but could not be retrieved');
        }
        
        // Update chat timestamp
        $updateChat = "UPDATE chats SET updated_at = NOW() WHERE id = ?";
        $stmt = $db->prepare($updateChat);
        $stmt->execute([$chatId]);
        
        http_response_code(200);
        echo json_encode([
            'success' => true,
            'message' => $message,
            'timestamp' => date('Y-m-d H:i:s')
        ]);
    } else {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'message' => $result['message'] ?? 'Failed to send message. Please try again.'
        ]);
    }
    
} catch (\PDOException $e) {
    error_log('Database error in send-message.php: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Database error. Please try again later.',
        'error' => APP_DEBUG ? $e->getMessage() : null
    ]);
    
} catch (\Exception $e) {
    error_log('Error in send-message.php: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage(),
        'error' => APP_DEBUG ? $e->getTraceAsString() : null
    ]);
}