<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // Get messages
    $user = hw_auth_user();
    if (!$user) hw_json(['success' => false, 'message' => 'Unauthorized'], 401);
    
    $sessionId = (int)($_GET['session_id'] ?? 0);
    if ($sessionId <= 0) hw_json(['success' => false, 'message' => 'session_id is required'], 422);
    
    try {
        $pdo = hw_db();
        
        // Verify user has access to session
        $stmt = $pdo->prepare("
            SELECT COUNT(*) as count FROM session_participants 
            WHERE session_id = ? AND user_id = ?
        ");
        $stmt->execute([$sessionId, (int)$user['sub']]);
        $access = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($access['count'] == 0) {
            hw_json(['success' => false, 'message' => 'Access denied'], 403);
        }
        
        // Get messages
        $stmt = $pdo->prepare("
            SELECT m.*, u.first_name, u.last_name 
            FROM session_messages m 
            JOIN users u ON m.user_id = u.id 
            WHERE m.session_id = ? 
            ORDER BY m.created_at ASC
        ");
        $stmt->execute([$sessionId]);
        $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        hw_json([
            'success' => true,
            'messages' => $messages
        ]);
    } catch (Throwable $e) {
        hw_json(['success' => false, 'message' => 'Server error', 'error' => $e->getMessage()], 500);
    }
} else {
    // Send message
    hw_require_method(['POST']);
    $user = hw_auth_user();
    if (!$user) hw_json(['success' => false, 'message' => 'Unauthorized'], 401);
    
    $input = hw_input_json();
    $sessionId = (int)($input['session_id'] ?? 0);
    $content = trim((string)($input['content'] ?? ''));
    $messageType = $input['message_type'] ?? 'text';
    
    if ($sessionId <= 0) hw_json(['success' => false, 'message' => 'session_id is required'], 422);
    if ($content === '') hw_json(['success' => false, 'message' => 'content is required'], 422);
    
    try {
        $pdo = hw_db();
        
        // Verify user has access to session
        $stmt = $pdo->prepare("
            SELECT COUNT(*) as count FROM session_participants 
            WHERE session_id = ? AND user_id = ?
        ");
        $stmt->execute([$sessionId, (int)$user['sub']]);
        $access = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($access['count'] == 0) {
            hw_json(['success' => false, 'message' => 'Access denied'], 403);
        }
        
        // Insert message
        $stmt = $pdo->prepare("
            INSERT INTO session_messages (session_id, user_id, message_type, content) 
            VALUES (?, ?, ?, ?)
        ");
        $stmt->execute([$sessionId, (int)$user['sub'], $messageType, $content]);
        $messageId = (int)$pdo->lastInsertId();
        
        hw_json([
            'success' => true,
            'message_id' => $messageId
        ]);
    } catch (Throwable $e) {
        hw_json(['success' => false, 'message' => 'Server error', 'error' => $e->getMessage()], 500);
    }
}