<?php

/**
 * Car-Dealer-Show functions and definitions
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @package Car-Dealer-Show
 * @since Car-Dealer-Show 1.0
 */
if (!defined('ABSPATH')) {
  exit; // Exit if accessed directly.
}
if (!defined('CAR_DEALER_SHOW_URL')) {
  define('CAR_DEALER_SHOW_URL', get_template_directory_uri());
}
function car_dealer_show_categories()
{
  $categories = [
    'car-dealer-show/faq' => ['label' => __('FAQ', 'car-dealer-show')],
    'car-dealer-show/services' => ['label' => __('Services', 'car-dealer-show')],
    'car-dealer-show/page' => ['label' => __('Pages', 'car-dealer-show')],
    'car-dealer-show/about' => ['label' => __('about', 'car-dealer-show')],
    'car-dealer-show/why' => ['label' => __('Why Choose Us', 'car-dealer-show')],
    'car-dealer-show/general' => ['label' => __('General', 'car-dealer-show')]
  ];
  foreach ($categories as $slug => $args) {
    if (!WP_Block_Pattern_Categories_Registry::get_instance()->is_registered($slug)) {
      register_block_pattern_category($slug, $args);
    }
  }
}
add_action('init', 'car_dealer_show_categories', 5); // Prioridade mais alta
function car_dealer_show_get_pattern_content_from_file($pattern_file_path)
{
  $theme_dir = realpath(get_template_directory());
  $real_path = realpath($pattern_file_path);
  if (!$real_path || strpos($real_path, $theme_dir) !== 0) {
    if (defined('WP_DEBUG') && WP_DEBUG) {
      trigger_error(esc_html__('Invalid pattern file path: ', 'car-dealer-show') . esc_html($pattern_file_path), E_USER_WARNING);
    }
    return '';
  }
  if (!file_exists($real_path)) {
    if (defined('WP_DEBUG') && WP_DEBUG) {
      trigger_error(esc_html__('Pattern file not found: ', 'car-dealer-show') . esc_html($real_path), E_USER_WARNING);
    }
    return '';
  }
  ob_start();
  include $real_path;
  return ob_get_clean();
}

