<?php
/**
 * ============================================================================
 * chat/ajax/delete-chat.php - Delete Chat Endpoint
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../../config/config.php';

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

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit;
}

try {
    $userId = getUserId();
    $chatId = (int)($_POST['chat_id'] ?? 0);
    
    if (!$chatId) {
        echo json_encode([
            'success' => false,
            'message' => 'Chat ID is required'
        ]);
        exit;
    }
    
    $database = new \App\Database();
    $db = $database->getConnection();
    $chatClass = new \App\Chat($db);
    
    // Verify user is member
    if (!$chatClass->isMember($chatId, $userId)) {
        echo json_encode([
            'success' => false,
            'message' => 'Access denied'
        ]);
        exit;
    }
    
    // Delete chat (remove user from members)
    $success = $chatClass->deleteChat($chatId, $userId);
    
    if ($success) {
        echo json_encode([
            'success' => true,
            'message' => 'Chat deleted successfully'
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Failed to delete chat'
        ]);
    }
    
} catch (\Exception $e) {
    error_log('Delete chat error: ' . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Failed to delete chat: ' . $e->getMessage()
    ]);
}