<?php
/**
 * Tenants Data - Fetch and manage tenant information from MongoDB
 */

try {
    $db = MongoDBConnection::getInstance()->getDatabase();
    
    // Get pagination parameters
    $page_num = (int)($_GET['page_num'] ?? 1);
    $items_per_page = 25;
    $skip = ($page_num - 1) * $items_per_page;
    
    // Get search and filter parameters
    $search = $_GET['search'] ?? '';
    $status_filter = $_GET['status'] ?? '';
    
    // Build filter
    $filter = [];
    if (!empty($search)) {
        $search_regex = new MongoDB\BSON\Regex(escape_mongo_regex($search), 'i');
        $filter['$or'] = [
            ['name' => $search_regex],
            ['tenant_id' => $search_regex]
        ];
    }
    
    if (!empty($status_filter)) {
        $filter['status'] = $status_filter;
    }
    
    // Get total count for pagination
    $total_tenants = $db->tenants->countDocuments($filter);
    $total_pages = ceil($total_tenants / $items_per_page);
    
    // Get tenants with pagination
    $tenants_cursor = $db->tenants->find($filter, [
        'sort' => ['created_at' => -1],
        'skip' => $skip,
        'limit' => $items_per_page
    ]);
    
    $tenants = [];
    foreach ($tenants_cursor as $tenant) {
        $tenant_data = [
            'id' => (string)$tenant['_id'],
            'tenant_id' => $tenant['tenant_id'],
            'name' => $tenant['name'],
            'status' => $tenant['status'],
            'created_at' => $tenant['created_at'],
            'updated_at' => $tenant['updated_at'] ?? null,
            'apps_count' => 0,
            'items_count' => 0,
            'interactions_count' => 0
        ];
        
        // Get related counts for each tenant
        try {
            // Count applications
            $tenant_data['apps_count'] = $db->apps->countDocuments([
                'tenant_id' => $tenant['tenant_id']
            ]);
            
            // Count items
            $tenant_data['items_count'] = $db->items->countDocuments([
                'tenant_id' => $tenant['tenant_id']
            ]);
            
            // Count recent interactions (last 30 days)
            $thirty_days_ago = new MongoDB\BSON\UTCDateTime((time() - (30 * 24 * 60 * 60)) * 1000);
            $tenant_data['interactions_count'] = $db->interactions->countDocuments([
                'tenant_id' => $tenant['tenant_id'],
                'ts' => ['$gte' => $thirty_days_ago]
            ]);
            
        } catch (Exception $e) {
            error_log("Error getting tenant stats for {$tenant['tenant_id']}: " . $e->getMessage());
        }
        
        $tenants[] = $tenant_data;
    }
    
    // Get tenant statistics for summary
    $tenant_stats = [
        'total' => $total_tenants,
        'active' => $db->tenants->countDocuments(['status' => 'active']),
        'inactive' => $db->tenants->countDocuments(['status' => 'inactive']),
        'suspended' => $db->tenants->countDocuments(['status' => 'suspended'])
    ];
    
    // Get recent tenant activity
    $recent_tenants = [];
    try {
        $recent_cursor = $db->tenants->find([], [
            'sort' => ['created_at' => -1],
            'limit' => 5,
            'projection' => ['tenant_id' => 1, 'name' => 1, 'status' => 1, 'created_at' => 1]
        ]);
        
        foreach ($recent_cursor as $tenant) {
            $recent_tenants[] = [
                'tenant_id' => $tenant['tenant_id'],
                'name' => $tenant['name'],
                'status' => $tenant['status'],
                'created_at' => $tenant['created_at']
            ];
        }
    } catch (Exception $e) {
        error_log("Error getting recent tenants: " . $e->getMessage());
    }
    
    // Handle POST requests (Add/Edit/Delete)
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
        $action = $_POST['action'];
        $response = ['success' => false, 'message' => ''];
        
        try {
            switch ($action) {
                case 'add':
                    // Add new tenant
                    $tenant_data = [
                        'tenant_id' => generateTenantId(),
                        'name' => $_POST['name'],
                        'status' => $_POST['status'] ?? 'active',
                        'created_at' => new MongoDB\BSON\UTCDateTime(),
                        'updated_at' => new MongoDB\BSON\UTCDateTime()
                    ];
                    
                    $result = $db->tenants->insertOne($tenant_data);
                    
                    if ($result->getInsertedCount() > 0) {
                        $response['success'] = true;
                        $response['message'] = 'Tenant created successfully';
                        
                        // Update counter
                        updateTenantCounter();
                    } else {
                        $response['message'] = 'Failed to create tenant';
                    }
                    break;
                    
                case 'update':
                    // Update existing tenant
                    $tenant_id = $_POST['tenant_id'];
                    $update_data = [
                        'name' => $_POST['name'],
                        'status' => $_POST['status'],
                        'updated_at' => new MongoDB\BSON\UTCDateTime()
                    ];
                    
                    $result = $db->tenants->updateOne(
                        ['tenant_id' => $tenant_id],
                        ['$set' => $update_data]
                    );
                    
                    if ($result->getModifiedCount() > 0) {
                        $response['success'] = true;
                        $response['message'] = 'Tenant updated successfully';
                    } else {
                        $response['message'] = 'No changes made or tenant not found';
                    }
                    break;
                    
                case 'delete':
                    // Delete tenant (with confirmation)
                    $tenant_id = $_POST['tenant_id'];
                    
                    // Check if tenant has apps or data
                    $apps_count = $db->apps->countDocuments(['tenant_id' => $tenant_id]);
                    $items_count = $db->items->countDocuments(['tenant_id' => $tenant_id]);
                    
                    if ($apps_count > 0 || $items_count > 0) {
                        $response['message'] = 'Cannot delete tenant with existing apps or data. Please remove all related data first.';
                    } else {
                        $result = $db->tenants->deleteOne(['tenant_id' => $tenant_id]);
                        
                        if ($result->getDeletedCount() > 0) {
                            $response['success'] = true;
                            $response['message'] = 'Tenant deleted successfully';
                        } else {
                            $response['message'] = 'Tenant not found or already deleted';
                        }
                    }
                    break;
            }
        } catch (Exception $e) {
            error_log("Tenant operation error: " . $e->getMessage());
            $response['message'] = 'Database operation failed: ' . $e->getMessage();
        }
        
        // Return JSON response for AJAX requests
        if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
            header('Content-Type: application/json');
            echo json_encode($response);
            exit;
        }
        
        // Redirect for regular form submissions
        if ($response['success']) {
            header('Location: ?page=tenants&message=' . urlencode($response['message']));
            exit;
        } else {
            $error_message = $response['message'];
        }
    }
    
} catch (Exception $e) {
    error_log("Tenants data error: " . $e->getMessage());
    
    // Fallback data
    $tenants = [];
    $tenant_stats = ['total' => 0, 'active' => 0, 'inactive' => 0, 'suspended' => 0];
    $recent_tenants = [];
    $total_pages = 1;
    $error_message = "Failed to load tenant data: " . $e->getMessage();
}

