<?php
/**
 * Theme functions and definitions
 *
 * @package HelloElementor
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

define( 'HELLO_ELEMENTOR_VERSION', '3.4.6' );
define( 'EHP_THEME_SLUG', 'hello-elementor' );

define( 'HELLO_THEME_PATH', get_template_directory() );
define( 'HELLO_THEME_URL', get_template_directory_uri() );
define( 'HELLO_THEME_ASSETS_PATH', HELLO_THEME_PATH . '/assets/' );
define( 'HELLO_THEME_ASSETS_URL', HELLO_THEME_URL . '/assets/' );
define( 'HELLO_THEME_SCRIPTS_PATH', HELLO_THEME_ASSETS_PATH . 'js/' );
define( 'HELLO_THEME_SCRIPTS_URL', HELLO_THEME_ASSETS_URL . 'js/' );
define( 'HELLO_THEME_STYLE_PATH', HELLO_THEME_ASSETS_PATH . 'css/' );
define( 'HELLO_THEME_STYLE_URL', HELLO_THEME_ASSETS_URL . 'css/' );
define( 'HELLO_THEME_IMAGES_PATH', HELLO_THEME_ASSETS_PATH . 'images/' );
define( 'HELLO_THEME_IMAGES_URL', HELLO_THEME_ASSETS_URL . 'images/' );

if ( ! isset( $content_width ) ) {
	$content_width = 800; // Pixels.
}

if ( ! function_exists( 'hello_elementor_setup' ) ) {
	/**
	 * Set up theme support.
	 *
	 * @return void
	 */
	function hello_elementor_setup() {
		if ( is_admin() ) {
			hello_maybe_update_theme_version_in_db();
		}

		if ( apply_filters( 'hello_elementor_register_menus', true ) ) {
			register_nav_menus( [ 'menu-1' => esc_html__( 'Header', 'hello-elementor' ) ] );
			register_nav_menus( [ 'menu-2' => esc_html__( 'Footer', 'hello-elementor' ) ] );
		}

		if ( apply_filters( 'hello_elementor_post_type_support', true ) ) {
			add_post_type_support( 'page', 'excerpt' );
		}

		if ( apply_filters( 'hello_elementor_add_theme_support', true ) ) {
			add_theme_support( 'post-thumbnails' );
			add_theme_support( 'automatic-feed-links' );
			add_theme_support( 'title-tag' );
			add_theme_support(
				'html5',
				[
					'search-form',
					'comment-form',
					'comment-list',
					'gallery',
					'caption',
					'script',
					'style',
					'navigation-widgets',
				]
			);
			add_theme_support(
				'custom-logo',
				[
					'height'      => 100,
					'width'       => 350,
					'flex-height' => true,
					'flex-width'  => true,
				]
			);
			add_theme_support( 'align-wide' );
			add_theme_support( 'responsive-embeds' );

			/*
			 * Editor Styles
			 */
			add_theme_support( 'editor-styles' );
			add_editor_style( 'assets/css/editor-styles.css' );

			/*
			 * WooCommerce.
			 */
			if ( apply_filters( 'hello_elementor_add_woocommerce_support', true ) ) {
				// WooCommerce in general.
				add_theme_support( 'woocommerce' );
				// Enabling WooCommerce product gallery features (are off by default since WC 3.0.0).
				// zoom.
				add_theme_support( 'wc-product-gallery-zoom' );
				// lightbox.
				add_theme_support( 'wc-product-gallery-lightbox' );
				// swipe.
				add_theme_support( 'wc-product-gallery-slider' );
			}
		}
	}
}
add_action( 'after_setup_theme', 'hello_elementor_setup' );

function hello_maybe_update_theme_version_in_db() {
	$theme_version_option_name = 'hello_theme_version';
	// The theme version saved in the database.
	$hello_theme_db_version = get_option( $theme_version_option_name );

	// If the 'hello_theme_version' option does not exist in the DB, or the version needs to be updated, do the update.
	if ( ! $hello_theme_db_version || version_compare( $hello_theme_db_version, HELLO_ELEMENTOR_VERSION, '<' ) ) {
		update_option( $theme_version_option_name, HELLO_ELEMENTOR_VERSION );
	}
}

if ( ! function_exists( 'hello_elementor_display_header_footer' ) ) {
	/**
	 * Check whether to display header footer.
	 *
	 * @return bool
	 */
	function hello_elementor_display_header_footer() {
		$hello_elementor_header_footer = true;

		return apply_filters( 'hello_elementor_header_footer', $hello_elementor_header_footer );
	}
}

if ( ! function_exists( 'hello_elementor_scripts_styles' ) ) {
	/**
	 * Theme Scripts & Styles.
	 *
	 * @return void
	 */
	function hello_elementor_scripts_styles() {
		if ( apply_filters( 'hello_elementor_enqueue_style', true ) ) {
			wp_enqueue_style(
				'hello-elementor',
				HELLO_THEME_STYLE_URL . 'reset.css',
				[],
				HELLO_ELEMENTOR_VERSION
			);
		}

		if ( apply_filters( 'hello_elementor_enqueue_theme_style', true ) ) {
			wp_enqueue_style(
				'hello-elementor-theme-style',
				HELLO_THEME_STYLE_URL . 'theme.css',
				[],
				HELLO_ELEMENTOR_VERSION
			);
		}

		if ( hello_elementor_display_header_footer() ) {
			wp_enqueue_style(
				'hello-elementor-header-footer',
				HELLO_THEME_STYLE_URL . 'header-footer.css',
				[],
				HELLO_ELEMENTOR_VERSION
			);
		}
	}
}
add_action( 'wp_enqueue_scripts', 'hello_elementor_scripts_styles' );