function car_dealer_show_register_all_patterns()
{
  static $has_run = false;

  if ($has_run) {
    return;
  }

  $has_run = true;


  $patterns = [
    'header-default'        => ['title' => __('Default Header', 'car-dealer-show'), 'categories' => ['car-dealer-show/page']],
    'footer-default'        => ['title' => __('Default Footer', 'car-dealer-show'), 'categories' => ['car-dealer-show/page']],
    'services'              => ['title' => __('Services Section', 'car-dealer-show'), 'categories' => ['car-dealer-show/services']],
    'services-2'            => ['title' => __('Services With Icons', 'car-dealer-show'), 'categories' => ['car-dealer-show/services']], // <-- LINHA ADICIONADA AQUI
    'deals'                 => ['title' => __('Buy/Sell Deals', 'car-dealer-show'), 'categories' => ['car-dealer-show/services']],
    'deals2'                => ['title' => __('Buy/Sell Deals2', 'car-dealer-show'), 'categories' => ['car-dealer-show/services']],
    'about'                 => ['title' => __('about Us', 'car-dealer-show'), 'categories' => ['car-dealer-show/about']],
    'faq'                   => ['title' => __('FAQ Section', 'car-dealer-show'), 'categories' => ['car-dealer-show/faq']],
    'show-room'             => ['title' => __('Show Room Section', 'car-dealer-show'), 'categories' => ['car-dealer-show/general']],
    '404-content'           => ['title' => __('404 Page Content', 'car-dealer-show'), 'categories' => ['car-dealer-show/page']],
    'template-query-loop'   => ['title' => __('Post List', 'car-dealer-show'), 'categories' => ['query']],
    'why'                   => ['title' => __('Why Choose Us', 'car-dealer-show'), 'categories' => ['car-dealer-show/why']],
    'simple-content'        => ['title' => __('Simple Content Section', 'car-dealer-show'), 'categories' => ['car-dealer-show/general']],
    'slider'                => ['title' => __('Car Dealer Slider', 'car-dealer-show'), 'categories' => ['car-dealer-show/general']],
  ];

  foreach ($patterns as $slug => $details) {
    $pattern_name = "car-dealer-show/{$slug}";


    if (WP_Block_Patterns_Registry::get_instance()->is_registered($pattern_name)) {
      continue;
    }

    $content = car_dealer_show_get_pattern_content_from_file(get_theme_file_path("/patterns/{$slug}.php"));

    if (empty($content)) {
      if (defined('WP_DEBUG') && WP_DEBUG) {
        trigger_error(
          esc_html__('Skipping pattern registration: Content is empty for pattern file: ', 'car-dealer-show') . esc_html($slug) . '.php',
          E_USER_WARNING
        );
      }
      continue;
    }

    register_block_pattern(
      $pattern_name,
      [
        'title'       => $details['title'],
        'content'     => $content,
        'categories'  => $details['categories'],
      ]
    );
  }
}
add_action('init', 'car_dealer_show_register_all_patterns', 10); // Prioridade mais baixa
if (!function_exists('car_dealer_show_block_styles')) :
  function car_dealer_show_block_styles()
  {
    $block_styles = [
      'core/details' => [
        'name' => 'arrow-icon-details',
        'label' => esc_attr__('Arrow icon', 'car-dealer-show'),
        'style_handle' => 'car-dealer-show-arrow-icon-details',
      ],
      'core/post-terms' => [
        'name' => 'pill',
        'label' => esc_attr__('Pill', 'car-dealer-show'),
        'style_handle' => 'car-dealer-show-post-terms-pill',
      ],
      'core/list' => [
        'name' => 'checkmark-list',
        'label' => esc_attr__('Checkmark', 'car-dealer-show'),
        'style_handle' => 'car-dealer-show-checkmark-list',
      ],
      'core/navigation-link' => [
        'name' => 'arrow-link',
        'label' => esc_attr__('With arrow', 'car-dealer-show'),
        'style_handle' => 'car-dealer-show-arrow-link',
      ],
      'core/heading' => [
        'name' => 'asterisk',
        'label' => esc_attr__('With asterisk', 'car-dealer-show'),
        'style_handle' => 'car-dealer-show-heading-asterisk',
      ],
    ];
    $style_path = get_theme_file_path('assets/css/block-styles.css');
    $style_src = get_theme_file_uri('assets/css/block-styles.css');
    foreach ($block_styles as $block => $args) {
      register_block_style($block, [
        'name' => $args['name'],
        'label' => $args['label'],
      ]);
      if (file_exists($style_path)) {
        wp_enqueue_block_style($block, [
          'handle' => $args['style_handle'],
          'src' => $style_src,
          'path' => $style_path,
          'ver' => wp_get_theme()->get('Version'),
        ]);
      } elseif (defined('WP_DEBUG') && WP_DEBUG) {
        trigger_error(esc_html__('Block style file not found: ', 'car-dealer-show') . esc_html($style_path), E_USER_WARNING);
      }
    }
  }
endif;
add_action('init', 'car_dealer_show_block_styles');
if (!function_exists('car_dealer_show_block_stylesheets')) :
  function car_dealer_show_block_stylesheets()
  {
    $style_path = get_theme_file_path('assets/css/button-outline.css');
    if (file_exists($style_path)) {
      wp_enqueue_block_style(
        'core/button',
        [
          'handle' => 'car-dealer-show-button-style-outline',
          'src'    => get_theme_file_uri('assets/css/button-outline.css'),
          'ver'    => wp_get_theme()->get('Version'),
          'path'   => $style_path,
        ]
      );
    } elseif (defined('WP_DEBUG') && WP_DEBUG) {
      trigger_error(esc_html__('Block style file not found: ', 'car-dealer-show') . esc_html($style_path), E_USER_WARNING);
    }
  }
endif;
add_action('init', 'car_dealer_show_block_stylesheets');
$dashboard_file = get_template_directory() . '/dashboard/dashboard.php';
if (file_exists($dashboard_file)) {
  require_once $dashboard_file;
} elseif (defined('WP_DEBUG') && WP_DEBUG) {
  trigger_error(esc_html__('Dashboard file not found: ', 'car-dealer-show') . esc_html($dashboard_file), E_USER_WARNING);
}

function car_dealer_show_theme_enqueue_styles()
{
  wp_enqueue_style(
    'car-dealer-show-style',
    get_stylesheet_uri(),
    [],
    wp_get_theme()->get('Version')
  );
}
add_action('wp_enqueue_scripts', 'car_dealer_show_theme_enqueue_styles');

