<?php
/**
 * Enqueue child styles.
 */
function child_enqueue_styles() {
    $style_path = get_stylesheet_directory() . '/style.css';
    $version    = file_exists( $style_path ) ? filemtime( $style_path ) : '1.0.1';
    wp_enqueue_style( 'child-theme', get_stylesheet_directory_uri() . '/style.css', array(), $version );
}

add_action( 'wp_enqueue_scripts', 'child_enqueue_styles', 20 );

/* Enable auto-updates of plugins/themes on Flywheel */
add_action(
    'wp_update_plugins',
    function() {
        if (wp_doing_cron() && ! doing_action('wp_maybe_auto_update')) {
            do_action('wp_maybe_auto_update');
        }
    },
    20
);


/**
 * Force exact phrase matching for Kadence Query Loop search.
 */
add_filter('posts_search', function ($search, $wp_query) {
    if (empty($search) || !$wp_query->get('s')) {
        return $search;
    }
    if (is_admin()) {
        return $search;
    }
    $search_term = $wp_query->get('s');
    $words = preg_split('/\s+/', trim($search_term));
    if (count($words) < 2) {
        return $search;
    }
    global $wpdb;
    $like = '%' . $wpdb->esc_like($search_term) . '%';
    $search = $wpdb->prepare(
        " AND (({$wpdb->posts}.post_title LIKE %s) OR ({$wpdb->posts}.post_excerpt LIKE %s) OR ({$wpdb->posts}.post_content LIKE %s))",
        $like, $like, $like
    );
    return $search;
}, 10, 2);

  /**
   * When searching, order by title match first, then date (newest first).
   */
  add_filter('posts_orderby', function ($orderby, $wp_query) {
      if (empty($wp_query->get('s')) || is_admin()) {
          return $orderby;
      }

      global $wpdb;
      $like = '%' . $wpdb->esc_like($wp_query->get('s')) . '%';

      $orderby = $wpdb->prepare(
          "({$wpdb->posts}.post_title LIKE %s) DESC, {$wpdb->posts}.post_date DESC",
          $like
      );

      return $orderby;
  }, 10, 2);


/**
 * =============================================================================
 * Grant Editor role access to Kadence Elements and Appearance Menu
 * Copy this entire section to other sites
 * =============================================================================
 */

/**
 * Add capabilities to Editor role for Kadence Elements and Appearance menu
 */
add_action('init', 'swc_editor_kadence_capabilities');
function swc_editor_kadence_capabilities() {
    $editor = get_role('editor');
    if (!$editor) {
        return;
    }

    // Kadence Elements capabilities (custom post type: kadence_element)
    $editor->add_cap('edit_kadence_elements');
    $editor->add_cap('edit_others_kadence_elements');
    $editor->add_cap('publish_kadence_elements');
    $editor->add_cap('read_private_kadence_elements');
    $editor->add_cap('delete_kadence_elements');
    $editor->add_cap('delete_others_kadence_elements');
    $editor->add_cap('delete_published_kadence_elements');
    $editor->add_cap('edit_published_kadence_elements');

    // Appearance menu capabilities (for Menus, Widgets, Customizer)
    $editor->add_cap('edit_theme_options');
}

/**
 * Allow Editors to access Kadence Elements admin menu
 */