/**
 * Helper function to generate next tenant ID
 */
function generateTenantId() {
    try {
        $db = MongoDBConnection::getInstance()->getDatabase();
        
        // Get and increment counter
        $result = $db->counters->findOneAndUpdate(
            ['_id' => 'tenant_id'],
            ['$inc' => ['sequence_value' => 1]],
            [
                'upsert' => true,
                'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER
            ]
        );
        
        return (string)$result['sequence_value'];
        
    } catch (Exception $e) {
        error_log("Error generating tenant ID: " . $e->getMessage());
        // Fallback to timestamp-based ID
        return (string)time();
    }
}

/**
 * Helper function to update tenant counter
 */
function updateTenantCounter() {
    try {
        $db = MongoDBConnection::getInstance()->getDatabase();
        
        // Ensure counter exists and is accurate
        $max_tenant = $db->tenants->findOne([], [
            'sort' => ['tenant_id' => -1],
            'projection' => ['tenant_id' => 1]
        ]);
        
        if ($max_tenant) {
            $max_id = (int)$max_tenant['tenant_id'];
            $db->counters->updateOne(
                ['_id' => 'tenant_id'],
                ['$set' => ['sequence_value' => $max_id]],
                ['upsert' => true]
            );
        }
    } catch (Exception $e) {
        error_log("Error updating tenant counter: " . $e->getMessage());
    }
}

?>
