<?php

/**
 * @file
 * Theme functions.
 */

// Include all files from the includes directory.
$includes_path = __DIR__ . '/includes/*.theme';
foreach (glob($includes_path) as $file) {
  require_once __DIR__ . '/includes/' . basename($file);
}

/**
 * Implements hook_preprocess_html().
 */
function starman_preprocess_html(&$variables) {
  // Obtener configuración del tema
  $theme_settings = \Drupal::config('starman.settings');

  // Obtener colores configurados o usar valores por defecto
  $colors = [
    'main' => $theme_settings->get('main_color') ?: '#667eea',
    'main_hover' => $theme_settings->get('main_color_hover') ?: '#5a6fd8',
    'secondary' => $theme_settings->get('secondary_color') ?: null,
    'accent' => $theme_settings->get('accent_color') ?: null,
  ];

  // Configuración de barra promocional
  $promo_bg_color = $theme_settings->get('promo_background_color');
  if (!empty($promo_bg_color)) {
    $colors['promo_bg'] = $promo_bg_color;
  }

  // Crear variables CSS dinámicas - siempre incluir los principales
  $css_variables = [
    '--starman-primary-color' => $colors['main'],
    '--starman-primary-hover' => $colors['main_hover'],
  ];

  // Solo agregar colores opcionales si están definidos
  if (!empty($colors['secondary'])) {
    $css_variables['--starman-secondary-color'] = $colors['secondary'];
  } else {
    // Si no hay color secundario, usar el principal para gradientes
    $css_variables['--starman-secondary-color'] = $colors['main'];
  }

  if (!empty($colors['accent'])) {
    $css_variables['--starman-accent-color'] = $colors['accent'];
  }

  if (!empty($colors['promo_bg'])) {
    $css_variables['--starman-promo-bg'] = $colors['promo_bg'];
  } else {
    $css_variables['--starman-promo-bg'] = $colors['main'];
  }

  // Convertir colores a RGB y HSL para más flexibilidad - solo para colores definidos
  foreach ($colors as $key => $color) {
    // Saltar colores que son null (opcionales no definidos)
    if (empty($color)) {
      continue;
    }

    $rgb = hex2rgb($color);
    $hsl = rgb2hsl($rgb[0], $rgb[1], $rgb[2]);

    $css_variables["--starman-{$key}-rgb"] = implode(', ', $rgb);
    $css_variables["--starman-{$key}-hsl"] = implode(', ', $hsl);

    // Generar variaciones automáticas
    $css_variables["--starman-{$key}-light"] = "hsl({$hsl[0]}, {$hsl[1]}%, " . min(95, $hsl[2] + 20) . "%)";
    $css_variables["--starman-{$key}-dark"] = "hsl({$hsl[0]}, {$hsl[1]}%, " . max(5, $hsl[2] - 20) . "%)";
    $css_variables["--starman-{$key}-alpha-10"] = "rgba({$rgb[0]}, {$rgb[1]}, {$rgb[2]}, 0.1)";
    $css_variables["--starman-{$key}-alpha-20"] = "rgba({$rgb[0]}, {$rgb[1]}, {$rgb[2]}, 0.2)";
  }

  // Agregar las variables CSS al head
  $css_vars = ':root { ';
  foreach ($css_variables as $property => $value) {
    $css_vars .= $property . ': ' . $value . '; ';
  }
  $css_vars .= '}';

  $variables['#attached']['html_head'][] = [
    [
      '#tag' => 'style',
      '#value' => $css_vars,
    ],
    'starman_css_variables'
  ];
}

/**
 * Función helper para convertir hex a RGB.
 */
function hex2rgb($hex) {
  $hex = str_replace('#', '', $hex);

  if (strlen($hex) == 3) {
    $r = hexdec(substr($hex, 0, 1) . substr($hex, 0, 1));
    $g = hexdec(substr($hex, 1, 1) . substr($hex, 1, 1));
    $b = hexdec(substr($hex, 2, 1) . substr($hex, 2, 1));
  } else {
    $r = hexdec(substr($hex, 0, 2));
    $g = hexdec(substr($hex, 2, 2));
    $b = hexdec(substr($hex, 4, 2));
  }

  return [$r, $g, $b];
}

/**
 * Función helper para convertir RGB a HSL.
 */
function rgb2hsl($r, $g, $b) {
  $r /= 255;
  $g /= 255;
  $b /= 255;

  $max = max($r, $g, $b);
  $min = min($r, $g, $b);

  $h = $s = $l = ($max + $min) / 2;

  if ($max == $min) {
    $h = $s = 0; // Gris
  } else {
    $d = $max - $min;
    $s = $l > 0.5 ? $d / (2 - $max - $min) : $d / ($max + $min);

    switch ($max) {
      case $r: $h = ($g - $b) / $d + ($g < $b ? 6 : 0); break;
      case $g: $h = ($b - $r) / $d + 2; break;
      case $b: $h = ($r - $g) / $d + 4; break;
    }
    $h /= 6;
  }

  return [round($h * 360), round($s * 100), round($l * 100)];
}

/**
 * Implements hook_preprocess_page().
 */
function starman_preprocess_page(&$variables) {
  $theme_settings = \Drupal::config('starman.settings');

  // Asegurar que las variables básicas estén disponibles
  $variables['logo'] = $variables['logo'] ?? '';
  $variables['logo_url'] = '/' . $theme_settings->get('logo.path');
  $variables['logo2_url'] = '/' . $theme_settings->get('logo.path');
  $variables['site_name'] = $variables['site_name'] ?? \Drupal::config('system.site')->get('name');
  $variables['front_page'] = $variables['front_page'] ?? '/';

  // Cargar el menú principal directamente si no está disponible en las regiones
  if (empty($variables['page']['primary_menu'])) {
    $menu_tree = \Drupal::menuTree();
    $menu_name = 'main';
    $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
    $tree = $menu_tree->load($menu_name, $parameters);
    $manipulators = [
      ['callable' => 'menu.default_tree_manipulators:checkAccess'],
      ['callable' => 'menu.default_tree_manipulators:generateIndexAndSort'],
    ];
    $tree = $menu_tree->transform($tree, $manipulators);
    $menu_build = $menu_tree->build($tree);

    $variables['main_menu_direct'] = $menu_build;
  }


  // Configuración del header con valores por defecto robustos
  $variables['header_config'] = [
    'type' => $theme_settings->get('header_type') ?: 'modern',
    'show_promo_bar' => $theme_settings->get('show_promo_bar') ?? TRUE,
    'promo_text' => $theme_settings->get('promo_text') ?: 'Envío gratuito en compras superiores a $150.000 y devoluciones de 30 días',
    'show_search' => $theme_settings->get('show_search') ?? TRUE,
    'show_user_account' => $theme_settings->get('show_user_account') ?? TRUE,
    'show_cart' => $theme_settings->get('show_cart') ?? TRUE,
    'show_locale_selector' => $theme_settings->get('show_locale_selector') ?? TRUE,
    'currency' => $theme_settings->get('currency_display') ?: '$ COP',
  ];
}

/**
 * Implements hook_theme().
 */
function starman_theme($existing, $type, $theme, $path) {
  return [
    'header' => [
      'variables' => [
        'header_config' => NULL,
        'logo2_url' => NULL,
        'site_name' => NULL,
        'front_page' => NULL,
        'main_menu' => NULL,
        'show_user_account' => NULL,
        'show_cart' => NULL,
        'show_locale_selector' => NULL,
      ],
      'template' => 'header',
      'path' => $path . '/templates',
    ],
  ];
}


