<?php

if (!function_exists('send_mail')) {

    function send_mail($destinatario, $subject, $message, $origen = 'default') {
        $config_email = ($origen === 'default') ? 'email' : $origen;
        $CI = &get_instance();
        $CI->load->library("email");
        $CI->config->load('email');
        $config = $CI->config->item($config_email);
        $CI->email->initialize($config);
        $CI->email->from($config['smtp_user']);
        if (ENVIRONMENT != 'production') {
            $destinatario = $CI->config->item('correo_tester');
        }
        if (is_array($destinatario)) {
            foreach ($destinatario as &$elemento) {
                $elemento = trim($elemento);
                unset($elemento);
            }
        } else {
            $destinatario = trim($destinatario);
        }
        $CI->email->to($destinatario);
        $CI->email->subject($subject);
        $CI->email->message(clean_mail_message($message));
        if ($CI->email->send()) {
            return TRUE;
        } else {
            $error = $CI->email->print_debugger();
            $log_error = "destinatario: " . json_encode($destinatario) . "\n";
            $log_error .= "subject: " . $subject . "\n";
            $log_error .= "message: " . $message . "\n";
            $log_error .= "config: " . json_encode($config) . "\n\n";
            $log_error .= $error;
            $CI->load->helper('custom_log');
            custom_log_message('error', $log_error, 'mail');
            throw new Exception($error);
        }
    }

}

if (!function_exists('send_mail_attached_files')) {

    function send_mail_attached_files($destinatario, $subject, $message, $attached_files = [], $origen = 'default') {
        $config_email = ($origen === 'default') ? 'email' : $origen;
        $CI = &get_instance();
        $CI->load->library("email");
        $CI->config->load('email');
        $config = $CI->config->item($config_email);
        $CI->email->initialize($config);
        $CI->email->from($config['smtp_user']);
        if (ENVIRONMENT != 'production') {
            $destinatario = $CI->config->item('correo_tester');
        }
        if (is_array($destinatario)) {
            foreach ($destinatario as &$elemento) {
                $elemento = trim($elemento);
                unset($elemento);
            }
        } else {
            $destinatario = trim($destinatario);
        }
        $CI->email->to($destinatario);
        $CI->email->subject($subject);
        $CI->email->message(clean_mail_message($message));
        if (is_array($attached_files)) {
            foreach ($attached_files as $file) {
                if (file_exists($file)) {
                    $CI->email->attach($file);
                } else {
                    throw new Exception("El archivo " . $file . " no existe.");
                }
            }
        } else if (is_string($attached_files)) {
            if (file_exists($attached_files)) {
                $CI->email->attach($attached_files);
            } else {
                throw new Exception("El archivo " . $attached_files . " no existe.");
            }
        }
        if ($CI->email->send()) {
            return TRUE;
        } else {
            $error = $CI->email->print_debugger();
            $log_error = "destinatario: " . json_encode($destinatario) . "\n";
            $log_error .= "subject: " . $subject . "\n";
            $log_error .= "message: " . $message . "\n";
            $log_error .= "config: " . json_encode($config) . "\n\n";
            $log_error .= $error;
            $CI->load->helper('custom_log');
            custom_log_message('error', $log_error, 'mail');
            throw new Exception($error);
        }
    }

}

if (!function_exists('encrypt_url')) {

    function encrypt_url($string, $key) {
        if ($string == NULL || $string == '') {
            show_error('Error: falta el código', 500, $heading = 'An Error Was Encountered');
        }
        if ($key == NULL || $key == '') {
            show_error('Error: falta el llave', 500, $heading = 'An Error Was Encountered');
        }
//        echo $string;
//        echo '.--.';
        $encrypted = encrypt_base64_encode($string, $key);
//        echo $encrypted;
        $encripted_encoded = rawurlencode($encrypted);
//        echo '.--.';
//        echo $encripted_encoded;
        return $encripted_encoded;
    }

}

if (!function_exists('decrypt_url')) {

    function decrypt_url($string_encripted_encoded, $key) {
        if ($string_encripted_encoded == NULL || $string_encripted_encoded == '') {
            show_error('Error: falta el código', 500, $heading = 'An Error Was Encountered');
        }
        if ($key == NULL || $key == '') {
            show_error('Error: falta la llave', 500, $heading = 'An Error Was Encountered');
        }
//        echo '::codificado::';
//        echo $string_encripted_encoded;
        $string_encrypted = rawurldecode($string_encripted_encoded);
//        echo '::decodificado::';
//        echo $string_encrypted;
        $result = decrypt_base64_encode($string_encrypted, $key);
//        echo '::descifrado::';
//        echo $result;
        return $result;
    }

}

if (!function_exists('encrypt_base64_encode')) {

    function encrypt_base64_encode($data, $key) {
        $cipher = "aes-256-cbc"; // Algoritmo de cifrado
        $ivlen = openssl_cipher_iv_length($cipher);
        $iv = openssl_random_pseudo_bytes($ivlen); // Generar un IV (vector de inicialización)
        $encrypted = openssl_encrypt($data, $cipher, $key, 0, $iv);
        // Para desencriptar más tarde, necesitaremos el IV, así que lo adjuntamos al texto cifrado
        $encrypted = base64_encode($iv . $encrypted);
        return $encrypted;
    }

}

if (!function_exists('decrypt_base64_encode')) {

    function decrypt_base64_encode($encrypted_data, $key) {
        $cipher = "aes-256-cbc";
        $encrypted_data = base64_decode($encrypted_data);
        $ivlen = openssl_cipher_iv_length($cipher);
        $iv = substr($encrypted_data, 0, $ivlen);
        $encrypted_text = substr($encrypted_data, $ivlen);
        $decrypted = openssl_decrypt($encrypted_text, $cipher, $key, 0, $iv);
        return $decrypted;
    }

}

if (!function_exists('clean_mail_message')) {

    function clean_mail_message($message) {
        $message_array1 = explode("\n", $message);
        $message_array2 = array_map('trim', $message_array1);
        $message_aux = implode("\n", $message_array2);
        return $message_aux;
    }

}