<?php
require_once __DIR__ . '/../lib.php';
hw_require_auth(['client']);

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

$authUser = hw_get_auth_user();
$input = json_decode(file_get_contents('php://input'), true);

$conversationId = $input['conversation_id'] ?? null;
$coachId = $input['coach_id'] ?? null;
$message = trim($input['message'] ?? '');

if (!$message) {
    echo json_encode(['success' => false, 'message' => 'Message cannot be empty']);
    exit;
}

$db = hw_db();

try {
    $db->beginTransaction();
    
    // If no conversation ID, create a new conversation
    if (!$conversationId) {
        if (!$coachId) {
            echo json_encode(['success' => false, 'message' => 'Coach ID required']);
            exit;
        }
        
        // Check if conversation already exists
        $checkStmt = $db->prepare("
            SELECT id FROM conversations 
            WHERE user_id = ? AND coach_id = ?
        ");
        $checkStmt->execute([$authUser['id'], $coachId]);
        $existing = $checkStmt->fetch(PDO::FETCH_ASSOC);
        
        if ($existing) {
            $conversationId = $existing['id'];
        } else {
            // Create new conversation
            $createStmt = $db->prepare("
                INSERT INTO conversations (user_id, coach_id, last_message, last_message_time, created_at)
                VALUES (?, ?, ?, NOW(), NOW())
            ");
            $createStmt->execute([$authUser['id'], $coachId, $message]);
            $conversationId = $db->lastInsertId();
        }
    }
    
    // Verify user has access to this conversation
    $verifyStmt = $db->prepare("SELECT id FROM conversations WHERE id = ? AND user_id = ?");
    $verifyStmt->execute([$conversationId, $authUser['id']]);
    
    if (!$verifyStmt->fetch()) {
        $db->rollBack();
        echo json_encode(['success' => false, 'message' => 'Unauthorized']);
        exit;
    }
    
    // Insert message
    $insertStmt = $db->prepare("
        INSERT INTO messages (conversation_id, sender_type, sender_id, message, created_at)
        VALUES (?, 'client', ?, ?, NOW())
    ");
    $insertStmt->execute([$conversationId, $authUser['id'], $message]);
    
    // Update conversation last message
    $updateStmt = $db->prepare("
        UPDATE conversations 
        SET last_message = ?, last_message_time = NOW()
        WHERE id = ?
    ");
    $updateStmt->execute([$message, $conversationId]);
    
    $db->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Message sent',
        'conversation_id' => $conversationId
    ]);
    
} catch (Exception $e) {
    $db->rollBack();
    error_log("Error sending message: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Failed to send message'
    ]);
}
