<?php

namespace GlpiPlugin\Butterfly;

class Scss {

   static function hasScssSuport() {
      return class_exists(\ScssPhp\ScssPhp\Compiler::class);
   }

   static function compileScss($content, $variables = []) {
      global $GLPI_CACHE;

      $scss = new \ScssPhp\ScssPhp\Compiler();
      $scss->setOutputStyle(\ScssPhp\ScssPhp\OutputStyle::COMPRESSED);
      $scss->setSourceMap(\ScssPhp\ScssPhp\Compiler::SOURCE_MAP_NONE);
      
      // Convert variables using ValueConverter
      if (!empty($variables)) {
         $convertedVariables = [];
         foreach ($variables as $key => $value) {
            $convertedVariables[$key] = \ScssPhp\ScssPhp\ValueConverter::fromPhp($value);
         }
         $scss->addVariables($convertedVariables);
      }
      
      $scss->addImportPath(GLPI_ROOT);

      $scss->addImportPath(
         function ($path) {
            $file_chunks = [];
            if (!preg_match('/^~@?(?<directory>.*)\/(?<file>[^\/]+)(?:(\.scss)?)/', $path, $file_chunks)) {
               return null;
            }

            $possible_filenames = [
               sprintf('%s/css/lib/%s/%s.scss', GLPI_ROOT, $file_chunks['directory'], $file_chunks['file']),
               sprintf('%s/css/lib/%s/_%s.scss', GLPI_ROOT, $file_chunks['directory'], $file_chunks['file']),
            ];
            foreach ($possible_filenames as $filename) {
               if (file_exists($filename)) {
                  return $filename;
               }
            }

            return null;
         }
      );

      $content = str_replace('\"', '"', $content);

      $ckey = md5($content . json_encode($variables));

      if ($GLPI_CACHE->has($ckey) && !isset($_GET['reload']) && !isset($_GET['nocache'])) {
         $css = $GLPI_CACHE->get($ckey);
      } else {
         $css = $scss->compileString($content, GLPI_ROOT . '/butterfly.scss')->getCss();
         if (!isset($_GET['nocache'])) {
            $GLPI_CACHE->set($ckey, $css);
         }
      }

      return $css;
   }

   static function getLoginCSS($theme = null, $variables = []) {
      if (!$theme) {
         $theme = Config::getConfig("login_theme", '');
      }
      $themeInfo = null;
      if ($theme) {
         $themeInfo = Theme::getThemeInfo($theme);
      }

      $picture = Config::getConfig("login_background_picture", '');

      if (!$picture && $themeInfo && !empty($themeInfo['login-background'])) {
         $picture = $themeInfo['login-background'] . '&theme=' . $themeInfo['id'];
      }

      $css = '';
      if ($picture) {
         $pictureUrl = Toolbox::getPictureUrl($picture);

         $css .= "#firstboxlogin, #text-login, #logo_login, .login-container, .login-card, .glpi-login__wrapper, .main-content-card {";
         $css .= " background-color: transparent !important;";
         $css .= "}";
         $css .= "html, body {";
         $css .= " height: 100%;";
         $css .= "}";
         $css .= "body, body.login-page, body.welcome-anonymous {";
         $css .= " background-size: cover;";
         $css .= " background-repeat: no-repeat;";
         $css .= " background-position: center;";
         $css .= " background-image: url(\"" . $pictureUrl . "\");";
         $css .= "}";
         $css .= ".login-page__container::before, .login-page__illustration, .welcome-layout__background {";
         $css .= " background-image: none !important;";
         $css .= "}";
      }

      $css_type = Config::getConfig("login_css_type", 'scss');
      $css_custom = Config::getConfig("login_css_custom", '');

      $themeVariables = [];

      $css_custom = html_entity_decode($css_custom);

      if ($css_type === 'scss' && Scss::hasScssSuport()) {
         $variables = [];
         if ($themeInfo && isset($themeInfo['variables'])) {
            foreach ($themeInfo['variables'] as $k => $v) {
               $themeId = $themeInfo['id'];
               $fieldName = "login_theme-$themeId-$k";
               $fieldValue = Config::getConfig($fieldName, $v['default']);
               $variables[$k] = $fieldValue;
               $themeVariables[$k] = $fieldValue;
            }
         }

         if ($themeInfo && $themeInfo['login-scss']) {
            $scssPath = str_replace('\\', '/', $themeInfo['path'] . '/' . $themeInfo['login-scss']);
            $css_custom = "@import '" . $scssPath . "';\n" . $css_custom;
         }

         $variables['butterfly_timestamp'] = Toolbox::getTimestamp();

         try {
            $css .= Scss::compileScss($css_custom, $variables);
         } catch (\Throwable $th) {
            // Log error and continue with basic CSS
            error_log("SCSS compilation error: " . $th->getMessage());
         }
      } else {
         if ($themeInfo && $themeInfo['login-css']) {
            $css .= file_get_contents($themeInfo['path'] . '/' . $themeInfo['login-css']) . "\n";
         }

         if ($css_type === 'css') {
            $css .= $css_custom;
         }

         if ($themeInfo && isset($themeInfo['variables'])) {
            foreach ($themeInfo['variables'] as $k => $v) {
               $themeId = $themeInfo['id'];
               $fieldName = "login_theme-$themeId-$k";
               $fieldValue = Config::getConfig($fieldName, $v['default']);
               $themeVariables[$k] = $fieldValue;
            }
         }
      }

      $cardBg = null;

      if (!empty($themeVariables)) {
         $btnBg = $themeVariables['btn-background-color'] ?? null;
         $btnFg = $themeVariables['btn-foreground-color'] ?? null;
         if (isset($themeVariables['card-background-color']) && $themeVariables['card-background-color'] !== '') {
            $cardBg = \Html::cleanInputText($themeVariables['card-background-color']);
         }

         if ($btnBg) {
            $btnBg = \Html::cleanInputText($btnBg);
            $css .= ".form-footer .btn.btn-primary, .form-footer .btn-primary.w-100, .glpi-login__wrapper .btn.btn-primary {";
            $css .= " background-color: {$btnBg} !important;";
            $css .= " border-color: {$btnBg} !important;";
            $css .= "}";
            $css .= ".form-footer .btn.btn-primary:hover, .glpi-login__wrapper .btn.btn-primary:hover {";
            $css .= " filter: brightness(0.9);";
            $css .= "}";
         }
         if ($btnFg) {
            $btnFg = \Html::cleanInputText($btnFg);
            $css .= ".form-footer .btn.btn-primary, .glpi-login__wrapper .btn.btn-primary {";
            $css .= " color: {$btnFg} !important;";
            $css .= "}";
         }
         if ($cardBg) {
            $css .= ".page-anonymous .main-content-card {";
            $css .= " background-color: {$cardBg} !important;";
            $css .= "}";
         }
      }

      if (!$cardBg && ($themeInfo || $picture)) {
         $css .= ".page-anonymous .main-content-card {";
         $css .= " background-color: transparent !important;";
         $css .= " border: 0;";
         $css .= " box-shadow: none;";
         $css .= "}";
      }

      return $css;
   }
}
