<?php
defined( 'ABSPATH' ) || exit; // Exit if accessed directly

if (! class_exists('Gridpress_WP_Bakery_Elements')) {

    class Gridpress_WP_Bakery_Elements {

        public function __construct() {
            add_action( 'vc_before_init', [ $this, 'gridpress_grid_element' ] );
        }

        public function gridpress_grid_element() {

            $gridpress_grid_list = [
                esc_html__( 'Select Grid', 'gridpress-grid-layout-design' ) => '',
            ];

            $gridpress_grid_posts = get_posts( [
                'post_type'      => 'gridpress_grid',
                'posts_per_page' => -1,
                'post_status'    => 'publish',
                'no_found_rows'  => true,
            ] );

            if ( ! is_wp_error( $gridpress_grid_posts ) && ! empty( $gridpress_grid_posts ) ) {
                foreach ( $gridpress_grid_posts as $gridpress_post_obj ) {

                    $gridpress_post_id = absint( $gridpress_post_obj->ID );
                    $gridpress_title   = get_the_title( $gridpress_post_id );

                    $gridpress_label = sprintf(
                        /* translators: 1: post title, 2: post ID */
                        esc_html( __( '%1$s (id: %2$d)', 'gridpress-grid-layout-design' ) ),
                        esc_html( $gridpress_title ),
                        $gridpress_post_id
                    );

                    $gridpress_grid_list[ $gridpress_label ] = $gridpress_post_id;
                }
            }

            $gridpress_attributes = [
                'name'     => esc_html__( 'Grid', 'gridpress-grid-layout-design' ),
                'base'     => 'gridpress_grid',
                'class'    => '',
                'category' => esc_html__( 'Gridpress', 'gridpress-grid-layout-design' ),
                'params'   => [
                    [
                        'type'        => 'dropdown',
                        'heading'     => esc_html__( 'Select Grid', 'gridpress-grid-layout-design' ),
                        'param_name'  => 'id',
                        'value'       => $gridpress_grid_list,
                        'description' => '',
                    ],
                ],
            ];

            if ( function_exists( 'vc_map' ) ) {
                vc_map( $gridpress_attributes );
            }
        }
    }
    new Gridpress_WP_Bakery_Elements();
}