<?php

/**
 * -------------------------------------------------------------------
 * Developed and maintained by Nayeem
 * -------------------------------------------------------------------
 */
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

if (!function_exists('message_box')) {

    function message_box($message_type, $close_button = TRUE)
    {
        $CI = &get_instance();
        static $rendered = array();

        if (isset($rendered[$message_type])) {
            return '';
        }

        $message = $CI->session->flashdata($message_type);
        $retval = '';

        if ($message) {
            $rendered[$message_type] = true;
            $message_id_key = '_flash_message_id_' . $message_type;
            $message_id = $CI->session->flashdata($message_id_key);
            if (empty($message_id)) {
                $message_id = hash('sha256', $message_type . '|' . $message);
            }

            // CI3 stores flash markers in __ci_vars. Remove both the value and marker
            // immediately so layouts, AJAX navigation, and later pages cannot replay it.
            if (method_exists($CI->session, 'unmark_flash')) {
                $CI->session->unmark_flash(array($message_type, $message_id_key));
            }
            $CI->session->unset_userdata(array($message_type, $message_id_key));

            $payload = json_encode(array(
                'type' => $message_type,
                'message' => $message,
                'id' => $message_id
            ));
            $escaped_message_id = htmlspecialchars($message_id, ENT_QUOTES, 'UTF-8');
            $retval = "<script type=\"text/JavaScript\" data-erp-flash-message=\"{$escaped_message_id}\">
                (function(){
                    var p = $payload;
                    var key = 'erp-flash-message:' + p.id;
                    window.erpShownFlashMessages = window.erpShownFlashMessages || {};
                    if (window.erpShownFlashMessages[p.id]) {
                        return;
                    }
                    try {
                        if (window.sessionStorage && window.sessionStorage.getItem(key)) {
                            window.erpShownFlashMessages[p.id] = true;
                            return;
                        }
                        if (window.sessionStorage) {
                            window.sessionStorage.setItem(key, '1');
                        }
                    } catch (e) {}
                    window.erpShownFlashMessages[p.id] = true;
                    var attempts = 0;
                    var notify = function(){
                        if (window.toaster && typeof window.toaster[p.type] === 'function') {
                            window.toaster[p.type](p.message);
                            return;
                        }
                        if (window.toastr && typeof window.toastr[p.type] === 'function') {
                            window.toastr[p.type](p.message);
                            return;
                        }
                        attempts++;
                        if (attempts < 40) {
                            window.setTimeout(notify, 50);
                        }
                    };
                    if (document.readyState === 'loading') {
                        document.addEventListener('DOMContentLoaded', notify);
                    } else {
                        notify();
                    }
                })();
            </script>";
            if (strtolower((string) $message_type) === 'success') {
                $retval .= "<script type=\"text/JavaScript\">window.erpDatatableCacheBust = true;</script>";
            }
            return $retval;
        }
    }
}

if (!function_exists('set_message')) {
    function set_message($type, $message)
    {
        $CI = &get_instance();
        $message_id_key = '_flash_message_id_' . $type;
        if (method_exists($CI->session, 'unmark_flash')) {
            $CI->session->unmark_flash(array($type, $message_id_key));
        }
        $CI->session->unset_userdata(array($type, $message_id_key));
        $CI->session->set_flashdata($type, $message);
        $CI->session->set_flashdata($message_id_key, uniqid($type . '_', true));
        if (strtolower((string) $type) === 'success') {
            $CI->session->set_flashdata('datatable_cache_bust', 1);
        }
    }
}

if (!function_exists('show_notification')) {
    function show_notification($users = array())
    {
        $realtime_notification = config_item('realtime_notification');
        if (empty($realtime_notification)) {
            return false;
        }

        if (!is_array($users)) {
            return false;
        }

        if (count($users) == 0) {
            return false;
        }

        $legacyPusherPath = APPPATH . 'libraries/Pusher.php';
        $vendorAutoloadPath = FCPATH . 'vendor/autoload.php';
        $pusherClass = null;

        if (class_exists('Pusher')) {
            $pusherClass = 'Pusher';
        } elseif (class_exists('\Pusher\Pusher')) {
            $pusherClass = '\Pusher\Pusher';
        } else {
            if (file_exists($legacyPusherPath)) {
                require_once($legacyPusherPath);
            } elseif (file_exists($vendorAutoloadPath)) {
                require_once($vendorAutoloadPath);
            }

            if (class_exists('Pusher')) {
                $pusherClass = 'Pusher';
            } elseif (class_exists('\Pusher\Pusher')) {
                $pusherClass = '\Pusher\Pusher';
            } else {
                return false;
            }
        }

        $app_key = config_item('pusher_app_key');
        $app_secret = config_item('pusher_app_secret');
        $app_id = config_item('pusher_app_id');

        if ($app_key == "" || $app_secret == "" || $app_id == "") {
            return false;
        }

        $pusher_options = array(
            'timeout' => 2,
            'useTLS' => true,
            'encrypted' => true,
        );
        if (!isset($pusher_options['cluster']) && config_item('pusher_cluster') != '') {
            $pusher_options['cluster'] = config_item('pusher_cluster');
        }

        $channels = array();
        foreach ($users as $id) {
            array_push($channels, 'notifications-channel-' . $id);
        }
        $channels = array_unique($channels);
        if (empty($channels)) {
            return false;
        }

        try {
            $pusher = new $pusherClass(
                $app_key,
                $app_secret,
                $app_id,
                $pusher_options
            );
            $pusher->trigger($channels, 'notification', array());
        } catch (Throwable $e) {
            log_message('error', 'Pusher notification failed: ' . $e->getMessage());
            return false;
        }
    }
}
