<?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'
    );

    // Global print stylesheet. media="print" => only fetched/applied when
    // printing, so zero cost on screen. Single source of truth for print
    // layout (fixes the mobile-layout-in-print bug). See assets/print.css.
    $child_dir = get_stylesheet_directory();
    $child_uri = get_stylesheet_directory_uri();

    // The child theme's own style.css (holds the red accent line, etc.).
    // WordPress does NOT auto-enqueue a child theme's stylesheet — the theme
    // must do it — so without this, edits to style.css never take effect.
    // Loaded after the parent, cache-busted by filemtime.
    wp_enqueue_style(
        'kadence-child-style',
        get_stylesheet_uri(),
        array( 'kadence-parent-style' ),
        filemtime( $child_dir . '/style.css' )
    );

    wp_enqueue_style(
        'bw-print',
        $child_uri . '/assets/print.css',
        array(),
        filemtime( $child_dir . '/assets/print.css' ),
        'print'
    );
}
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
);

require_once get_stylesheet_directory() . "/inc/brentwood-blocks.php";
require_once get_stylesheet_directory() . "/inc/brentwood-subnav.php";
require_once get_stylesheet_directory() . "/inc/brentwood-hero.php";
require_once get_stylesheet_directory() . "/inc/brentwood-livestream.php";
require_once get_stylesheet_directory() . "/inc/brentwood-staff.php";
require_once get_stylesheet_directory() . "/inc/brentwood-course.php";
require_once get_stylesheet_directory() . "/inc/brentwood-editor-layout.php";
require_once get_stylesheet_directory() . "/inc/brentwood-curve.php";
require_once get_stylesheet_directory() . "/inc/brentwood-search.php";
require_once get_stylesheet_directory() . "/inc/brentwood-calendar.php";
require_once get_stylesheet_directory() . "/inc/brentwood-timetable.php";
require_once get_stylesheet_directory() . "/inc/bw-my-profile.php";
require_once get_stylesheet_directory() . "/inc/bw-google-login.php";
require_once get_stylesheet_directory() . "/inc/bw-cover-style.php";  // "Cover (fill column)" image block style
require_once get_stylesheet_directory() . "/inc/bw-row-defaults.php"; // default new rows to equal-height columns
require_once get_stylesheet_directory() . "/inc/bw-lightbox.php";    // opt-in "Lightbox" toggle on image blocks
require_once get_stylesheet_directory() . "/inc/bw-image-hd.php";    // "Always HD": Image (Adv) blocks load full-size (no blurry 300w srcset pick)
require_once get_stylesheet_directory() . "/inc/bw-redborder.php";   // "Red Border" on/off toggle on Kadence sections (columns)
require_once get_stylesheet_directory() . "/inc/bw-hundred.php";     // Brentwood 100 CPT query + modal-body + cache bust
require_once get_stylesheet_directory() . "/inc/bw-row-style.php";   // "Brentwood Shadow" + "Border Radius" on/off toggles on Kadence rows
require_once get_stylesheet_directory() . "/inc/bw-newspaper.php";   // "Newspaper Columns" toggle on Kadence rows: flow one column of text into 2–3 columns
require_once get_stylesheet_directory() . "/inc/bw-blog-archive.php"; // "Auto Hide Old Blog Posts": hide posts older than N yrs from on-site listings (still published + search-reachable)
require_once get_stylesheet_directory() . "/inc/bw-img-alt.php";      // Image alt migration: inject attachment alt into empty-alt <img> at render (interlinking cards, blog thumbnails, images)
require_once get_stylesheet_directory() . "/inc/bw-inside-row.php";  // auto-add .bw-inside-row class to nested Row Layouts (no admin option)
require_once get_stylesheet_directory() . "/inc/bw-staff-anchor.php"; // open staff profile modal anywhere via #staff-<slug> anchor / [bw_staff_modal] shortcode
require_once get_stylesheet_directory() . "/inc/bw-sectionnum.php";  // "Number Badge" on/off toggle on Kadence sections (columns)
require_once get_stylesheet_directory() . "/inc/bw-gf-review.php";   // Gravity Forms live "Review Information" step (no add-on)
require_once get_stylesheet_directory() . "/inc/bw-gf-editor.php";   // Mirror form CSS into the block editor preview
require_once get_stylesheet_directory() . "/inc/bw-inquiry-thankyou.php"; // Contact form -> Thank-You page personalization (shortcodes)
require_once get_stylesheet_directory() . "/inc/bw-footer.php";     // Footer: collapse the empty gap when a page has no footer image + blue readability overlay when it does
require_once get_stylesheet_directory() . "/inc/bw-title-override-acf.php"; // H1 title override as an ACF field in the "Page Settings" box, bridged to the bw-dev _bw_dev_title_override meta
require_once get_stylesheet_directory() . "/inc/bw-editor-customizer-css.php"; // strip site-chrome rules from the Customizer CSS that core injects into the block editor (was breaking the editor's post title)
require_once get_stylesheet_directory() . "/inc/bw-roles.php";      // custom editorial roles (Site Editor (Draft) — create/revise drafts, cannot publish)
require_once get_stylesheet_directory() . "/inc/bw-staff-access.php"; // teachers (bw_staff): land on /my-profile, no wp-admin, no admin bar
require_once get_stylesheet_directory() . "/inc/bw-user-management.php"; // delegated user management for Marketing (Erin) — create/role users, guardrailed against touching admins


