<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Filter users by selected markets for notification routing
 * 
 * IMPORTANT: This function handles market-based notification routing.
 * It ensures notifications are sent only to users in the selected markets,
 * regardless of user type (customers, vendors, drivers).
 * 
 * NOTE: Order-related driver notifications remain strictly city-scoped
 * and should use send_order_notification_to_drivers() instead.
 * 
 * @param array $selectedMarkets Array of city IDs (e.g., ['city123', 'city456'])
 * @param object $common Common model instance
 * @param array $userTypes Optional array of user roles to filter (e.g., ['user', 'vendor', 'driver']). If empty, includes all user types.
 * @return array Array with 'userIds', 'tokens', and 'userTypeCounts'
 */
function filter_users_by_markets($selectedMarkets, $common, $userTypes = array()) {
    // Validate selected markets
    if (empty($selectedMarkets) || !is_array($selectedMarkets)) {
        return array(
            'userIds' => array(),
            'tokens' => array(),
            'userTypeCounts' => array(
                'customers' => 0,
                'vendors' => 0,
                'drivers' => 0,
                'other' => 0
            )
        );
    }
    
    $userIds = array();
    $tokens = array();
    $userTypeCounts = array(
        'customers' => 0,
        'vendors' => 0,
        'drivers' => 0,
        'other' => 0
    );
    
    // Get all users from the Users collection
    $allUsers = $common->readdatacollection("Users");
    
    if (empty($allUsers)) {
        return array(
            'userIds' => $userIds,
            'tokens' => $tokens,
            'userTypeCounts' => $userTypeCounts
        );
    }
    
    // Filter users by selected markets
    foreach ($allUsers as $userId => $user) {
        // Get user's city ID
        $userCityId = isset($user['cityId']) ? $user['cityId'] : null;
        $userRole = isset($user['userRole']) ? $user['userRole'] : 'other';
        
        // Skip if user has no cityId assigned
        if ($userCityId === null) {
            continue;
        }
        
        // Skip if user type filter is specified and user doesn't match
        if (!empty($userTypes) && !in_array($userRole, $userTypes)) {
            continue;
        }
        
        // Include user only if their cityId is in the selected markets
        // This ensures strict market separation for notifications
        if (in_array($userCityId, $selectedMarkets)) {
            $userIds[] = $userId;
            
            // Collect FCM token if available
            if (isset($user['token']) && $user['token'] != "") {
                $tokens[] = $user['token'];
                
                // Count by user type for reporting
                if ($userRole == 'user') {
                    $userTypeCounts['customers']++;
                } elseif ($userRole == 'vendor') {
                    $userTypeCounts['vendors']++;
                } elseif ($userRole == 'driver') {
                    $userTypeCounts['drivers']++;
                } else {
                    $userTypeCounts['other']++;
                }
            }
        }
    }
    
    return array(
        'userIds' => $userIds,
        'tokens' => $tokens,
        'userTypeCounts' => $userTypeCounts
    );
}

/**
 * Get market names from city IDs
 * 
 * @param array $cityIds Array of city IDs
 * @param object $common Common model instance
 * @return array Array of city names
 */
function get_market_names($cityIds, $common) {
    $marketNames = array();
    
    if (empty($cityIds) || !is_array($cityIds)) {
        return $marketNames;
    }
    
    foreach ($cityIds as $cityId) {
        $city = $common->readdatadocument("Cities", $cityId);
        if (!empty($city) && isset($city['cityName'])) {
            $marketNames[] = $city['cityName'];
        }
    }
    
    return $marketNames;
}

/**
 * Validate selected markets for notifications
 * 
 * @param array $selectedMarkets Array of city IDs
 * @return array Array with 'valid' (bool) and 'message' (string)
 */
function validate_selected_markets($selectedMarkets) {
    if (empty($selectedMarkets) || !is_array($selectedMarkets)) {
        return array(
            'valid' => false,
            'message' => 'Please select at least one market.'
        );
    }
    
    // Remove empty values
    $selectedMarkets = array_filter($selectedMarkets);
    
    if (empty($selectedMarkets)) {
        return array(
            'valid' => false,
            'message' => 'Please select at least one market.'
        );
    }
    
    return array(
        'valid' => true,
        'message' => ''
    );
}

/**
 * Format notification success message with market and user type breakdown
 * 
 * @param int $totalUsers Total number of users notified
 * @param array $userTypeCounts Array with counts by user type
 * @param array $marketNames Array of market names
 * @return string Formatted success message
 */
function format_notification_success_message($totalUsers, $userTypeCounts, $marketNames) {
    $marketsText = !empty($marketNames) ? ' (' . implode(', ', $marketNames) . ')' : '';
    
    // Build user type breakdown
    $userTypeBreakdown = array();
    if (isset($userTypeCounts['customers']) && $userTypeCounts['customers'] > 0) {
        $userTypeBreakdown[] = $userTypeCounts['customers'] . ' customer' . ($userTypeCounts['customers'] > 1 ? 's' : '');
    }
    if (isset($userTypeCounts['vendors']) && $userTypeCounts['vendors'] > 0) {
        $userTypeBreakdown[] = $userTypeCounts['vendors'] . ' vendor' . ($userTypeCounts['vendors'] > 1 ? 's' : '');
    }
    if (isset($userTypeCounts['drivers']) && $userTypeCounts['drivers'] > 0) {
        $userTypeBreakdown[] = $userTypeCounts['drivers'] . ' driver' . ($userTypeCounts['drivers'] > 1 ? 's' : '');
    }
    
    $breakdownText = !empty($userTypeBreakdown) ? ' (' . implode(', ', $userTypeBreakdown) . ')' : '';
    
    return 'Notification sent successfully to ' . $totalUsers . ' users in selected markets' . $marketsText . $breakdownText;
}
