<?php
/**
 * Kadence-Child functions and definitions
 *
 * @package Kadence-Child
 */

// Enqueue parent theme styles
function kadence_child_enqueue_styles() {
    wp_enqueue_style(
        'kadence-parent-style',
        get_template_directory_uri() . '/style.css'
    );
}
add_action( 'wp_enqueue_scripts', 'kadence_child_enqueue_styles' );

// Add your custom functions below this line

/* 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
);

/**
 * Helper: return the first non-empty ACF/meta field among $names.
 * Matches the bw-agenda-table convention so shortcodes work whether
 * the session uses `speakers`, `speaker`, `pembicara`, etc.
 */
if ( ! function_exists( 'pv_get_first_field' ) ) {
    function pv_get_first_field( $names, $post_id = null ) {
        $post_id = $post_id ?: get_the_ID();
        foreach ( (array) $names as $name ) {
            $val = function_exists( 'get_field' )
                ? get_field( $name, $post_id )
                : get_post_meta( $post_id, $name, true );
            if ( ! empty( $val ) ) {
                return $val;
            }
        }
        return null;
    }
}

/**
 * Shortcode: display speaker names from the ACF Relationship field on a
 * single session. Tries common field-name variants (speakers / speaker
 * / pembicara / presenter / presenters).
 *
 * Usage:
 *   [session_speaker_names]
 *   [session_speaker_names link="no"]
 *   [session_speaker_names separator=" · "]
 */
add_shortcode( 'session_speaker_names', function( $atts ) {
    $atts = shortcode_atts( array(
        'separator' => ', ',
        'link'      => 'yes',
    ), $atts );

    if ( ! function_exists( 'get_field' ) ) {
        return '';
    }

    $speakers = pv_get_first_field( array( 'speakers', 'speaker', 'pembicara', 'presenter', 'presenters' ) );
    if ( empty( $speakers ) ) {
        return '';
    }

    $names = array();
    foreach ( $speakers as $speaker ) {
        $id = is_object( $speaker ) ? $speaker->ID : (int) $speaker;
        $name = get_the_title( $id );
        if ( ! $name ) {
            continue;
        }

        if ( $atts['link'] === 'yes' ) {
            $names[] = '<a href="' . esc_url( get_permalink( $id ) ) . '">' . esc_html( $name ) . '</a>';
        } else {
            $names[] = esc_html( $name );
        }
    }

    return '<span style="padding-left:10px;">' . implode( $atts['separator'], $names ) . '</span>';
} );

/**
 * Shortcode: display a list of speaker cards from the ACF Relationship field "speaker".
 * Markup follows the .pv-speaker-card structure in single_agenda.html.
 *
 * Usage:
 *   [session_speaker_cards]
 *
 * Fields used from the speaker post type:
 *   - Featured image  -> avatar
 *   - Post title      -> name
 *   - role_company    -> role/company line
 *   - Post excerpt    -> bio
 *   - website         -> ACF link (globe icon)
 *   - linkedin        -> ACF link (linkedin icon)
 *   - xtwitter        -> ACF link (X icon)
 */
