<?php
require_once __DIR__.'/htmlpurifier/HTMLPurifier.auto.php';

function get_html_purifier() {
    static $purifier = null;

    if ($purifier === null) {
        $config = HTMLPurifier_Config::createDefault();
        $config->set('Core.Encoding', 'UTF-8');
        $config->set('HTML.Allowed', 'b,i,u,a[href|target|rel],br,p,ul,ol,li,span,strong,em');
        $config->set('CSS.AllowedProperties', ['color','font-size','font-weight','text-decoration','font-style']);
        $config->set('URI.AllowedSchemes', ['https' => true]);
        $config->set('Attr.AllowedFrameTargets', ['_blank']);
    
        $purifier = new HTMLPurifier($config);
    }

    return $purifier;
}

function clean_value($value) {
    $purifier = get_html_purifier();

    if (is_array($value)) {
        return array_map('clean_value', $value);
    }

    if (!is_scalar($value)) {
        return '';
    }

    if (is_numeric($value)) {
        return $value + 0;
    }

    if (is_string($value)) {
        $value = trim($value);
        $value = mb_convert_encoding($value, 'UTF-8', 'auto');
        return $purifier->purify($value);
    }

    return '';
}

function clean_array(array $data) {
    $cleaned = [];
    foreach ($data as $key => $value) {
        $clean_key = preg_replace('/[^a-zA-Z0-9_\-]/', '', $key);
        $cleaned[$clean_key] = clean_value($value);
    }
    return $cleaned;
}

// تنظيف المدخلات العامة
$GET     = clean_array($_GET);
$POST    = clean_array($_POST);
$COOKIE  = clean_array($_COOKIE);


if (!empty($_SESSION)) {
    foreach ($_SESSION as $key => $value) {
        $_SESSION[$key] = clean_value($value); // تنظيف القيم فقط
    }
}

if(isset($post_data)){
	if (is_array($post_data)) {
		$post_data = clean_array($post_data);
	}
}
?>