//  add_theme_support('title-tag');
function car_dealer_show_setup()
{
  add_theme_support('post-thumbnails');
  add_theme_support('custom-logo');
  add_theme_support('align-wide');
  add_theme_support('responsive-embeds');
  add_theme_support('wp-block-styles');
  add_theme_support('editor-styles');

  $editor_styles = [
    'style.css',
    'assets/css/editor-style.css',
  ];

  foreach ($editor_styles as $style) {
    $style_path = get_theme_file_path($style);
    if (file_exists($style_path)) {
      add_editor_style($style);
    } elseif (defined('WP_DEBUG') && WP_DEBUG) {
      trigger_error(esc_html__('Editor style file not found: ', 'car-dealer-show') . esc_html($style_path), E_USER_WARNING);
    }
  }
}
add_action('after_setup_theme', 'car_dealer_show_setup');

/*
add_action('init', function () {
  $theme_uri = esc_url(get_template_directory_uri());
  $pattern_file = __DIR__ . '/patterns/header-default.html';

  if (file_exists($pattern_file)) {
    $pattern_content = file_get_contents($pattern_file);
    // Substitui o marcador pelo caminho real do tema
    $pattern_content = str_replace('{theme_uri}', $theme_uri, $pattern_content);

    //'title'       => __('Default Header', 'car-dealer-show'),
 
    register_block_pattern(
      'car-dealer-show/header-default',
      array(
        'description' => __('A default header with logo, location, phone, and email icons.', 'car-dealer-show'),
        'content'     => $pattern_content,
        'categories'  => array('header'),
      )
    );
  }
});
*/

/**
 * Checks if the required 'Car Dealer' plugin is installed.
 * If not, it displays a dismissible admin notice.
 */
function car_dealer_show_check_required_plugin()
{

  // Define the full path to the plugin's main file.
  // The path is folder-name/main-php-file.php. For the Car Dealer plugin, it's typically 'cardealer/cardealer.php'.
  $plugin_path = WP_PLUGIN_DIR . '/cardealer/cardealer.php';

  // Check directly on the file system if the plugin file does NOT exist.
  // This is the most reliable method and is not affected by WordPress cache.
  if (!file_exists($plugin_path)) {

    // The slug of the plugin to create the installation link.
    $plugin_slug = 'cardealer';
    $install_url = admin_url('plugin-install.php?tab=search&s=' . $plugin_slug);

    // The message to be displayed in the notice.
    $message = sprintf(
      esc_html__('The Car Dealer Show theme requires the free "Car Dealer" plugin for full functionality. %s', 'car-dealer-show'),
      '<a href="' . esc_url($install_url) . '"><strong>' . esc_html__('Please install the plugin from the WordPress directory.', 'car-dealer-show') . '</strong></a>'
    );

    // Output the admin notice HTML with the correct classes for styling and the dismiss button.
    printf(
      '<div class="notice notice-warning is-dismissible"><p>%s</p></div>',
      $message
    );
  }
}
// Add the function to the 'admin_notices' action hook to display it in the dashboard.
add_action('admin_notices', 'car_dealer_show_check_required_plugin');




function car_dealer_show_load_theme_color_palette()
{
  // Obter o estilo selecionado
  $selected_style = get_theme_mod('car_dealer_show_selected_style', 'blue');
  $json_file = get_template_directory() . '/styles/colors/' . $selected_style . '.json';

  // Fallback para blue se o arquivo não existir
  if (!file_exists($json_file)) {
    $json_file = get_template_directory() . '/styles/colors/blue.json';
  }

  // Ler e decodificar o JSON
  $json_data = file_get_contents($json_file);
  $color_data = json_decode($json_data, true);

  return $color_data;
}

function car_dealer_show_apply_theme_colors()
{
  //$selected_style = get_theme_mod('selected_style', '');
  $user_has_chosen = get_theme_mod('car_dealer_show_user_has_chosen_style', false);
  if ($user_has_chosen) {
    return;
  }
  $color_data = car_dealer_show_load_theme_color_palette();
  if (!$color_data) {
    return;
  }
  $css = '';
  // 1. Variáveis CSS
  if (isset($color_data['settings']['color']['palette'])) {
    $css .= ':root {';
    foreach ($color_data['settings']['color']['palette'] as $color) {
      if (isset($color['slug']) && isset($color['color'])) {
        $css .= '--wp--preset--color--' . $color['slug'] . ': ' . $color['color'] . ';';
      }
    }
    $css .= '}';
  }
  // 2. Estilos para headings (usar valores reais)
  $contrast_color = '#000000'; // Fallback
  if (isset($color_data['settings']['color']['palette'])) {
    foreach ($color_data['settings']['color']['palette'] as $color) {
      if ($color['slug'] === 'contrast') {
        $contrast_color = $color['color'];
        break;
      }
    }
  }
  $css .= '.wp-block-heading, h1, h2, h3, h4, h5, h6 { color: ' . $contrast_color . ' !important; }';
  $css .= 'h2.wp-block-heading { color: ' . $contrast_color . ' !important; }';
  // 3. Adicionar CSS diretamente no head
  echo '<style id="theme-color-styles">' . $css . '</style>';
}
add_action('wp_head', 'car_dealer_show_apply_theme_colors', 10);

