<?php
class utility {

public function __construct() {
$env = file_get_contents(".env");
$lines = explode("\n",$env);

foreach($lines as $line){
preg_match("/([^#]+)\=(.*)/",$line,$matches);
if(isset($matches[2])){ putenv(trim($line)); }
}
}

public function sanitize($input) {
$input = trim($input);
$input = stripslashes($input);
$input = htmlspecialchars($input);
$input = strip_tags($input);

return $input;
}

public function sanitize_request($request) {
$temp_Arr = array();
foreach ($request as $key => $value) {

if (is_array($value)) {

$temp_Arr[$key] = serialize($value);

}else{
if ($key !== 'csrf_token' AND $key !== 'id' AND $key !== 'csrf_form_id' AND $key !== 'submit'){
if ($key == 'fname' OR $key == 'lname' OR $key == 'name' OR $key == 'first_name' OR $key == 'last_name' OR $key == 'title') {
$temp_Arr[$key] = $this->sanitize(ucwords($value));
}elseif($key == 'code') {
$temp_Arr[$key] = $this->sanitize(strtoupper($value));
}else{
$key == 'hashed_pw' ? $temp_Arr[$key] = password_hash($value,PASSWORD_BCRYPT) : $temp_Arr[$key] = $this->sanitize($value);
}
}
}

}
return $temp_Arr;
}

public function setMessage($tpye, $message) {

$_SESSION['alert'] = array (array($tpye,$message));

}

public function uploader($path, $file, $file_name, $extensions) {

$target_dir = $path;
$ext = explode(",", $extensions);
$target_file_0 = $target_dir . basename($file["file"]["name"]);
$FileType = strtolower(pathinfo($target_file_0,PATHINFO_EXTENSION));
$target_file = $target_dir . $file_name.'.png';

$file_status = 1;

if ($file["file"]["size"] > ((int)(ini_get('upload_max_filesize'))*1000000)) {
return "Sorry, your file is too large.";
}elseif (!in_array($FileType, $ext)) {
return "Sorry, only $extensions files are allowed";
}elseif (move_uploaded_file($file["file"]["tmp_name"], $target_file)) {
return "OK";
}else {
return "Sorry, there was an error uploading your file.";
}

}


public function extension($file) {

$target_file_0 = basename($file["file"]["name"]);
return strtolower(pathinfo($target_file_0,PATHINFO_EXTENSION));

}

public function strip_tags_content($string) {
$string = preg_replace ('/<[^>]*>/', ' ', $string);

$string = str_replace("\r", '', $string);
$string = str_replace("\n", ' ', $string);
$string = str_replace("\t", ' ', $string);

$string = trim(preg_replace('/ {2,}/', ' ', $string));
return $string;

}

public function delete_file($file) {
unlink($file);
}

public function check_menu($x, $y) {
$y = explode(",",$y);
if (in_array($x, $y))
{
return 'active open';
}
else
{
return '';
}
}

public function genRandString($length) {
$stringSpace = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$pieces = [];
$max = mb_strlen($stringSpace, '8bit') - 1;
for ($i = 0; $i < $length; ++ $i) {
$pieces[] = $stringSpace[random_int(0, $max)];
}
return implode('', $pieces);
}

public function get_page() {
$x = explode("/",$_SERVER['REQUEST_URI']);
$y = count($x);
$z = ($y-1);
return $x[$z];
}

public function action_name(): string {
if (php_sapi_name() === 'cli') {
return basename($_SERVER['argv'][0] ?? '');
}

$candidates = [
'SCRIPT_NAME',
'PHP_SELF',
'SCRIPT_FILENAME',
'REQUEST_URI'
];

foreach ($candidates as $key) {
if (empty($_SERVER[$key])) continue;
$path = $_SERVER[$key];

if ($key === 'REQUEST_URI') {
$path = parse_url($path, PHP_URL_PATH) ?: $path;
}

$name = basename($path);
if ($name !== '' && $name !== '/' && strpos($name, '.') !== false) {
return $name;
}
}

return '';
}

public function generate_reg_no($lastRegNo, $gender, $prefix) {
$currentYear = date('y');
$genderCode = $gender == 'Female' ? '1' : '2';
if (empty($lastRegNo)) {
$last_entry = $prefix.'/'.$currentYear.'/'.$genderCode.'/000001';
}else{
$last_entry = $prefix.'/'.$currentYear.'/'.$genderCode.'/'.sprintf("%06d", explode("/", $lastRegNo)[3]+1);
}
return $last_entry;
}

public function score($x) {
if ($x === null || $x === '' || $x === '-' || trim($x) === '') {
return '-';
}

if (is_numeric($x)) {
$x = (float)$x;

if ($x >= 100) {
return (int)$x;
}

if (fmod($x, 1) == 0) {
return number_format($x, 1);
}

return number_format($x, 1);
}

return $x;
}


public function generateSerialSecure() {
$prefix = 'SN';
$timestampPart = str_pad(substr(time(), -10), 10, '0', STR_PAD_LEFT);
return $prefix . $timestampPart . bin2hex(random_bytes(8));
}

public function getClientIP()
{
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
return trim($ips[0]);
} elseif (!empty($_SERVER['HTTP_X_REAL_IP'])) {
return $_SERVER['HTTP_X_REAL_IP'];
} else {
return $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
}
}



public function createResetToken() {
$token = bin2hex(random_bytes(32));
$expires = date("Y-m-d H:i:s", time() + (30 * 60));

return [
'token' => $token,
'expires' => $expires
];
}


public function passwordDoesNotMatchAny($password, $hashArray) {
foreach ($hashArray as $hash) {
if (password_verify($password, $hash)) {
return false;
}
}
return true;
}

public function verifyResetToken($token_data) {

if (strtotime($token_data['expire_date']) < time()) {
return false;
}else{
return true;
}

}

public function generateReference($prefix = "REF")
{
return $prefix . '-' . date('YmdHis') . '-' . rand(1000, 9999);
}

}
?>