/**
 * Output the red vertical accent line down the body content on single
 * posts, pages, and custom post types.
 *
 * DISABLED 2026-07-20 at the client's request (they decided to remove the
 * red line). The injection is commented out rather than deleted, and the
 * `.border-primary-line` CSS is left intact in style.css, so re-enabling is
 * a one-line uncomment if they change their mind. See style.css line ~33.
 */
function brentwood_border_primary_line() {
    if ( is_singular() ) {
        echo '<div class="border-primary-line" aria-hidden="true"></div>';
    }
}
// add_action( 'kadence_single_after_inner_content', 'brentwood_border_primary_line' );


/**
 * [bw_current_time] — outputs the current date/time in Brentwood's local
 * timezone, e.g. "June 10, 6:05am PDT @Brentwood".
 *
 * Uses America/Vancouver so the timezone abbreviation switches between
 * PDT (summer) and PST (winter) automatically with daylight saving — the
 * whole string is computed live each time the shortcode renders.
 */
function bw_current_time_shortcode() {
    $now = new DateTime( 'now', new DateTimeZone( 'America/Vancouver' ) );
    // F j   -> "June 10"
    // g:ia  -> "6:05am"
    // T     -> "PDT" / "PST" (dynamic)
    return esc_html( $now->format( 'F j, g:ia T' ) . ' @Brentwood' );
}
add_shortcode( 'bw_current_time', 'bw_current_time_shortcode' );


/**
 * [bw_print] — a "Print" button that opens the browser's print dialog,
 * mirroring the print control in brentwood.ca's footer (FontAwesome
 * `print` icon + "Print" label).
 *
 * Optional attribute:
 *   label  -> button text (default "Print")
 *
 * The button hides itself on the printed page (so it never appears in the
 * printout) and inherits the surrounding text colour, like the original.
 * Styling is self-contained — it does not rely on Tailwind utilities.
 */
