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

/*
| -------------------------------------------------------------------------
| Hooks
| -------------------------------------------------------------------------
| This file lets you define "hooks" to extend CI without hacking the core.
| -------------------------------------------------------------------------
*/

// Boot the WordPress-style hooks if needed (no-op if already loaded via autoload helper).
if (!function_exists('do_action')) {
	include_once APPPATH . 'helpers/hooks_helper.php';
}

if (!function_exists('e')) {
	/**
	 * Encode HTML special characters in a string.
	 */
	function e($value, $doubleEncode = true)
	{
		if ($value instanceof BackedEnum) {
			$value = $value->value;
		}

		return htmlspecialchars($value ?? '', ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8', $doubleEncode);
	}
}

/**
 * Global hooks accessor (mirrors CI global $hooks).
 */
function hooks()
{
	global $hooks;
	return $hooks;
}

$hook['pre_system'][] = [
	'class'    => 'EnhanceSecurity',
	'function' => 'protect',
	'filename' => 'EnhanceSecurity.php',
	'filepath' => 'hooks',
	'params'   => [],
];

// $hook['pre_system'][] = [
// 	'class'    => 'Autoloader',
// 	'function' => 'register',
// 	'filename' => 'Autoloader.php',
// 	'filepath' => 'hooks',
// 	'params'   => [],
// ];

$hook['pre_system'][] = [
	'class'    => 'InitModule',
	'function' => 'handle',
	'filename' => 'InitModule.php',
	'filepath' => 'hooks',
	'params'   => [],
];

$hook['pre_controller_constructor'][] = [
	'class'    => '',
	'function' => '_app_init',
	'filename' => 'InitHook.php',
	'filepath' => 'hooks',
];

$hook['post_controller'] = function () {
	if (PHP_SAPI === 'cli') {
		return;
	}

	$ci = get_instance();

	if (!$ci->input->is_ajax_request()) {
		$currentUrl = current_full_url();

		$skip = [
			'pusher_auth',
			'download/preview_image',
			'download/preview_video',
			'download/file'
		];

		$remember = true;

		foreach ($skip as $haystack) {
			if (strpos($currentUrl, $haystack) !== false) {
				$remember = false;
				break;
			}
		}

		if ($remember) {
			$ci->session->set_userdata('_prev_url', $currentUrl);
		}
	}
};

if (file_exists(APPPATH . 'config/my_hooks.php')) {
	include_once APPPATH . 'config/my_hooks.php';
}
