<?php
declare(strict_types=1);

if (empty($noauth) && php_sapi_name() != 'cli') {
    require SITE_PATH . '/core/admin/includes/auth.php';
}

/**
 * Get admin folders from plugins and modules
 */
$admin_folders = [];

$module_types = [
    'plugins',
    'modules',
];

/*
 * Add shop and CMS by default to admin folders array
 */
foreach (['shop', 'cms', 'abs'] as $coreModule) {
    $pathCandidate = SITE_PATH . '/' . $coreModule . '/admin/';
    if (is_dir($pathCandidate)) {
        $admin_folders[] = $pathCandidate;
    }
}

foreach ($module_types as $module_type) {

    $moduleBase = SITE_PATH . '/' . $module_type . '/';
    if (!is_dir($moduleBase)) {
        continue;
    }

    $modules = scandir($moduleBase);
    if ($modules === false) {
        continue;
    }

    foreach ($modules as $module) {
        if ($module === '.' || $module === '..') {
            continue;
        }
        $module_admin_folder = $moduleBase . $module . '/admin/';
        if (is_dir($module_admin_folder)) {
            $admin_folders[] = $module_admin_folder;
        }
    }
}

/**
 * Get admin css/less and js files
 */
$admin_css_files_before = [];
$admin_css_files_after = [];
$admin_js_files = [];
$css_excluded_files = [
    '/core/admin/css/mtc_admin_style.less',
    '/core/admin/css/dynamic_before.less',
    '/core/admin/css/dynamic_after.less',
    '/shop/admin/css/print_order.css',
    '/core/css/style_404.less',
    '/core/css/datepicker.less',
    '/core/css/form.less',
    '/core/css/zoom.less',
    '/core/css/import.less',
];
$js_excluded_files = [
    '/core/js/less.js',
    '/core/js/vue.js',
    '/core/js/vue.min.js',
    '/core/js/pattern_browser.js',
    '/core/js/css_browser.js',
    '/core/js/jquery.js',
    '/core/js/jquery.datetimepicker.js',
    '/core/js/plugins/mtc_zoom.js',
    '/core/js/plugins/mtc_jquery_ui.js',
    '/core/js/site_scripts/mtc_show_hide_menus.js',
];

$es_module_js = [
    '/core/js/functions.js',
    '/core/js/plugins/mtc_vue_directives.js',
    '/core/js/plugins/mtc_vue_filters.js',
    '/core/js/plugins/mtc_vue_resource.js',
    '/modules/Members/js/mtc_follow_ups.js',
    '/modules/BasketRecovery/admin/js/mtc_follow_ups.js',
];

/**
 * Get default css/less and js
 */
$less_folders = [
    SITE_PATH . '/core/css/*.less',
    SITE_PATH . '/core/admin/css/plugins/*.css',
    SITE_PATH . '/core/admin/css/*.css',
    SITE_PATH . '/core/admin/css/*.less',
];
$js_folders = [
    SITE_PATH . '/core/js/tinymce/*.js',
    SITE_PATH . '/core/js/*.js',
    SITE_PATH . '/core/js/plugins/*.js',
    SITE_PATH . '/core/admin/js/plugins/*.js',
    SITE_PATH . '/core/admin/js/*.js',
];

// css/less
foreach ($less_folders as $directory) {
    $files = glob($directory, GLOB_NOSORT);
    if (empty($files)) {
        continue;
    }
    foreach ($files as $file_name) {
        $css_file = str_replace(SITE_PATH, '', $file_name);

        if (!in_array($css_file, $css_excluded_files, true)) {
            $admin_css_files_before[] = $css_file;
        }
    }
}

// js
foreach ($js_folders as $directory) {
    $files = glob($directory, GLOB_NOSORT);
    if (empty($files)) {
        continue;
    }
    foreach ($files as $file_name) {
        $js_file = str_replace(SITE_PATH, '', $file_name);

        if (!in_array($js_file, $js_excluded_files, true) && !in_array($js_file, $es_module_js, true)) {
            $admin_js_files[] = $js_file;
        }
    }
}

