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

/**
 * Mask mobile number
 * Example: 9876543210 -> 987****210 (show first 3, last 3)
 */
if (!function_exists('mask_mobile')) {
    function mask_mobile($mobile) {
        // Generate random number if mobile is empty
        if (empty($mobile)) {
            $mobile = '9' . rand(100000000, 999999999);
        }
        
        if (strlen($mobile) < 6) {
            return $mobile;
        }
        
        $length = strlen($mobile);
        $visible_start = 3;
        $visible_end = 3;
        $mask_length = $length - $visible_start - $visible_end;
        
        return substr($mobile, 0, $visible_start) . str_repeat('*', max($mask_length, 2)) . substr($mobile, -$visible_end);
    }
}

/**
 * Mask name
 * Example: Rohit Kumar -> Roh** Kum** (show first 3 chars of each word)
 */
if (!function_exists('mask_name')) {
    function mask_name($name) {
        if (empty($name)) {
            return $name;
        }
        
        $length = strlen($name);
        if ($length <= 3) {
            return $name;
        }
        
        // Show first 3 characters, mask rest with only 2 stars
        return substr($name, 0, 3) . str_repeat('*', min($length - 3, 2));
    }
}

/**
 * Mask email
 * Example: abc@gmail.com -> abc**@gmail.com (show first 3 chars)
 */
if (!function_exists('mask_email')) {
    function mask_email($email) {
        if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return $email;
        }
        
        $parts = explode('@', $email);
        $username = $parts[0];
        $domain = $parts[1];
        
        $username_length = strlen($username);
        if ($username_length <= 3) {
            $masked_username = $username;
        } else {
            $masked_username = substr($username, 0, 3) . str_repeat('*', min($username_length - 3, 2));
        }
        
        return $masked_username . '@' . $domain;
    }
}

/**
 * Mask address
 * Example: Andheri -> Andh****
 */
if (!function_exists('mask_address')) {
    function mask_address($address) {
        if (empty($address)) {
            return $address;
        }
        
        $length = strlen($address);
        if ($length <= 4) {
            return $address;
        }
        
        $visible = 4;
        return substr($address, 0, $visible) . str_repeat('*', min($length - $visible, 5));
    }
}

/**
 * Mask all data fields
 */
if (!function_exists('mask_data')) {
    function mask_data($data) {
        if (is_object($data)) {
            $masked = clone $data;
        } else {
            $masked = $data;
        }
        
        if (isset($masked->mobile)) {
            $masked->mobile = mask_mobile($masked->mobile);
        }
        
        if (isset($masked->name)) {
            $masked->name = mask_name($masked->name);
        }
        
        if (isset($masked->email)) {
            $masked->email = mask_email($masked->email);
        }
        
        if (isset($masked->address)) {
            $masked->address = mask_address($masked->address);
        }
        
        return $masked;
    }
}

/**
 * Check if user is logged in
 */
if (!function_exists('is_logged_in')) {
    function is_logged_in() {
        $CI =& get_instance();
        // @phpstan-ignore-line
        $logged_in = $CI->session->userdata('logged_in') === TRUE;
        
        // Verify portal_id to prevent cross-portal access
        if ($logged_in) {
            $session_portal = $CI->session->userdata('portal_id');
            $current_portal = $CI->config->item('portal_id');
            
            if ($session_portal !== $current_portal) {
                // Session is from different portal - destroy and deny access
                $CI->session->sess_destroy();
                return FALSE;
            }
        }
        
        return $logged_in;
    }
}

/**
 * Check if user is admin
 */
if (!function_exists('is_admin')) {
    function is_admin() {
        $CI =& get_instance();
        // @phpstan-ignore-line
        return $CI->session->userdata('role') === 'admin';
    }
}

/**
 * Check if user is regular user
 */
if (!function_exists('is_user')) {
    function is_user() {
        $CI =& get_instance();
        // @phpstan-ignore-line
        return $CI->session->userdata('role') === 'user';
    }
}

/**
 * Get current user ID
 */
if (!function_exists('current_user_id')) {
    function current_user_id() {
        $CI =& get_instance();
        // @phpstan-ignore-line
        return $CI->session->userdata('user_id');
    }
}

/**
 * Get current username
 */
if (!function_exists('current_username')) {
    function current_username() {
        $CI =& get_instance();
        // @phpstan-ignore-line
        return $CI->session->userdata('username');
    }
}

/**
 * Flash message helper
 */
if (!function_exists('set_flash')) {
    function set_flash($type, $message) {
        $CI =& get_instance();
        // @phpstan-ignore-line
        $CI->session->set_flashdata($type, $message);
    }
}

/**
 * Get flash message
 */
if (!function_exists('get_flash')) {
    function get_flash($type) {
        $CI =& get_instance();
        // @phpstan-ignore-line
        return $CI->session->flashdata($type);
    }
}

if (!function_exists('campaign_type_meta')) {
    function campaign_type_meta($type) {
        $map = [
            'SMS' => ['icon' => 'bi-chat-dots', 'badge' => 'bg-primary text-white', 'preview' => 'sms'],
            'WhatsApp' => ['icon' => 'bi-whatsapp', 'badge' => 'bg-success text-white', 'preview' => 'whatsapp'],
            'WhatsApp Image' => ['icon' => 'bi-image', 'badge' => 'bg-success text-white', 'preview' => 'image'],
            'Status Messaging' => ['icon' => 'bi-broadcast', 'badge' => 'bg-warning text-dark', 'preview' => 'status'],
            'Custom' => ['icon' => 'bi-sliders', 'badge' => 'bg-secondary text-white', 'preview' => 'text']
        ];

        $resolved = $type ?: 'Custom';
        $meta = isset($map[$resolved]) ? $map[$resolved] : ['icon' => 'bi-megaphone', 'badge' => 'bg-secondary text-white', 'preview' => 'text'];
        $meta['label'] = $resolved;

        return $meta;
    }
}
