<?php
/**
 * Timber cache invalidation.
 * Clears the cache on content changes and adds an admin-bar flush button.
 *
 * @package Genesis
 */

// Clear Timber cache whenever content changes (useful for dynamic blocks).
foreach ( [ 'save_post', 'deleted_post', 'trashed_post' ] as $hook ) {
    add_action( $hook, static function () {
        ( new Timber\Loader() )->clear_cache_timber();
    } );
}

// Admin-bar button to flush the cache manually.
add_action( 'admin_bar_menu', static function ( $wp_admin_bar ) {
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }
    $wp_admin_bar->add_node( [
        'id'    => 'clear_timber_cache',
        'title' => '🗑️ Vider le cache Timber',
        'href'  => add_query_arg( 'clear_timber_cache', '1' ),
    ] );
}, 100 );

add_action( 'init', static function () {
    if ( ! isset( $_GET['clear_timber_cache'] ) || ! current_user_can( 'manage_options' ) ) {
        return;
    }
    $loader = new Timber\Loader();
    $loader->clear_cache_twig();
    $loader->clear_cache_timber();
    wp_redirect( remove_query_arg( 'clear_timber_cache' ) );
    exit;
} );
