<?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 conversations
            if (isset($_GET['conversation_id'])) {
                // Get messages in a conversation
                $conversationId = (int)$_GET['conversation_id'];
                $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 50;
                $offset = isset($_GET['offset']) ? (int)$_GET['offset'] : 0;
                
                // Verify user is part of conversation
                $stmt = $db->prepare("
                    SELECT id FROM conversation_participants 
                    WHERE conversation_id = ? AND user_id = ?
                ");
                $stmt->execute([$conversationId, $userId]);
                
                if (!$stmt->fetch()) {
                    http_response_code(403);
                    echo json_encode(['success' => false, 'message' => 'Access denied']);
                    exit;
                }
                
                // Get messages
                $stmt = $db->prepare("
                    SELECT m.*, u.first_name, u.last_name
                    FROM messages m
                    JOIN users u ON m.sender_id = u.id
                    WHERE m.conversation_id = ?
                    ORDER BY m.created_at DESC
                    LIMIT ? OFFSET ?
                ");
                $stmt->execute([$conversationId, $limit, $offset]);
                $messages = $stmt->fetchAll();
                
                // Mark messages as read
                $stmt = $db->prepare("
                    UPDATE messages 
                    SET is_read = 1, read_at = NOW() 
                    WHERE conversation_id = ? AND receiver_id = ? AND is_read = 0
                ");
                $stmt->execute([$conversationId, $userId]);
                
                echo json_encode([
                    'success' => true,
                    'messages' => array_reverse($messages),
                    'conversation_id' => $conversationId
                ]);
                
            } else {
                // Get all conversations
                $stmt = $db->prepare("
                    SELECT c.*, 
                           (SELECT COUNT(*) FROM messages 
                            WHERE conversation_id = c.id AND receiver_id = ? AND is_read = 0) as unread_count,
                           (SELECT message FROM messages 
                            WHERE conversation_id = c.id 
                            ORDER BY created_at DESC LIMIT 1) as last_message,
                           (SELECT created_at FROM messages 
                            WHERE conversation_id = c.id 
                            ORDER BY created_at DESC LIMIT 1) as last_message_time
                    FROM conversations c
                    JOIN conversation_participants cp ON c.id = cp.conversation_id
                    WHERE cp.user_id = ?
                    ORDER BY last_message_time DESC
                ");
                $stmt->execute([$userId, $userId]);
                $conversations = $stmt->fetchAll();
                
                // Get participants for each conversation
                foreach ($conversations as &$conv) {
                    $stmt = $db->prepare("
                        SELECT u.id, u.first_name, u.last_name
                        FROM users u
                        JOIN conversation_participants cp ON u.id = cp.user_id
                        WHERE cp.conversation_id = ? AND u.id != ?
                    ");
                    $stmt->execute([$conv['id'], $userId]);
                    $conv['participants'] = $stmt->fetchAll();
                }
                
                echo json_encode([
                    'success' => true,
                    'conversations' => $conversations
                ]);
            }
            break;
            
        case 'POST':
            // Send a message
            $data = json_decode(file_get_contents('php://input'), true);
            
            if (!isset($data['conversation_id']) || !isset($data['message'])) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Conversation ID and message required']);
                exit;
            }
            
            $conversationId = (int)$data['conversation_id'];
            $message = sanitize($data['message']);
            
            // Verify user is part of conversation
            $stmt = $db->prepare("
                SELECT id FROM conversation_participants 
                WHERE conversation_id = ? AND user_id = ?
            ");
            $stmt->execute([$conversationId, $userId]);
            
            if (!$stmt->fetch()) {
                http_response_code(403);
                echo json_encode(['success' => false, 'message' => 'Access denied']);
                exit;
            }
            
            // Get receiver ID (other participant)
            $stmt = $db->prepare("
                SELECT user_id FROM conversation_participants 
                WHERE conversation_id = ? AND user_id != ?
                LIMIT 1
            ");
            $stmt->execute([$conversationId, $userId]);
            $receiver = $stmt->fetch();
            $receiverId = $receiver ? $receiver['user_id'] : null;
            
            // Insert message
            $stmt = $db->prepare("
                INSERT INTO messages (conversation_id, sender_id, receiver_id, message)
                VALUES (?, ?, ?, ?)
            ");
            $stmt->execute([$conversationId, $userId, $receiverId, $message]);
            $messageId = $db->lastInsertId();
            
            // Update conversation last_message_at
            $stmt = $db->prepare("UPDATE conversations SET last_message_at = NOW() WHERE id = ?");
            $stmt->execute([$conversationId]);
            
            // Create notification for receiver
            if ($receiverId) {
                $stmt = $db->prepare("
                    INSERT INTO notifications (user_id, type, title, message, related_id)
                    VALUES (?, 'message', 'New Message', ?, ?)
                ");
                $stmt->execute([$receiverId, 'You have a new message', $messageId]);
            }
            
            echo json_encode([
                'success' => true,
                'message_id' => $messageId,
                'message' => 'Message sent successfully'
            ]);
            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']);
}
?>