add_shortcode( 'session_speaker_cards', function() {
    if ( ! function_exists( 'get_field' ) ) {
        return '';
    }

    $speakers = pv_get_first_field( array( 'speakers', 'speaker', 'pembicara', 'presenter', 'presenters' ) );
    if ( empty( $speakers ) ) {
        return '';
    }

    $icon_website  = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>';
    $icon_linkedin = '<svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor" aria-hidden="true"><path d="M20.45 20.45h-3.55v-5.57c0-1.33-.03-3.04-1.85-3.04-1.85 0-2.13 1.45-2.13 2.94v5.67H9.36V9h3.41v1.56h.05a3.74 3.74 0 0 1 3.37-1.85c3.6 0 4.27 2.37 4.27 5.46v6.28zM5.34 7.43a2.06 2.06 0 1 1 0-4.13 2.06 2.06 0 0 1 0 4.13zM7.12 20.45H3.56V9h3.56v11.45z"/></svg>';
    $icon_xtwitter = '<svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor" aria-hidden="true"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231Zm-1.161 17.52h1.833L7.084 4.126H5.117Z"/></svg>';

    ob_start();

    foreach ( $speakers as $speaker ) {
        $id        = is_object( $speaker ) ? $speaker->ID : (int) $speaker;
        $name      = get_the_title( $id );
        $permalink = get_permalink( $id );
        $role      = get_field( 'role', $id );
        $bio       = get_the_excerpt( $id );
        $avatar    = get_the_post_thumbnail( $id, 'medium', array( 'alt' => $name ) );

        $links = array(
            'website'  => array( 'url' => get_field( 'website', $id ),  'icon' => $icon_website,  'label' => 'website' ),
            'linkedin' => array( 'url' => get_field( 'linkedin', $id ), 'icon' => $icon_linkedin, 'label' => 'LinkedIn' ),
            'xtwitter' => array( 'url' => get_field( 'xtwitter', $id ), 'icon' => $icon_xtwitter, 'label' => 'X' ),
        );
        ?>
        <article class="pv-speaker-card">
            <div class="pv-speaker-card__avatar">
                <?php echo $avatar; ?>
            </div>
            <div>
                <h3 class="pv-speaker-card__name">
                    <a href="<?php echo esc_url( $permalink ); ?>"><?php echo esc_html( $name ); ?></a>
                </h3>

                <?php if ( $role ) : ?>
                    <p class="pv-speaker-card__role"><?php echo esc_html( $role ); ?></p>
                <?php endif; ?>

                <?php if ( $bio ) : ?>
                    <p class="pv-speaker-card__bio"><?php echo esc_html( $bio ); ?></p>
                <?php endif; ?>

                <?php
                $active_links = array_filter( $links, function( $l ) {
                    return ! empty( $l['url'] );
                } );

                if ( $active_links ) : ?>
                    <div class="pv-speaker-card__links">
                        <?php foreach ( $active_links as $link ) :
                            if ( is_array( $link['url'] ) ) {
                                $href   = isset( $link['url']['url'] )    ? $link['url']['url']    : '';
                                $target = isset( $link['url']['target'] ) ? $link['url']['target'] : '_blank';
                            } else {
                                $href   = $link['url'];
                                $target = '_blank';
                            }
                            if ( ! $href ) {
                                continue;
                            }
                            ?>
                            <a class="pv-speaker-card__link"
                               href="<?php echo esc_url( $href ); ?>"
                               target="<?php echo esc_attr( $target ); ?>"
                               rel="noopener noreferrer"
                               aria-label="<?php echo esc_attr( $name . ' - ' . $link['label'] ); ?>">
                                <?php echo $link['icon']; ?>
                            </a>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </article>
        <?php
    }

    return ob_get_clean();
} );

/**
 * Shortcode: list of sessions a given speaker appears in.
 * Reverse query against the ACF Relationship field "speakers"
 * (or speaker / pembicara / presenter) on the session post type.
 *
 * Track is read from the "track" taxonomy (matches bw-agenda-table).
 * Date / time fields try multiple common name variants.
 *
 * Usage on a single speaker template:
 *   [speaker_sessions]
 *   [speaker_sessions speaker_id="467"]
 */