add_filter('kadence_element_post_type_args', 'swc_kadence_elements_editor_access');
function swc_kadence_elements_editor_access($args) {
    $args['capability_type'] = 'kadence_element';
    $args['map_meta_cap'] = true;
    $args['capabilities'] = array(
        'edit_post'              => 'edit_kadence_element',
        'read_post'              => 'read_kadence_element',
        'delete_post'            => 'delete_kadence_element',
        'edit_posts'             => 'edit_kadence_elements',
        'edit_others_posts'      => 'edit_others_kadence_elements',
        'publish_posts'          => 'publish_kadence_elements',
        'read_private_posts'     => 'read_private_kadence_elements',
        'delete_posts'           => 'delete_kadence_elements',
        'delete_others_posts'    => 'delete_others_kadence_elements',
        'delete_published_posts' => 'delete_published_kadence_elements',
        'edit_published_posts'   => 'edit_published_kadence_elements',
    );
    return $args;
}

  /**
   * SWC — auto-fill "Lead Source (Salesforce)" on every Gravity Form.
   *
   * If the form was submitted from a URL containing "/l/", set the value to
   * "SWC Landing Page"; otherwise "Website". Finds the field by label, so the
   * snippet keeps working across form edits and multiple forms.
   */
  add_action( 'gform_pre_submission', function ( $form ) {
      $referer = isset( $_SERVER['HTTP_REFERER'] ) ? wp_unslash( $_SERVER['HTTP_REFERER'] ) : '';
      $value   = ( false !== strpos( $referer, '/l/' ) ) ? 'SWC Landing Page' : 'Website';

      foreach ( $form['fields'] as $field ) {
          if ( strcasecmp( trim( (string) $field->label ), 'Lead Source (Salesforce)' ) === 0 ) {
              $_POST[ 'input_' . $field->id ] = $value;
              break;
          }
      }
  } );

/**
 * =============================================================================
 * Kadence Testimonials Enhancements (Hook-based in Child Theme)
 * =============================================================================
 */

