<?php

use App\Models\AdminChurchModel;

if (!function_exists('getAdminChurchIds')) {
    function getAdminChurchIds(int $adminId): ?array
    {
        if (!$adminId) return [0];

        if (session()->get('role_id') == 1) {
            return null;
        }

        $model = new \App\Models\AdminChurchModel();
        $result = $model->where('admin_id', $adminId)->findAll();
        $ids = array_column($result, 'church_id');
        
        return !empty($ids) ? $ids : [0];
    }
}

if (!function_exists('dot_array_search')) {
    function dot_array_search(string $index, array $array)
    {
        $keys = explode('.', $index);
        foreach ($keys as $key) {
            if (!is_array($array) || !array_key_exists($key, $array)) {
                return null;
            }
            $array = $array[$key];
        }
        return $array;
    }
}

if (!function_exists('sanitize_alphanumeric_space')) {
    function sanitize_alphanumeric_space(?string $text): string
    {
        if ($text === null) {
            return '';
        }
        $cleanedText = preg_replace('/[^a-zA-Z\s]/', '', $text);
        return trim(preg_replace('/\s+/', ' ', $cleanedText));
    }
}
if (!function_exists('sanitize_filename')) {
    function sanitize_filename(string $filename): string
    {
        $filename = preg_replace('/[\/\\\?%*:|"<>]/', '', $filename);
        $filename = preg_replace('/\s+/', '_', $filename);
        $filename = str_replace('..', '', $filename);

        return $filename;
    }
}

if (!function_exists('getAdminChurchIds')) {
    function getAdminChurchIds(int $adminId): ?array
    {
        if (!$adminId) return [];

        $model = new \App\Models\AdminChurchModel();
        $result = $model->where('admin_id', $adminId)->findAll();

        if (empty($result)) {
            return null;
        }

        return array_column($result, 'church_id');
    }
}

if (!function_exists('strip_leading_zeros')) {
    function strip_leading_zeros(?string $value): ?string
    {
        if ($value === null || $value === '' || !ctype_digit($value)) {
            return $value;
        }
        // Ubah ke integer lalu kembali ke string untuk menghapus leading zeros.
        return (string)(int)$value;
    }
}

if (!function_exists('get_database_enum_values')) {
    function get_database_enum_values(string $table, string $column): array
    {
        $db = \Config\Database::connect();
        $query = $db->query("SHOW COLUMNS FROM `$table` LIKE '$column'");
        $row = $query->getRow();

        if (!$row) {
            return [];
        }

        preg_match("/^enum\((.*)\)$/", $row->Type, $matches);

        if (!isset($matches[1])) {
            return [];
        }

        // Pisahkan dan bersihkan tanda kutip
        $enum = explode(",", $matches[1]);
        return array_map(function ($value) {
            return trim($value, "'");
        }, $enum);
    }
}

?>