add_shortcode( 'speaker_sessions', function( $atts ) {
    $atts = shortcode_atts( array(
        'speaker_id' => get_the_ID(),
    ), $atts );

    $speaker_id = (int) $atts['speaker_id'];
    if ( ! $speaker_id ) {
        return '';
    }

    // Helper: read the first ACF/meta field that has a value.
    $get_first_field = function( $names, $post_id, $raw = false ) {
        foreach ( (array) $names as $name ) {
            if ( function_exists( 'get_field' ) ) {
                $val = $raw ? get_field( $name, $post_id, false ) : get_field( $name, $post_id );
            } else {
                $val = get_post_meta( $post_id, $name, true );
            }
            if ( ! empty( $val ) ) {
                return $val;
            }
        }
        return null;
    };

    // ACF Relationship stores values as a serialized array of string IDs.
    // Quoting the ID prevents false matches (e.g. 6 vs 60, 61).
    // We OR across the common field-name variants used by this site.
    $needle    = '"' . $speaker_id . '"';
    $key_names = array( 'speakers', 'speaker', 'pembicara', 'presenter', 'presenters' );

    $meta_query = array( 'relation' => 'OR' );
    foreach ( $key_names as $k ) {
        $meta_query[] = array( 'key' => $k, 'value' => $needle, 'compare' => 'LIKE' );
    }

    // No meta_key in orderby — that would silently drop sessions that
    // don't have the key. Sort in PHP after the query.
    $sessions = get_posts( array(
        'post_type'      => 'session',
        'posts_per_page' => -1,
        'orderby'        => 'date',
        'order'          => 'ASC',
        'meta_query'     => $meta_query,
    ) );

    if ( empty( $sessions ) ) {
        return '';
    }

    // Sort by event_date (raw "Ymd") if any session has it.
    usort( $sessions, function( $a, $b ) use ( $get_first_field ) {
        $da = (string) $get_first_field( array( 'event_date', 'date', 'session_date' ), $a->ID, true );
        $db = (string) $get_first_field( array( 'event_date', 'date', 'session_date' ), $b->ID, true );
        return strcmp( $da, $db );
    } );

    $icon_clock    = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9"/><polyline points="12 7 12 12 15 14"/></svg>';
    $icon_pin      = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 10c0 7-9 13-9 13S3 17 3 10a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3"/></svg>';
    $icon_calendar = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>';
    $icon_arrow    = '<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>';

    // Heading text adapts to the number of sessions found.
    $session_eyebrow = ( count( $sessions ) > 1 ) ? 'The Sessions' : 'The Session';

    ob_start(); ?>
    <div style="text-align:left" class="bw-pre-heading bw-pre-heading--align-left wp-block-bw-pre-heading">
        <div class="pv-hero__eyebrow">
            <svg class="pv-hero__eyebrow-prompt" aria-hidden="true" viewBox="0 0 28 16" xmlns="http://www.w3.org/2000/svg" style="color: #f58220;">
                <path d="M4 4 L 11 8 L 4 12" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"></path>
                <line class="pv-hero__eyebrow-prompt-cursor" x1="15" y1="12" x2="23" y2="12" stroke="currentColor" stroke-width="2" stroke-linecap="round"></line>
            </svg>
            <span class="pv-hero__eyebrow-text" style="color: #f58220;"><?php echo esc_html( $session_eyebrow ); ?></span>
        </div>
    </div>
    <h2 class="pv-speaker-sessions__heading">On the Stage</h2>
    <div class="pv-speaker-sessions">
        <ul class="pv-speaker-sessions__list">
            <?php foreach ( $sessions as $s ) :
                // Date — raw "Ymd" then format for display
                $raw_date = $get_first_field( array( 'event_date', 'date', 'session_date' ), $s->ID, true );
                $date_out = '';
                if ( $raw_date ) {
                    $ts = strtotime( $raw_date );
                    $date_out = $ts ? date_i18n( 'F j, Y', $ts ) : (string) $raw_date;
                }

                // Time — combine start_time + end_time if available
                $start = $get_first_field( array( 'start_time', 'start', 'time_start' ), $s->ID, true );
                $end   = $get_first_field( array( 'end_time',   'end',   'time_end'   ), $s->ID, true );
                $fmt_t = function( $t ) {
                    if ( ! $t ) return '';
                    $ts = strtotime( $t );
                    return $ts ? date_i18n( 'g:i a', $ts ) : (string) $t;
                };
                $time_out = trim( $fmt_t( $start ) . ( $end ? ' – ' . $fmt_t( $end ) : '' ) );

                // Room
                $room = $get_first_field( array( 'room', 'venue', 'location' ), $s->ID );

                // Track — taxonomy, not field
                $track_out = '';
                $terms = wp_get_post_terms( $s->ID, 'track' );
                if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {
                    $track_out = $terms[0]->name;
                }
            ?>
                <li>
                    <article class="pv-session-row">
                        <div>
                            <span class="pv-session-row__track-label">Track</span>
                            <span class="pv-session-row__track"><?php echo esc_html( $track_out ?: '—' ); ?></span>
                        </div>

                        <div>
                            <h3 class="pv-session-row__title"><?php echo esc_html( get_the_title( $s ) ); ?></h3>
                            <div class="pv-session-row__meta">
                                <span class="pv-session-row__meta-item">
                                    <?php echo $icon_clock; ?>
                                    <?php echo esc_html( $time_out ?: '[Time TBA]' ); ?>
                                </span>
                                <span class="pv-session-row__meta-item">
                                    <?php echo $icon_pin; ?>
                                    <?php echo esc_html( is_string( $room ) ? $room : '[Room TBA]' ); ?>
                                </span>
                                <?php if ( $date_out ) : ?>
                                    <span class="pv-session-row__meta-item">
                                        <?php echo $icon_calendar; ?>
                                        <?php echo esc_html( $date_out ); ?>
                                    </span>
                                <?php endif; ?>
                            </div>
                        </div>

                        <a class="pv-session-row__cta" href="<?php echo esc_url( get_permalink( $s ) ); ?>">
                            View Session
                            <?php echo $icon_arrow; ?>
                        </a>
                    </article>
                </li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php
    return ob_get_clean();
} );