// 1. Enqueue block editor custom controls
add_action( 'enqueue_block_editor_assets', function() {
    $editor_js = get_stylesheet_directory() . '/assets/js/testimonial-editor.js';
    if ( file_exists( $editor_js ) ) {
        wp_enqueue_script(
            'kadence-child-testimonial-editor',
            get_stylesheet_directory_uri() . '/assets/js/testimonial-editor.js',
            array( 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-i18n', 'wp-hooks', 'wp-compose' ),
            filemtime( $editor_js ),
            true
        );
    }
} );

// 2. Enqueue styles for front-end & block editor
add_action( 'enqueue_block_editor_assets', function() {
    $style_css = get_stylesheet_directory() . '/style.css';
    if ( file_exists( $style_css ) ) {
        wp_enqueue_style( 'kadence-child-block-editor-style', get_stylesheet_directory_uri() . '/style.css', array(), filemtime( $style_css ) );
    }
} );

add_action( 'after_setup_theme', function() {
    add_theme_support( 'editor-styles' );
    add_editor_style( 'style.css' );
} );

// 3. Helper to extract name initials (2 letters for 2 words, e.g. Seth Klein -> SK)
function kadence_child_get_name_initials( $name ) {
    $name = trim( strip_tags( (string) $name ) );
    if ( empty( $name ) ) {
        return '';
    }
    $words = preg_split( '/[\s\-_]+/', $name );
    if ( count( $words ) >= 2 ) {
        $first = function_exists( 'mb_substr' ) ? mb_substr( $words[0], 0, 1, 'UTF-8' ) : substr( $words[0], 0, 1 );
        $last  = function_exists( 'mb_substr' ) ? mb_substr( end( $words ), 0, 1, 'UTF-8' ) : substr( end( $words ), 0, 1 );
        $res   = $first . $last;
        return function_exists( 'mb_strtoupper' ) ? mb_strtoupper( $res, 'UTF-8' ) : strtoupper( $res );
    } elseif ( count( $words ) === 1 && ! empty( $words[0] ) ) {
        $len = function_exists( 'mb_strlen' ) ? mb_strlen( $words[0], 'UTF-8' ) : strlen( $words[0] );
        if ( $len <= 2 ) {
            return function_exists( 'mb_strtoupper' ) ? mb_strtoupper( $words[0], 'UTF-8' ) : strtoupper( $words[0] );
        }
        $first = function_exists( 'mb_substr' ) ? mb_substr( $words[0], 0, 1, 'UTF-8' ) : substr( $words[0], 0, 1 );
        return function_exists( 'mb_strtoupper' ) ? mb_strtoupper( $first, 'UTF-8' ) : strtoupper( $first );
    }
    return '';
}

// 4. Safe non-destructive render_block filter for Dynamic Initials and YouTube Embed
add_filter( 'render_block', 'kadence_child_render_testimonial_block', 10, 3 );
function kadence_child_render_testimonial_block( $block_content, $block, $instance = null ) {
    if ( ! isset( $block['blockName'] ) || $block['blockName'] !== 'kadence/testimonial' ) {
        return $block_content;
    }

    $context = ( $instance && isset( $instance->context ) ) ? $instance->context : [];
    
    // Respect parent block displayMedia setting
    $display_media = isset( $context['kadence/testimonials-displayMedia'] ) ? (bool)$context['kadence/testimonials-displayMedia'] : true;
    if ( ! $display_media ) {
        return $block_content;
    }

    $attrs = isset( $block['attrs'] ) ? $block['attrs'] : [];
    $media = isset( $attrs['media'] ) ? $attrs['media'] : 'image';
    $url   = isset( $attrs['url'] ) ? trim( $attrs['url'] ) : '';
    $name  = isset( $attrs['name'] ) ? $attrs['name'] : '';
    $style = isset( $context['kadence/testimonials-style'] ) ? $context['kadence/testimonials-style'] : 'card';

    // If icon mode, let Kadence render icon
    if ( 'icon' === $media ) {
        return $block_content;
    }

    // Check if YouTube (media is 'youtube' or URL is a youtube link)
    $is_youtube = ( 'youtube' === $media ) || ( ! empty( $url ) && preg_match( '/(?:youtu\.be\/|youtube(?:-nocookie)?\.com)/i', $url ) );

    if ( $is_youtube && ! empty( $url ) ) {
        $video_id = '';
        if ( preg_match( '/(?:i\.ytimg\.com\/vi\/|youtu\.be\/|youtube(?:-nocookie)?\.com\/(?:watch\?v=|embed\/|shorts\/|v\/|user\/[^\/]+\/u\/[0-9]+\/))([a-zA-Z0-9_-]{11})/i', $url, $matches ) ) {
            $video_id = $matches[1];
        } elseif ( preg_match( '/^[a-zA-Z0-9_-]{11}$/', $url ) ) {
            $video_id = $url;
        }

        if ( ! empty( $video_id ) ) {
            $embed_url = 'https://www.youtube.com/embed/' . rawurlencode( $video_id );
            $iframe = '<iframe src="' . esc_url( $embed_url ) . '" class="kt-testimonial-youtube-iframe" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen loading="lazy"></iframe>';
            
            if ( strpos( $block_content, 'kadence-testimonial-image-intrisic' ) !== false ) {
                return preg_replace(
                    '/(<div class="kadence-testimonial-image-intrisic"[^>]*>).*?(<\/div>)/is',
                    '$1' . $iframe . '$2',
                    $block_content,
                    1
                );
            } elseif ( in_array( $style, [ 'card', 'inlineimage' ] ) && strpos( $block_content, 'kt-testimonial-text-wrap' ) !== false ) {
                $media_wrap = '<div class="kt-testimonial-media-wrap kt-testimonial-media-youtube"><div class="kt-testimonial-media-inner-wrap"><div class="kadence-testimonial-image-intrisic">' . $iframe . '</div></div></div>';
                return preg_replace( '/(<div class="kt-testimonial-text-wrap"[^>]*>)/', '$1' . $media_wrap, $block_content, 1 );
            }
        }
        return $block_content;
    }

    // Text-only testimonials (no image, no video) render as plain text — Kadence
    // outputs no media box when the item has no URL. We deliberately do NOT inject
    // a placeholder avatar here: the client has no people photos, so a placeholder
    // reads as broken. Only real videos (above) and real images get a media area.
    return $block_content;
}