function car_dealer_show_apply_palette_as_user_choice()
{
  // Só se ainda não houver paleta escolhida
  if (get_theme_mod('car_dealer_show_user_has_chosen_style', false)) {
    return;
  }

  $color_data = car_dealer_show_load_theme_color_palette();
  if (!$color_data || !isset($color_data['settings']['color']['palette'])) {
    return;
  }

  // Salva cada cor do JSON como theme_mod
  foreach ($color_data['settings']['color']['palette'] as $color) {
    if (isset($color['slug']) && isset($color['color'])) {
      set_theme_mod('car_dealer_show_color_' . $color['slug'], $color['color']);
    }
  }

  // Marca como escolhido
  set_theme_mod('car_dealer_show_user_has_chosen_style', true);
}
add_action('after_setup_theme', 'car_dealer_show_apply_palette_as_user_choice');



/**
 * Adiciona uma flag quando os estilos globais são salvos via Editor de Site.
 */
add_action('rest_insert_wp_global_styles', 'car_dealer_show_registrar_estilo_salvo', 10, 3);
function car_dealer_show_registrar_estilo_salvo($post, $request, $creating)
{
  if ($post->post_type === 'wp_global_styles' && strpos($post->post_name, 'wp-global-styles-') === 0) {
    set_theme_mod('car_dealer_show_user_has_chosen_style', true);
  }
}
//=================================


/**
 * Enfileira o CSS e JavaScript do padrão Car Dealer Showcase.
 */
function seu_tema_enqueue_car_dealer_assets()
{
  // Verifica se o padrão está em uso na página atual
  global $post;
  // if ( has_block( 'car-dealer-show/slider', $post ) ) {
  // Enfileira o CSS
  wp_enqueue_style(
    'car-dealer-showcase-style',
    get_theme_file_uri('/assets/css/slider.css'),
    array(),
    '1.0'
  );

  // Enfileira o JavaScript
  wp_enqueue_script(
    'car-dealer-showcase-script',
    get_theme_file_uri('/assets/js/slider.js'),
    array(),
    '1.0',
    true // Coloca o script no rodapé
  );
  //}
}
add_action('wp_enqueue_scripts', 'seu_tema_enqueue_car_dealer_assets');

// Define logo padrão do tema (aparece só se o usuário ainda não definiu o dele)
add_action('after_setup_theme', 'car_dealer_show_set_default_logo');
function car_dealer_show_set_default_logo()
{

  // Só roda uma vez: se já tiver custom_logo definido, não faz nada
  if (get_theme_mod('custom_logo')) {
    return;
  }

  $logo_path = get_template_directory() . '/assets/images/logo.png'; // ← ajuste se for .svg ou outro nome

  if (!file_exists($logo_path)) {
    return; // se o arquivo não existir, nem tenta
  }

  // Cria o attachment corretamente no wp-content/uploads
  $upload_dir = wp_upload_dir();
  $filename   = basename($logo_path);
  $upload_file = $upload_dir['path'] . '/' . $filename;

  // Copia o arquivo do tema para a pasta uploads (assim o guid fica correto)
  if (!file_exists($upload_file)) {
    copy($logo_path, $upload_file);
  }

  // Verifica se já existe esse arquivo como attachment
  $attachment = get_page_by_title($filename, OBJECT, 'attachment');

  if (!$attachment) {
    require_once(ABSPATH . 'wp-admin/includes/image.php');
    require_once(ABSPATH . 'wp-admin/includes/file.php');
    require_once(ABSPATH . 'wp-admin/includes/media.php');

    $attachment_id = wp_insert_attachment([
      'guid'           => $upload_dir['url'] . '/' . $filename,
      'post_mime_type' => wp_check_filetype($filename)['type'],
      'post_title'     => 'Logo Padrão do Tema',
      'post_content'   => '',
      'post_status'    => 'inherit'
    ], $upload_file);

    if (!is_wp_error($attachment_id)) {
      wp_update_attachment_metadata($attachment_id, wp_generate_attachment_metadata($attachment_id, $upload_file));
    }
  } else {
    $attachment_id = $attachment->ID;
  }

  // Define como logo oficial do tema
  if ($attachment_id) {
    set_theme_mod('custom_logo', $attachment_id);
  }
}