/**
 * Get admin extended file paths
 */
foreach ($admin_folders as $directory) {

    if (is_dir($directory . 'css/')) {
        // css
        $files = glob($directory . 'css/*.css', GLOB_NOSORT);
        if (!empty($files)) {
            foreach ($files as $file_name) {

                $css_file = str_replace(SITE_PATH, '', $file_name);

                if (!in_array($css_file, $css_excluded_files, true)) {
                    $admin_css_files_after[] = $css_file;
                }
            }
        }
        // less
        $files = glob($directory . 'css/*.less', GLOB_NOSORT);
        if (!empty($files)) {
            foreach ($files as $file_name) {

                $css_file = str_replace(SITE_PATH, '', $file_name);

                if (!in_array($css_file, $css_excluded_files, true)) {
                    $admin_css_files_after[] = $css_file;
                }
            }
        }
    }

    if (is_dir($directory . 'js/')) {
        $files = glob($directory . 'js/*.js', GLOB_NOSORT);
        if (!empty($files)) {
            foreach ($files as $file_name) {
                $admin_js_files[] = str_replace(SITE_PATH, '', $file_name);
            }
        }
    }
}

/**
 * Remove ES module files that may have slipped through globbing (in case of overrides)
 */
$admin_js_files = array_values(array_filter($admin_js_files, static function ($file) use ($es_module_js) {
    if (in_array($file, $es_module_js, true)) {
        return false;
    }

    $absolute = SITE_PATH . $file;

    if (is_readable($absolute)) {
        $handle = fopen($absolute, 'r');
        if ($handle) {
            $snippet = fread($handle, 512);
            fclose($handle);

            if ($snippet !== false) {
                $snippet = ltrim($snippet);
                if (str_starts_with($snippet, 'import ') || str_starts_with($snippet, 'export ')) {
                    return false;
                }
            }
        }
    }

    return true;
}));

$twig->addGlobal('admin_js_files', $admin_js_files);

/**
 * generate dynamic files
 */

//generate /core/admin/css/dynamic_before.less
$dynamic_less = SITE_PATH . '/core/admin/css/dynamic_before.less';
$less_data = implode(PHP_EOL, array_map(static fn($file) => "@import '../../../" . ltrim($file, '/') . "';", $admin_css_files_before));
$less_data .= PHP_EOL;

// write dynamic_before.less if it has changed
if (!file_exists($dynamic_less) || md5_file($dynamic_less) !== md5($less_data)) {
    file_put_contents($dynamic_less, $less_data, LOCK_EX);
}
unset($less_data);

//generate /core/admin/css/dynamic_after.less
$dynamic_less = SITE_PATH . '/core/admin/css/dynamic_after.less';
$less_data = implode(PHP_EOL, array_map(static fn($file) => "@import '../../../" . ltrim($file, '/') . "';", $admin_css_files_after));
$less_data .= PHP_EOL;

// write dynamic_after.less if it has changed
if (!file_exists($dynamic_less) || md5_file($dynamic_less) !== md5($less_data)) {
    file_put_contents($dynamic_less, $less_data, LOCK_EX);
}
unset($less_data);

//generate /core/admin/js/dynamic.json
$dynamic_json = SITE_PATH . '/core/admin/js/dynamic.json';
$jsonArray = array_map(static fn($file) => '../..' . $file, $admin_js_files);
$json_data = json_encode($jsonArray, JSON_PRETTY_PRINT);

// write dynamic_after.less if it has changed
if (!file_exists($dynamic_json) || md5_file($dynamic_json) !== md5($json_data)) {
    file_put_contents($dynamic_json, $json_data, LOCK_EX);
}
unset($json_data);

if (isset($adminuser)) {
    $new_message_count = \Mtc\Plugins\MembersMessaging\Classes\Message::getUnread($adminuser->user['id']);
    $twig->addGlobal('new_message_count', $new_message_count);
}