if ( ! function_exists( 'hello_elementor_register_elementor_locations' ) ) {
	/**
	 * Register Elementor Locations.
	 *
	 * @param ElementorPro\Modules\ThemeBuilder\Classes\Locations_Manager $elementor_theme_manager theme manager.
	 *
	 * @return void
	 */
	function hello_elementor_register_elementor_locations( $elementor_theme_manager ) {
		if ( apply_filters( 'hello_elementor_register_elementor_locations', true ) ) {
			$elementor_theme_manager->register_all_core_location();
		}
	}
}
add_action( 'elementor/theme/register_locations', 'hello_elementor_register_elementor_locations' );

if ( ! function_exists( 'hello_elementor_content_width' ) ) {
	/**
	 * Set default content width.
	 *
	 * @return void
	 */
	function hello_elementor_content_width() {
		$GLOBALS['content_width'] = apply_filters( 'hello_elementor_content_width', 800 );
	}
}
add_action( 'after_setup_theme', 'hello_elementor_content_width', 0 );

if ( ! function_exists( 'hello_elementor_add_description_meta_tag' ) ) {
	/**
	 * Add description meta tag with excerpt text.
	 *
	 * @return void
	 */
	function hello_elementor_add_description_meta_tag() {
		if ( ! apply_filters( 'hello_elementor_description_meta_tag', true ) ) {
			return;
		}

		if ( ! is_singular() ) {
			return;
		}

		$post = get_queried_object();
		if ( empty( $post->post_excerpt ) ) {
			return;
		}

		echo '<meta name="description" content="' . esc_attr( wp_strip_all_tags( $post->post_excerpt ) ) . '">' . "\n";
	}
}
add_action( 'wp_head', 'hello_elementor_add_description_meta_tag' );

// Settings page
require get_template_directory() . '/includes/settings-functions.php';

// Header & footer styling option, inside Elementor
require get_template_directory() . '/includes/elementor-functions.php';

if ( ! function_exists( 'hello_elementor_customizer' ) ) {
	// Customizer controls
	function hello_elementor_customizer() {
		if ( ! is_customize_preview() ) {
			return;
		}

		if ( ! hello_elementor_display_header_footer() ) {
			return;
		}

		require get_template_directory() . '/includes/customizer-functions.php';
	}
}
add_action( 'init', 'hello_elementor_customizer' );

if ( ! function_exists( 'hello_elementor_check_hide_title' ) ) {
	/**
	 * Check whether to display the page title.
	 *
	 * @param bool $val default value.
	 *
	 * @return bool
	 */
	function hello_elementor_check_hide_title( $val ) {
		if ( defined( 'ELEMENTOR_VERSION' ) ) {
			$current_doc = Elementor\Plugin::instance()->documents->get( get_the_ID() );
			if ( $current_doc && 'yes' === $current_doc->get_settings( 'hide_title' ) ) {
				$val = false;
			}
		}
		return $val;
	}
}
add_filter( 'hello_elementor_page_title', 'hello_elementor_check_hide_title' );

/**
 * BC:
 * In v2.7.0 the theme removed the `hello_elementor_body_open()` from `header.php` replacing it with `wp_body_open()`.
 * The following code prevents fatal errors in child themes that still use this function.
 */
if ( ! function_exists( 'hello_elementor_body_open' ) ) {
	function hello_elementor_body_open() {
		wp_body_open();
	}
}

require HELLO_THEME_PATH . '/theme.php';

HelloTheme\Theme::instance();


// add slider cards post type 
/* ─────────────────────────────────────────────
   1.  CUSTOM POST TYPE
───────────────────────────────────────────── */
function iwd_register_slider_post_type() {
    $labels = [
        'name'               => __( 'Slider Cards', 'iwd-slider' ),
        'singular_name'      => __( 'Slider Card',  'iwd-slider' ),
        'add_new'            => __( 'Add New Card',  'iwd-slider' ),
        'add_new_item'       => __( 'Add New Slider Card', 'iwd-slider' ),
        'edit_item'          => __( 'Edit Slider Card',    'iwd-slider' ),
        'new_item'           => __( 'New Slider Card',     'iwd-slider' ),
        'view_item'          => __( 'View Slider Card',    'iwd-slider' ),
        'search_items'       => __( 'Search Slider Cards', 'iwd-slider' ),
        'not_found'          => __( 'No slider cards found', 'iwd-slider' ),
        'not_found_in_trash' => __( 'No slider cards in trash', 'iwd-slider' ),
        'menu_name'          => __( 'Slider Cards', 'iwd-slider' ),
    ];

    register_post_type( 'iwd_slider_card', [
        'labels'        => $labels,
        'public'        => false,
        'show_ui'       => true,
        'show_in_menu'  => true,
        'menu_icon'     => 'dashicons-slides',
        'supports'      => [ 'title', 'thumbnail' ],
        'rewrite'       => false,
    ] );
}
add_action( 'init', 'iwd_register_slider_post_type' );