function bw_print_shortcode( $atts ) {
    $atts = shortcode_atts( array( 'label' => 'Print' ), $atts, 'bw_print' );

    // FontAwesome "print" (fa-print) solid icon — same path as brentwood.ca.
    $svg = '<svg class="bw-print__svg" aria-hidden="true" focusable="false" '
         . 'role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">'
         . '<path fill="currentColor" d="M128 0C92.7 0 64 28.7 64 64v96h64V64H354.7'
         . 'L384 93.3V160h64V93.3c0-17-6.7-33.3-18.7-45.3L400 18.7C388 6.7 371.7 0 '
         . '354.7 0H128zM384 352v32 64H128V384 368 352H384zm64 32h32c17.7 0 32-14.3 '
         . '32-32V256c0-35.3-28.7-64-64-64H64c-35.3 0-64 28.7-64 64v96c0 17.7 14.3 '
         . '32 32 32H64v64c0 35.3 28.7 64 64 64H384c35.3 0 64-28.7 64-64V384zM432 '
         . '248a24 24 0 1 1 0 48 24 24 0 1 1 0-48z"></path></svg>';

    // Emit the shared stylesheet only once per page render.
    static $printed_style = false;
    $style = '';
    if ( ! $printed_style ) {
        $printed_style = true;
        $style = '<style id="bw-print-style">'
               . '.bw-print,.bw-print:hover,.bw-print:focus,.bw-print:active{'
               . 'display:inline-flex;align-items:center;gap:.4em;'
               . 'background:none !important;border:0;box-shadow:none !important;'
               . 'padding:0;margin:0;cursor:pointer;'
               . 'font:inherit;color:var(--global-palette1);line-height:1;}'
               . '.bw-print__svg{width:1em;height:1em;display:block;}'
               // Desktop-only: printing makes sense from a real screen, so the
               // button is hidden on tablet (<=1024px) and phone. >=1025px shows it.
               . '@media (max-width:1024px){.bw-print{display:none !important;}}'
               // Never let the button itself appear in the printout.
               . '@media print{.bw-print{display:none !important;}}'
               . '</style>';
    }

    return $style
         . '<button type="button" class="bw-print cp link" '
         . 'onclick="window.print();return false;">'
         . '<span class="bw-print__icon">' . $svg . '</span>'
         . '<span class="bw-print__label">' . esc_html( $atts['label'] ) . '</span>'
         . '</button>';
}
add_shortcode( 'bw_print', 'bw_print_shortcode' );


/**
 * Raise PHP upload limits via php_value directives in the webroot .htaccess
 * (this WordPress image runs Apache + mod_php). upload_max_filesize and
 * post_max_size are PHP_INI_PERDIR so they cannot be set at runtime, and the
 * container's php.ini is gateway-managed — .htaccess is the only writable
 * place. The .htaccess lives in the container layer and is lost when the
 * container is recreated, so this re-appends the block whenever it's missing.
 */
function bw_ensure_upload_limits() {
	$target = ABSPATH . '.htaccess';
	$marker = '# BEGIN BW upload limits';

	if ( ! is_readable( $target ) || ! is_writable( $target ) ) {
		return;
	}
	$current = (string) file_get_contents( $target );
	if ( false !== strpos( $current, $marker ) ) {
		return;
	}
	// Only safe under mod_php — a foreign php_value directive 500s otherwise.
	if ( ! glob( '/etc/apache2/mods-enabled/php*.load' ) ) {
		return;
	}
	$block = "\n" . $marker . " (re-added automatically by the kadence-child theme)\n"
		. "php_value upload_max_filesize 200M\n"
		. "php_value post_max_size 210M\n"
		. "php_value max_execution_time 300\n"
		. "php_value max_input_time 300\n"
		. "# END BW upload limits\n";
	file_put_contents( $target, $current . $block );
}
add_action( 'admin_init', 'bw_ensure_upload_limits' );


/**
 * Keep nav menu labels true to Appearance → Menus.
 *
 * Menu items with an empty navigation label fall back to the linked page's
 * title, and core passes that fallback through `the_title` using the PAGE's
 * ID. On the page itself that ID matches get_queried_object_id(), so the
 * bw-dev Title Override (the long H1 headline imported from the Laravel
 * site) leaks into the current page's menu item. Rebuild the label from the
 * raw titles instead, bypassing the override.
 */
function brentwood_nav_menu_label( $title, $menu_item ) {
	if ( '' !== (string) $menu_item->post_title ) {
		// Explicit label set in Appearance → Menus — already correct.
		return $title;
	}
	if ( 'post_type' === $menu_item->type && ! empty( $menu_item->object_id ) ) {
		$original = get_post( (int) $menu_item->object_id );
		if ( $original instanceof WP_Post ) {
			return wptexturize( $original->post_title );
		}
	}
	return $title;
}
add_filter( 'nav_menu_item_title', 'brentwood_nav_menu_label', 20, 2 );