/* ─────────────────────────────────────────────
   2.  DYNAMIC TIME-AGO HELPER  (Arabic output)
       Returns e.g. "منذ 3 ساعات", "منذ يومين", "منذ أسبوع"
       Pass a post ID or a UTC timestamp string.
───────────────────────────────────────────── */
function iwd_time_ago( $post_id ) {
    $post_time = get_post_time( 'U', true, $post_id ); // Unix UTC timestamp
    $now       = current_time( 'timestamp', true );    // current UTC Unix
    $diff      = max( 0, $now - $post_time );

    $minute = 60;
    $hour   = $minute * 60;
    $day    = $hour   * 24;
    $week   = $day    * 7;
    $month  = $day    * 30;
    $year   = $day    * 365;

    if ( $diff < $minute ) {
        return __( 'منذ لحظات', 'iwd-slider' );
    } elseif ( $diff < 2 * $minute ) {
        return __( 'منذ دقيقة', 'iwd-slider' );
    } elseif ( $diff < $hour ) {
        $mins = (int) floor( $diff / $minute );
        /* Arabic plural: 3-10 use جمع, 11+ use مفرد مع عدد */
        if ( $mins === 2 ) return __( 'منذ دقيقتين', 'iwd-slider' );
        if ( $mins <= 10 ) return sprintf( __( 'منذ %d دقائق', 'iwd-slider' ), $mins );
        return sprintf( __( 'منذ %d دقيقة', 'iwd-slider' ), $mins );
    } elseif ( $diff < 2 * $hour ) {
        return __( 'منذ ساعة', 'iwd-slider' );
    } elseif ( $diff < $day ) {
        $hours = (int) floor( $diff / $hour );
        if ( $hours === 2 ) return __( 'منذ ساعتين', 'iwd-slider' );
        if ( $hours <= 10 ) return sprintf( __( 'منذ %d ساعات', 'iwd-slider' ), $hours );
        return sprintf( __( 'منذ %d ساعة', 'iwd-slider' ), $hours );
    } elseif ( $diff < 2 * $day ) {
        return __( 'منذ يوم', 'iwd-slider' );
    } elseif ( $diff < $week ) {
        $days = (int) floor( $diff / $day );
        if ( $days === 2 ) return __( 'منذ يومين', 'iwd-slider' );
        return sprintf( __( 'منذ %d أيام', 'iwd-slider' ), $days );
    } elseif ( $diff < 2 * $week ) {
        return __( 'منذ أسبوع', 'iwd-slider' );
    } elseif ( $diff < $month ) {
        $weeks = (int) floor( $diff / $week );
        if ( $weeks === 2 ) return __( 'منذ أسبوعين', 'iwd-slider' );
        return sprintf( __( 'منذ %d أسابيع', 'iwd-slider' ), $weeks );
    } elseif ( $diff < 2 * $month ) {
        return __( 'منذ شهر', 'iwd-slider' );
    } elseif ( $diff < $year ) {
        $months = (int) floor( $diff / $month );
        if ( $months === 2 ) return __( 'منذ شهرين', 'iwd-slider' );
        return sprintf( __( 'منذ %d أشهر', 'iwd-slider' ), $months );
    } elseif ( $diff < 2 * $year ) {
        return __( 'منذ سنة', 'iwd-slider' );
    } else {
        $years = (int) floor( $diff / $year );
        if ( $years === 2 ) return __( 'منذ سنتين', 'iwd-slider' );
        return sprintf( __( 'منذ %d سنوات', 'iwd-slider' ), $years );
    }
}


/* ─────────────────────────────────────────────
   3.  META BOXES  (body text, PDF URL, link URL)
       Time label is now automatic — no field needed.
───────────────────────────────────────────── */
function iwd_add_slider_meta_boxes() {
    add_meta_box(
        'iwd_slider_details',
        __( 'Card Details', 'iwd-slider' ),
        'iwd_slider_meta_box_html',
        'iwd_slider_card',
        'normal',
        'high'
    );
}
add_action( 'add_meta_boxes', 'iwd_add_slider_meta_boxes' );

function iwd_slider_meta_box_html( $post ) {
    wp_nonce_field( 'iwd_slider_save', 'iwd_slider_nonce' );

    $body_text = get_post_meta( $post->ID, '_iwd_body_text', true );
    $pdf_url   = get_post_meta( $post->ID, '_iwd_pdf_url',   true );
    $link_url  = get_post_meta( $post->ID, '_iwd_link_url',  true );
    ?>
    <style>
        .iwd-meta-table { width:100%; border-collapse:collapse; }
        .iwd-meta-table th { width:160px; text-align:right; padding:10px 12px; font-weight:600; vertical-align:top; }
        .iwd-meta-table td { padding:8px 4px; }
        .iwd-meta-table input[type=url],
        .iwd-meta-table textarea { width:100%; }
        .iwd-meta-table textarea { height:80px; }
        .iwd-time-preview { display:inline-block; background:#f0f0f0; border-radius:4px; padding:4px 10px; font-size:13px; color:#555; }
    </style>
    <table class="iwd-meta-table">
        <tr>
            <th><?php _e( 'Time Label', 'iwd-slider' ); ?></th>
            <td>
                <span class="iwd-time-preview">
                    ⏱ <?php echo esc_html( iwd_time_ago( $post->ID ) ); ?>
                </span>
                <p class="description" style="margin-top:4px">
                    <?php _e( 'Auto-calculated from the publish date. Update the post date to change it.', 'iwd-slider' ); ?>
                </p>
            </td>
        </tr>
        <tr>
            <th><label for="iwd_body_text"><?php _e( 'Body Text', 'iwd-slider' ); ?></label></th>
            <td><textarea id="iwd_body_text" name="iwd_body_text"><?php echo esc_textarea( $body_text ); ?></textarea></td>
        </tr>
        <tr>
            <th><label for="iwd_pdf_url"><?php _e( 'PDF File URL', 'iwd-slider' ); ?></label></th>
            <td>
                <input type="url" id="iwd_pdf_url" name="iwd_pdf_url"
                       value="<?php echo esc_url( $pdf_url ); ?>"
                       placeholder="https://...">
                <button type="button" class="button iwd-media-upload"
                        data-target="#iwd_pdf_url"
                        data-type="application/pdf"><?php _e( 'Upload PDF', 'iwd-slider' ); ?></button>
            </td>
        </tr>
        <tr>
            <th><label for="iwd_link_url"><?php _e( 'Button Link URL', 'iwd-slider' ); ?></label></th>
            <td><input type="url" id="iwd_link_url" name="iwd_link_url"
                       value="<?php echo esc_url( $link_url ); ?>"
                       placeholder="https://..."></td>
        </tr>
    </table>
    <script>
    jQuery(function($){
        $('.iwd-media-upload').on('click', function(){
            var btn    = $(this);
            var target = $(btn.data('target'));
            var frame  = wp.media({
                title  : '<?php echo esc_js( __( 'Select or Upload File', 'iwd-slider' ) ); ?>',
                button : { text: '<?php echo esc_js( __( 'Use this file', 'iwd-slider' ) ); ?>' },
                multiple: false
            });
            frame.on('select', function(){
                var attachment = frame.state().get('selection').first().toJSON();
                target.val( attachment.url );
            });
            frame.open();
        });
    });
    </script>
    <?php
}

function iwd_save_slider_meta( $post_id ) {
    if ( ! isset( $_POST['iwd_slider_nonce'] ) ) return;
    if ( ! wp_verify_nonce( $_POST['iwd_slider_nonce'], 'iwd_slider_save' ) ) return;
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
    if ( ! current_user_can( 'edit_post', $post_id ) ) return;

    $fields = [
        '_iwd_body_text' => 'iwd_body_text',
        '_iwd_pdf_url'   => 'iwd_pdf_url',
        '_iwd_link_url'  => 'iwd_link_url',
    ];

    foreach ( $fields as $meta_key => $post_key ) {
        if ( isset( $_POST[ $post_key ] ) ) {
            update_post_meta( $post_id, $meta_key, sanitize_text_field( wp_unslash( $_POST[ $post_key ] ) ) );
        }
    }
}
add_action( 'save_post_iwd_slider_card', 'iwd_save_slider_meta' );


/* ─────────────────────────────────────────────
   4.  SHORTCODE  [iwd_slider]
       Optional attributes:
         count   – number of cards (default: -1 = all)
         orderby – WP_Query orderby  (default: menu_order)
         order   – ASC / DESC        (default: ASC)
───────────────────────────────────────────── */
function iwd_slider_shortcode( $atts ) {
    $atts = shortcode_atts( [
        'count'   => -1,
        'orderby' => 'menu_order',
        'order'   => 'ASC',
    ], $atts, 'iwd_slider' );

    $query = new WP_Query( [
        'post_type'      => 'iwd_slider_card',
        'post_status'    => 'publish',
        'posts_per_page' => intval( $atts['count'] ),
        'orderby'        => sanitize_key( $atts['orderby'] ),
        'order'          => in_array( strtoupper( $atts['order'] ), [ 'ASC', 'DESC' ] ) ? strtoupper( $atts['order'] ) : 'ASC',
    ] );

    if ( ! $query->have_posts() ) return '';

    /* enqueue assets */
    wp_enqueue_style(  'slick-css',       'https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css',       [], null );
    wp_enqueue_style(  'slick-theme-css', 'https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick-theme.min.css', [], null );
    wp_enqueue_script( 'jquery' );
    wp_enqueue_script( 'slick-js', 'https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js', [ 'jquery' ], null, true );

    $pdf_icon_url   = 'https://360.era-solutions.com/IWD/wp-content/uploads/2026/03/pdf.svg';
    $arrow_right    = 'https://360.era-solutions.com/IWD/wp-content/uploads/2026/03/red_arrow-2.svg';
    $arrow_left     = 'https://360.era-solutions.com/IWD/wp-content/uploads/2026/03/red_arrow.svg';

    ob_start(); ?>

    <!-- IWD Slider Styles -->
    <style>
    .logo_slider{padding:0 70px!important}
    .logo_slider .slick-next:before{content:url(<?php echo esc_url($arrow_right); ?>)}
    .logo_slider .slick-next{right:45px}
    .logo_slider .slick-prev{left:5px;z-index:99}
    .logo_slider .slick-prev:before{content:url(<?php echo esc_url($arrow_left); ?>)}
    .logo_slider .slick-slider{overflow:visible}
    .logo_slider .slick-track{display:flex;align-items:center;justify-content:center}
    .logo_slider img{width:100%;border-radius:16px 16px 0 0}
    .logo_slider .slide-one{margin:0 10px}
    .logo_slider p{font-family:"Tajawal",Sans-serif;font-size:16px;font-weight:400;color:#000;text-align:right;padding:0 15px}
    .logo_slider h3{font-family:"Tajawal",Sans-serif;font-size:16px;text-align:right;color:#000;font-weight:700;padding:0 15px;margin-bottom:5px}
    .logo_slider span{text-align:right;display:block;font-family:"Tajawal",Sans-serif;font-size:14px;color:#4B5563;padding:0 15px}
    .logo_slider a{text-align:center;display:flex;color:#C91717;border:1px solid #C91717;font-family:"Tajawal",Sans-serif;padding:12px 24px;border-radius:8px;margin:0 15px;justify-content:center;align-items:center;text-decoration:none}
    .logo_slider .container{background-color:#F7E8E8;border-radius:16px;padding-bottom:20px}
    .logo_slider a img{width:24px}
    .logo_slider .slick-dots li button:before{color:transparent;border:1px solid red;border-radius:50%;width:10px;height:10px}
    .slick-dots li.slick-active button:before{background:red;color:transparent!important;opacity:1!important}
    .logo_slider .slick-dots li{margin:0}
    .logo_slider .slick-dots{bottom:unset;position:unset}
    @media screen and (max-width:767px){
        .logo_slider{padding:0!important}
        .logo_slider .slick-prev,.logo_slider .slick-next{display:none!important}
    }
    </style>

    <div class="slick-list logo_slider">
        <?php while ( $query->have_posts() ) : $query->the_post();
            $time_label  = iwd_time_ago( get_the_ID() );
            $body_text   = get_post_meta( get_the_ID(), '_iwd_body_text',  true );
            $pdf_url     = get_post_meta( get_the_ID(), '_iwd_pdf_url',    true );
            $link_url    = get_post_meta( get_the_ID(), '_iwd_link_url',   true ) ?: '#';
            $thumb_url   = get_the_post_thumbnail_url( get_the_ID(), 'large' );
        ?>
        <div class="slide-one slide">
            <div class="container">
                <?php if ( $thumb_url ) : ?>
                    <img src="<?php echo esc_url( $thumb_url ); ?>" alt="<?php the_title_attribute(); ?>">
                <?php endif; ?>
                <h3><?php the_title(); ?></h3>
                <span><?php echo esc_html( $time_label ); ?></span>
                <?php if ( $body_text ) : ?>
                    <p><?php echo nl2br( esc_html( $body_text ) ); ?></p>
                <?php endif; ?>
                <a href="<?php echo esc_url( $pdf_url ?: $link_url ); ?>"
                   <?php echo $pdf_url ? 'target="_blank" rel="noopener"' : ''; ?>>
                    <?php _e( 'Download PDF', 'iwd-slider' ); ?>
                    <img src="<?php echo esc_url( $pdf_icon_url ); ?>" alt="PDF">
                </a>
            </div>
        </div>
        <?php endwhile; wp_reset_postdata(); ?>
    </div>

    <script>
    jQuery(document).ready(function($){
        $(".logo_slider.slick-list").slick({
            slidesToShow  : 3,
            slidesToScroll: 1,
            arrows        : true,
            infinite      : true,
            autoplay      : false,
            dots          : true,
            responsive: [
                { breakpoint: 1024, settings: { slidesToShow: 2 } },
                { breakpoint: 767,  settings: { slidesToShow: 1 } }
            ]
        });
    });
    </script>

    <?php
    return ob_get_clean();
}
add_shortcode( 'iwd_slider', 'iwd_slider_shortcode' );


/* ─────────────────────────────────────────────
   5.  ADMIN COLUMNS  (thumbnail + dynamic time)
───────────────────────────────────────────── */
function iwd_slider_admin_columns( $columns ) {
    $new = [];
    foreach ( $columns as $key => $label ) {
        if ( $key === 'title' ) {
            $new['iwd_thumb'] = __( 'Image', 'iwd-slider' );
        }
        $new[ $key ] = $label;
        if ( $key === 'title' ) {
            $new['iwd_time']  = __( 'Time Label', 'iwd-slider' );
            $new['iwd_pdf']   = __( 'PDF', 'iwd-slider' );
        }
    }
    return $new;
}
add_filter( 'manage_iwd_slider_card_posts_columns', 'iwd_slider_admin_columns' );

function iwd_slider_admin_column_content( $column, $post_id ) {
    switch ( $column ) {
        case 'iwd_thumb':
            $thumb = get_the_post_thumbnail( $post_id, [ 60, 60 ] );
            echo $thumb ?: '—';
            break;
        case 'iwd_time':
            echo esc_html( iwd_time_ago( $post_id ) );
            break;
        case 'iwd_pdf':
            $pdf = get_post_meta( $post_id, '_iwd_pdf_url', true );
            echo $pdf
                ? '<a href="' . esc_url( $pdf ) . '" target="_blank">PDF ↗</a>'
                : '—';
            break;
    }
}
add_action( 'manage_iwd_slider_card_posts_custom_column', 'iwd_slider_admin_column_content', 10, 2 );

// add programme post type 
/* ─────────────────────────────────────────────
   1.  CUSTOM POST TYPE
───────────────────────────────────────────── */
function iwd_register_programme_post_type() {
    $labels = [
        'name'               => __( 'Programme Cards',        'iwd-programme-slider' ),
        'singular_name'      => __( 'Programme Card',         'iwd-programme-slider' ),
        'add_new'            => __( 'Add New Card',           'iwd-programme-slider' ),
        'add_new_item'       => __( 'Add New Programme Card', 'iwd-programme-slider' ),
        'edit_item'          => __( 'Edit Programme Card',    'iwd-programme-slider' ),
        'new_item'           => __( 'New Programme Card',     'iwd-programme-slider' ),
        'search_items'       => __( 'Search Programme Cards', 'iwd-programme-slider' ),
        'not_found'          => __( 'No programme cards found', 'iwd-programme-slider' ),
        'not_found_in_trash' => __( 'No programme cards in trash', 'iwd-programme-slider' ),
        'menu_name'          => __( 'Programme Cards',        'iwd-programme-slider' ),
    ];

    register_post_type( 'iwd_prog_card', [
        'labels'       => $labels,
        'public'       => false,
        'show_ui'      => true,
        'show_in_menu' => true,
        'menu_icon'    => 'dashicons-video-alt3',
        'supports'     => [ 'title' ],   // title = person name
        'rewrite'      => false,
    ] );
}
add_action( 'init', 'iwd_register_programme_post_type' );


/* ─────────────────────────────────────────────
   1b. ENQUEUE MEDIA LIBRARY ON EDIT SCREEN
───────────────────────────────────────────── */
function iwd_prog_enqueue_admin_media( $hook ) {
    if ( ! in_array( $hook, [ 'post.php', 'post-new.php' ] ) ) return;
    $screen = get_current_screen();
    if ( ! $screen || $screen->post_type !== 'iwd_prog_card' ) return;
    wp_enqueue_media();
}
add_action( 'admin_enqueue_scripts', 'iwd_prog_enqueue_admin_media' );


/* ─────────────────────────────────────────────
   2.  META BOX
       Fields:
         - Video URL          (_iwd_prog_video_url)
         - Video Poster image (_iwd_prog_poster_url)
         - Avatar image       (_iwd_prog_avatar_url)
         - Quote / body text  (_iwd_prog_quote)
         - Role / subtitle    (_iwd_prog_role)
───────────────────────────────────────────── */
function iwd_add_programme_meta_box() {
    add_meta_box(
        'iwd_prog_details',
        __( 'Card Details', 'iwd-programme-slider' ),
        'iwd_programme_meta_box_html',
        'iwd_prog_card',
        'normal',
        'high'
    );
}
add_action( 'add_meta_boxes', 'iwd_add_programme_meta_box' );

function iwd_programme_meta_box_html( $post ) {
    wp_nonce_field( 'iwd_prog_save', 'iwd_prog_nonce' );

    $video_url  = get_post_meta( $post->ID, '_iwd_prog_video_url',  true );
    $poster_url = get_post_meta( $post->ID, '_iwd_prog_poster_url', true );
    $avatar_url = get_post_meta( $post->ID, '_iwd_prog_avatar_url', true );
    $quote      = get_post_meta( $post->ID, '_iwd_prog_quote',      true );
    $role       = get_post_meta( $post->ID, '_iwd_prog_role',       true );
    ?>
    <style>
        .iwd-prog-table { width:100%; border-collapse:collapse; }
        .iwd-prog-table th { width:160px; text-align:left; padding:10px 12px; font-weight:600; vertical-align:top; }
        .iwd-prog-table td { padding:8px 4px; }
        .iwd-prog-table input[type=url],
        .iwd-prog-table input[type=text],
        .iwd-prog-table textarea { width:100%; box-sizing:border-box; }
        .iwd-prog-table textarea { height:80px; }
        .iwd-prog-table .button { margin-top:4px; }
        .iwd-prog-preview { max-width:120px; max-height:80px; display:block; margin-top:6px; border-radius:6px; }
    </style>

    <table class="iwd-prog-table">

        <tr>
            <th><label for="iwd_prog_video_url"><?php _e( 'Video URL', 'iwd-programme-slider' ); ?></label></th>
            <td>
                <input type="url" id="iwd_prog_video_url" name="iwd_prog_video_url"
                       value="<?php echo esc_url( $video_url ); ?>"
                       placeholder="https://...mp4">
                <button type="button" class="button iwd-prog-media-upload"
                        data-target="#iwd_prog_video_url"
                        data-mime="video/mp4"><?php _e( 'Upload Video', 'iwd-programme-slider' ); ?></button>
            </td>
        </tr>

        <tr>
            <th><label for="iwd_prog_poster_url"><?php _e( 'Video Poster', 'iwd-programme-slider' ); ?></label></th>
            <td>
                <input type="url" id="iwd_prog_poster_url" name="iwd_prog_poster_url"
                       value="<?php echo esc_url( $poster_url ); ?>"
                       placeholder="https://...jpg">
                <button type="button" class="button iwd-prog-media-upload"
                        data-target="#iwd_prog_poster_url"
                        data-mime="image"><?php _e( 'Upload Image', 'iwd-programme-slider' ); ?></button>
                <?php if ( $poster_url ) : ?>
                    <img src="<?php echo esc_url( $poster_url ); ?>" class="iwd-prog-preview" alt="">
                <?php endif; ?>
            </td>
        </tr>

        <tr>
            <th><label for="iwd_prog_quote"><?php _e( 'Quote / Text', 'iwd-programme-slider' ); ?></label></th>
            <td><textarea id="iwd_prog_quote" name="iwd_prog_quote"><?php echo esc_textarea( $quote ); ?></textarea></td>
        </tr>

        <tr>
            <th><label for="iwd_prog_avatar_url"><?php _e( 'Avatar Image', 'iwd-programme-slider' ); ?></label></th>
            <td>
                <input type="url" id="iwd_prog_avatar_url" name="iwd_prog_avatar_url"
                       value="<?php echo esc_url( $avatar_url ); ?>"
                       placeholder="https://...jpg">
                <button type="button" class="button iwd-prog-media-upload"
                        data-target="#iwd_prog_avatar_url"
                        data-mime="image"><?php _e( 'Upload Avatar', 'iwd-programme-slider' ); ?></button>
                <?php if ( $avatar_url ) : ?>
                    <img src="<?php echo esc_url( $avatar_url ); ?>" class="iwd-prog-preview" alt="">
                <?php endif; ?>
            </td>
        </tr>

        <tr>
            <th><label><?php _e( 'Person Name', 'iwd-programme-slider' ); ?></label></th>
            <td>
                <p class="description">
                    <?php _e( 'Set the name using the post <strong>Title</strong> field above.', 'iwd-programme-slider' ); ?>
                </p>
            </td>
        </tr>

        <tr>
            <th><label for="iwd_prog_role"><?php _e( 'Role / Subtitle', 'iwd-programme-slider' ); ?></label></th>
            <td>
                <input type="text" id="iwd_prog_role" name="iwd_prog_role"
                       value="<?php echo esc_attr( $role ); ?>"
                       placeholder="<?php esc_attr_e( 'e.g. رائدة أعمال', 'iwd-programme-slider' ); ?>">
            </td>
        </tr>

    </table>

    <script>
    jQuery(function($){
        $('.iwd-prog-media-upload').on('click', function(){
            var btn    = $(this);
            var target = $(btn.data('target'));
            var frame  = wp.media({
                title   : '<?php echo esc_js( __( 'Select or Upload File', 'iwd-programme-slider' ) ); ?>',
                button  : { text: '<?php echo esc_js( __( 'Use this file', 'iwd-programme-slider' ) ); ?>' },
                multiple: false
            });
            frame.on('select', function(){
                var att = frame.state().get('selection').first().toJSON();
                target.val( att.url );
                // refresh preview if next sibling is an img
                var preview = target.closest('td').find('.iwd-prog-preview');
                if ( preview.length ) {
                    preview.attr('src', att.url);
                } else if ( att.url.match(/\.(jpe?g|png|gif|webp|svg)$/i) ) {
                    $('<img class="iwd-prog-preview">').attr('src', att.url).insertAfter( btn );
                }
            });
            frame.open();
        });
    });
    </script>
    <?php
}

function iwd_save_programme_meta( $post_id ) {
    if ( ! isset( $_POST['iwd_prog_nonce'] ) ) return;
    if ( ! wp_verify_nonce( $_POST['iwd_prog_nonce'], 'iwd_prog_save' ) ) return;
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
    if ( ! current_user_can( 'edit_post', $post_id ) ) return;

    $url_fields = [ '_iwd_prog_video_url', '_iwd_prog_poster_url', '_iwd_prog_avatar_url' ];
    $map = [
        '_iwd_prog_video_url'  => 'iwd_prog_video_url',
        '_iwd_prog_poster_url' => 'iwd_prog_poster_url',
        '_iwd_prog_avatar_url' => 'iwd_prog_avatar_url',
        '_iwd_prog_quote'      => 'iwd_prog_quote',
        '_iwd_prog_role'       => 'iwd_prog_role',
    ];

    foreach ( $map as $meta_key => $post_key ) {
        if ( isset( $_POST[ $post_key ] ) ) {
            $value = wp_unslash( $_POST[ $post_key ] );
            $value = in_array( $meta_key, $url_fields )
                ? esc_url_raw( $value )
                : sanitize_text_field( $value );
            update_post_meta( $post_id, $meta_key, $value );
        }
    }
}
add_action( 'save_post_iwd_prog_card', 'iwd_save_programme_meta' );


/* ─────────────────────────────────────────────
   3.  SHORTCODE  [iwd_programme_slider]
       Optional attributes:
         count   – number of cards to show (default: -1 = all)
         orderby – WP_Query orderby         (default: menu_order)
         order   – ASC / DESC               (default: ASC)
───────────────────────────────────────────── */
function iwd_programme_slider_shortcode( $atts ) {
    $atts = shortcode_atts( [
        'count'   => -1,
        'orderby' => 'menu_order',
        'order'   => 'ASC',
    ], $atts, 'iwd_programme_slider' );

    $query = new WP_Query( [
        'post_type'      => 'iwd_prog_card',
        'post_status'    => 'publish',
        'posts_per_page' => intval( $atts['count'] ),
        'orderby'        => sanitize_key( $atts['orderby'] ),
        'order'          => in_array( strtoupper( $atts['order'] ), [ 'ASC', 'DESC' ] )
                                ? strtoupper( $atts['order'] ) : 'ASC',
    ] );

    if ( ! $query->have_posts() ) return '';

    /* ── enqueue assets ── */
    wp_enqueue_style(  'slick-css',       'https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css',       [], null );
    wp_enqueue_style(  'slick-theme-css', 'https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick-theme.min.css', [], null );
    wp_enqueue_script( 'jquery' );
    wp_enqueue_script( 'slick-js', 'https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js', [ 'jquery' ], null, true );

    $arrow_next = 'https://360.era-solutions.com/IWD/wp-content/uploads/2026/03/red_arrow-2.svg';
    $arrow_prev = 'https://360.era-solutions.com/IWD/wp-content/uploads/2026/03/red_arrow.svg';

    ob_start(); ?>

    <!-- IWD Programme Slider Styles -->
    <style>
    .programe_slider { padding: 0 70px; }
    .programe_slider video { cursor: pointer; border-radius: 16px; margin-bottom: 10px; width: 100%; display: block; }
    .programe_slider .slick-next:before { content: url(<?php echo esc_url( $arrow_next ); ?>); }
    .programe_slider .slick-next { right: 45px; }
    .programe_slider .slick-prev { left: 5px; z-index: 99; }
    .programe_slider .slick-prev:before { content: url(<?php echo esc_url( $arrow_prev ); ?>); }
    .programe_slider .slick-slider { overflow: visible; }
    .programe_slider .slick-track { display: flex; align-items: stretch; justify-content: center; }
    .programe_slider .slick-slide { height: auto; }
    .programe_slider .slick-slide > div { height: 100%; }
    .programe_slider .slide-one { margin: 0 10px; height: 100%; }
    .programe_slider .container { height: 100%; display: flex; flex-direction: column; }
    .programe_slider img { width: 100%; border-radius: 16px 16px 0 0; }
    .programe_slider a img { width: 24px; border-radius: 0; }
    .programe_slider p { font-family: "Tajawal", Sans-serif; font-size: 16px; font-weight: 400; color: #000; text-align: right; padding: 0 15px; margin: 0; }
    .programe_slider h3 { font-family: "Tajawal", Sans-serif; font-size: 16px; text-align: right; color: #000; font-weight: 700; padding: 0 15px; margin-bottom: 5px; }
    .programe_slider span { text-align: right; display: block; font-family: "Tajawal", Sans-serif; font-size: 14px; color: #4B5563; padding: 0 15px; }
    .programe_slider .content { background: #F7E8E8; padding: 20px 0; border-radius: 12px; flex: 1; }
    .programe_slider .row { display: flex; justify-content: flex-end; flex-direction: row-reverse; margin: 20px 20px 0; align-items: center; gap: 10px; }
    .programe_slider .row img { width: 40px; height: 40px; border-radius: 50%; object-fit: cover; }
    .programe_slider .slick-dots li button:before { color: transparent; border: 1px solid red; border-radius: 50%; width: 10px; height: 10px; }
    .programe_slider li.slick-active button:before { background: red; color: transparent; opacity: 1; }
    .programe_slider .slick-dots li { margin: 0; }
    .programe_slider .slick-dots { bottom: unset; position: unset; }
    @media screen and (max-width: 767px) {
        .programe_slider { padding: 0 !important; }
        .programe_slider .slick-prev, .programe_slider .slick-next { display: none !important; }
    }
    </style>

    <div class="slick-list programe_slider">

        <?php while ( $query->have_posts() ) : $query->the_post();
            $video_url  = get_post_meta( get_the_ID(), '_iwd_prog_video_url',  true );
            $poster_url = get_post_meta( get_the_ID(), '_iwd_prog_poster_url', true );
            $avatar_url = get_post_meta( get_the_ID(), '_iwd_prog_avatar_url', true );
            $quote      = get_post_meta( get_the_ID(), '_iwd_prog_quote',      true );
            $role       = get_post_meta( get_the_ID(), '_iwd_prog_role',       true );
            $name       = get_the_title();
        ?>

        <div class="slide-one slide">
            <div class="container">

                <?php if ( $video_url ) : ?>
                <video controls<?php echo $poster_url ? ' poster="' . esc_url( $poster_url ) . '"' : ''; ?>>
                    <source src="<?php echo esc_url( $video_url ); ?>" type="video/mp4">
                </video>
                <?php endif; ?>

                <div class="content">

                    <?php if ( $quote ) : ?>
                    <p><?php echo nl2br( esc_html( $quote ) ); ?></p>
                    <?php endif; ?>

                    <div class="row">
                        <?php if ( $avatar_url ) : ?>
                        <div><img src="<?php echo esc_url( $avatar_url ); ?>" alt="<?php echo esc_attr( $name ); ?>"></div>
                        <?php endif; ?>
                        <div>
                            <?php if ( $name ) : ?>
                            <h3><?php echo esc_html( $name ); ?></h3>
                            <?php endif; ?>
                            <?php if ( $role ) : ?>
                            <p><?php echo esc_html( $role ); ?></p>
                            <?php endif; ?>
                        </div>
                    </div>

                </div><!-- .content -->

            </div><!-- .container -->
        </div><!-- .slide-one -->

        <?php endwhile; wp_reset_postdata(); ?>

    </div><!-- .programe_slider -->

    <script>
    jQuery(document).ready(function($){
        $(".programe_slider.slick-list").slick({
            slidesToShow  : 3,
            slidesToScroll: 1,
            arrows        : true,
            infinite      : true,
            autoplay      : false,
            dots          : true,
            responsive: [
                { breakpoint: 1024, settings: { slidesToShow: 2 } },
                { breakpoint: 767,  settings: { slidesToShow: 1 } }
            ]
        });
    });
    </script>

    <?php
    return ob_get_clean();
}
add_shortcode( 'iwd_programme_slider', 'iwd_programme_slider_shortcode' );


/* ─────────────────────────────────────────────
   4.  ADMIN COLUMNS
───────────────────────────────────────────── */
function iwd_prog_admin_columns( $columns ) {
    $new = [];
    foreach ( $columns as $key => $label ) {
        if ( $key === 'title' ) {
            $new['iwd_poster'] = __( 'Poster', 'iwd-programme-slider' );
        }
        $new[ $key ] = $label;
        if ( $key === 'title' ) {
            $new['iwd_role']  = __( 'Role', 'iwd-programme-slider' );
            $new['iwd_video'] = __( 'Video', 'iwd-programme-slider' );
        }
    }
    return $new;
}
add_filter( 'manage_iwd_prog_card_posts_columns', 'iwd_prog_admin_columns' );

function iwd_prog_admin_column_content( $column, $post_id ) {
    switch ( $column ) {
        case 'iwd_poster':
            $poster = get_post_meta( $post_id, '_iwd_prog_poster_url', true );
            echo $poster
                ? '<img src="' . esc_url( $poster ) . '" style="width:60px;height:40px;object-fit:cover;border-radius:4px;" alt="">'
                : '—';
            break;
        case 'iwd_role':
            echo esc_html( get_post_meta( $post_id, '_iwd_prog_role', true ) ?: '—' );
            break;
        case 'iwd_video':
            $vid = get_post_meta( $post_id, '_iwd_prog_video_url', true );
            echo $vid
                ? '<a href="' . esc_url( $vid ) . '" target="_blank">▶ Video</a>'
                : '—';
            break;
    }
}
add_action( 'manage_iwd_prog_card_posts_custom_column', 'iwd_prog_admin_column_content', 10, 2 );