Snippets Collections
<?php

class Product_Search_Widget extends \Elementor\Widget_Base
{
    public function get_name()
    {
        return 'product-search-widget';
    }

    public function get_title()
    {
        return __('Product Search Widget', 'text-domain');
    }

    public function get_icon()
    {
        return 'eicon-search'; 
    }

    public function get_categories()
    {
        return ['general'];
    }

    protected function render()
    {
        ?>

        <form class="pp-search-form" role="search" action="<?php echo esc_url(home_url('/')); ?>" method="get" aria-label="Search form">
            <div class="pp-search-form__toggle">
                <i class="fa fa-search" aria-hidden="true"></i>
            </div>
            <div class="pp-search-form__container pp-search-form--lightbox">
                <div class="search-form">
                    <label class="pp-screen-reader-text" for="pp-search-form__input-<?php echo esc_attr($this->get_id()); ?>">
                        Search our products
                    </label>
                    <input id="pp-search-form__input-<?php echo esc_attr($this->get_id()); ?>" class="pp-search-form__input" type="search" name="s" title="Search" value="">
                </div>
                <button type="submit" class="pp-search-form__button">
                    <span class="pp-icon-search" aria-hidden="true">
                        <i class="fa fa-search" aria-hidden="true"></i>
                    </span>
                </button>
                <input type="hidden" name="post_type" value="product"> 
                <div class="pp-search-form--lightbox-close">
                    <span class="pp-icon-close" aria-hidden="true">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><path d="M342.6 150.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L192 210.7 86.6 105.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L146.7 256 41.4 361.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0L192 301.3 297.4 406.6c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L237.3 256 342.6 150.6z"/></svg>
                    </span>
                </div>
            </div>
        </form>
        
        <?php
    }
}

\Elementor\Plugin::instance()->widgets_manager->register_widget_type(new Product_Search_Widget());



JS

$('#ceremonial').change(function () {
    var ceremonial_id = $(this).val();
    $('#responsible_ceremonial_name').empty().append('<option value=""></option>');
    $('#responsible_ceremonial_phone').val('');

    if (ceremonial_id) {
      $.ajax({
        url: BASE_URL + 'Ajax/getResponsibleCeremonialName',
        type: 'POST',
        data: { ceremonial_id: ceremonial_id },
        dataType: 'json',
        success: function (data) {
          $('#responsible_ceremonial_name').append('<option value="new">Novo</option>');
          $.each(data, function (index, responsible_ceremonial) {
            $('#responsible_ceremonial_name').append('<option value="' + responsible_ceremonial.id + '">' + responsible_ceremonial.name + '</option>');
          });


        },
        error: function (jqXHR, textStatus, errorThrown) {
          console.error('Erro ao buscar responsavel pelo cerimonial: ' + textStatus);
        }
      });
    }
  });


HTML - Primeiro Select normal preenchido pelo BD

<div id="select_ceremonial" class="col-lg-3 col-md-8">
                                            <!-- <label for="">Informações do Local do evento:</label> -->
                                            <div class="input-group mb-3">
                                                <div class="input-group-prepend">
                                                    <!-- <label class="input-group-text" for="ceremonial">Local</label> -->
                                                </div>
                                                <select class="custom-select" id="ceremonial" name="ceremonial">
                                                    <option value="" selected></option>
                                                    <option value="0">Novo</option>
                                                    <?php foreach ($ceremonials as $ceremonial) : ?>
                                                        <?php if (isset($info_event)) : ?> <!-- verificando se o form é create ou edit -->
                                                            <option value="<?= $ceremonial['id'] ?>" <?= ($info_event['ceremonial_id'] == $ceremonial['id']) ? 'selected' : '' ?>><?= $ceremonial['name'] ?></option>
                                                        <?php else : ?>
                                                            <option value="<?= $ceremonial['id'] ?>"><?= $ceremonial['name'] ?></option>
                                                        <?php endif; ?> <!-- fim da verificação create edit -->
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                        </div>


O SELECT A SER PREENCHIDO
<div class="col-lg-2 col-md-6 responsible-ceremonial-name">
                                            <div class="input-group mb-3">
                                                <!-- select controlado por js -->
                                                <select class="custom-select" name="responsible_ceremonial_name" id="responsible_ceremonial_name">

                                                    <option value="" selected></option>

                                                </select>

                                                <!-- fim select controlado -->
                                            </div>
                                        </div>
// Splide JS
function splide_js_script () {
    wp_enqueue_script( 'splide-js', 'https://cdn.jsdelivr.net/npm/@splidejs/splide@4.1.4/dist/js/splide.min.js', null, null, true );
    wp_enqueue_style('splide-css', 'https://cdn.jsdelivr.net/npm/@splidejs/splide@4.1.4/dist/css/splide.min.css');
}
add_action( 'wp_enqueue_scripts', 'splide_js_script' );
<?php

/**
 * Checkout billing information form
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/checkout/form-billing.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see     https://woocommerce.com/document/template-structure/
 * @package WooCommerce\Templates
 * @version 3.6.0
 * @global WC_Checkout $checkout
 */

defined('ABSPATH') || exit;
$fields = $checkout->get_checkout_fields('billing');
?>
<?php if (!is_user_logged_in() && $checkout->is_registration_enabled()) : ?>
  <div class="woocommerce-billing-fields woocommerce-billing-fields-top">
    <h3><?php esc_html_e('Login', 'woocommerce'); ?></h3>
    <p>Log in to place your order</p>
    <div class="woocommerce-billing-fields__field-wrapper">
      <?php
      foreach ($fields as $key => $field) {
        if ($key === 'billing_email') {
          woocommerce_form_field($key, $field, $checkout->get_value($key));
        }
      }
      ?>
      <p class="form-row form-row-wide" id="billing_password_field" data-priority="110">
        <span class="woocommerce-input-wrapper">
          <input type="password" class="input-text" name="billing_password" id="billing_password" placeholder="Password">
        </span>
      </p>
      <div class="flogin-btn">
        <button type="button"><?php _e('Login and place order', 'wp'); ?></button>
      </div>
      <div class="flogin-footer">
        <div>Not yet a member?</div>
        <div>create an account</div>
        <div>Create an account and place your order</div>
      </div>
    </div>
  </div>
<?php else : ?>
  <div class="woocommerce-billing-fields">
    <h3><?php esc_html_e('Account', 'woocommerce'); ?></h3>
    <div class="woocommerce-billing-fields__field-wrapper">
      <?php
      foreach ($fields as $key => $field) {
        if ($key === 'billing_email') {
          woocommerce_form_field($key, $field, $checkout->get_value($key));
        }
      }
      ?>
    </div>
  </div>
<?php endif; ?>
<div class="woocommerce-billing-fields">
  <?php if (wc_ship_to_billing_address_only() && WC()->cart->needs_shipping()) : ?>

    <h3><?php esc_html_e('Billing &amp; Shipping', 'woocommerce'); ?></h3>

  <?php else : ?>

    <h3><?php esc_html_e('Billing Info', 'woocommerce'); ?></h3>

  <?php endif; ?>

  <?php do_action('woocommerce_before_checkout_billing_form', $checkout); ?>

  <div class="woocommerce-billing-fields__field-wrapper">
    <?php
    foreach ($fields as $key => $field) {
      if ($key !== 'billing_email') {
        woocommerce_form_field($key, $field, $checkout->get_value($key));
      }
    }
    ?>
	 
      <?php woocommerce_form_field('billing_notes', array(
            'type' => 'textarea',
            'class' => array('form-row-wide'),
            'label' => false,
            'placeholder' => __('Order notes(optional)', 'woocommerce'),
            'required' => false,
        ), $checkout->get_value('billing_notes')); ?>
    
    <div class="form-row shipping-address-method-field">
      <input type="radio" name="shipping-address-method[]" value="billing_address" id="method-billing_address" checked>
      <label for="method-billing_address">Ship to this address</label>
    </div>
  </div>

  <?php do_action('woocommerce_after_checkout_billing_form', $checkout); ?>
</div>

<?php if (!is_user_logged_in() && $checkout->is_registration_enabled()) : ?>
  <div class="woocommerce-account-fields">
    <?php if (!$checkout->is_registration_required()) : ?>

      <p class="form-row form-row-wide create-account">
        <label class="woocommerce-form__label woocommerce-form__label-for-checkbox checkbox">
          <input class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox" id="createaccount" <?php checked((true === $checkout->get_value('createaccount') || (true === apply_filters('woocommerce_create_account_default_checked', false))), true); ?> type="checkbox" name="createaccount" value="1" /> <span><?php esc_html_e('Create an account?', 'woocommerce'); ?></span>
        </label>
      </p>

    <?php endif; ?>

    <?php do_action('woocommerce_before_checkout_registration_form', $checkout); ?>

    <?php if ($checkout->get_checkout_fields('account')) : ?>

      <div class="create-account">
        <?php foreach ($checkout->get_checkout_fields('account') as $key => $field) : ?>
          <?php woocommerce_form_field($key, $field, $checkout->get_value($key)); ?>
        <?php endforeach; ?>
        <div class="clear"></div>
      </div>

    <?php endif; ?>

    <?php do_action('woocommerce_after_checkout_registration_form', $checkout); ?>
  </div>
<?php endif; ?>
<?php
// Define the start year and get the current year
$start_year = 2020; // Replace with your start year
$current_year = date('Y');
?>
<p>&copy; <?php echo $start_year; ?><?php if ($start_year != $current_year) echo '-' . $current_year; ?> <?php bloginfo('name'); ?>. Minden jog fenntartva.</p>
<?php
/**
 * Review order table
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/checkout/review-order.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see https://woocommerce.com/document/template-structure/
 * @package WooCommerce\Templates
 * @version 5.2.0
 */

defined( 'ABSPATH' ) || exit;
$total_order = WC()->cart->total;
$total_sale = 0;

foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
    $product = $cart_item['data'];
    if ( $product->is_on_sale() ) {
        $total_sale += ( $product->get_regular_price() - $product->get_sale_price() ) * $cart_item['quantity'];
    }
}
?>
<div class="woocommerce-checkout-review-order-table">
	<?php do_action('custom-freeshiping-bar');?>
    <div id="total-header">
    <button type="button" id="toggle-cart-items" class="button-toggle-cart">
        Order Summary
		<i class="fa-solid fa-chevron-down"></i>
    </button>
	<div class="total-money">
       <span class="total-sale">$<?php echo number_format($total_sale, 2); ?></span>
       <span class="total-order">$<?php echo number_format($total_order, 2); ?></span>
    </div>
</div>
    <div id="cart-details">
		<div class="title-in-review">
				<h3 class="co-h3">PURCHARE SUMMARY</h3>
				<?php do_action('custom-freeshiping-bar');?>
			</div>
        <ul id="cart-items-list" class="woocommerce-mini-cart cart_list product_list_widget">
            <?php if ( ! WC()->cart->is_empty() ) : ?>
                <?php
                    do_action( 'woocommerce_review_order_before_cart_contents' );

                    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
                        $_product     = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
                        $product_id   = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );

                        if ( $_product && $_product->exists() && $cart_item['quantity'] > 0 && apply_filters( 'woocommerce_checkout_cart_item_visible', true, $cart_item, $cart_item_key ) ) {
                            $product_name      = apply_filters( 'woocommerce_cart_item_name', $_product->get_name(), $cart_item, $cart_item_key );
                            $thumbnail         = apply_filters( 'woocommerce_cart_item_thumbnail', $_product->get_image(), $cart_item, $cart_item_key );
                            $product_price     = apply_filters( 'woocommerce_cart_item_subtotal', WC()->cart->get_product_subtotal( $_product, $cart_item['quantity'] ), $cart_item, $cart_item_key );
                            $product_permalink = apply_filters( 'woocommerce_cart_item_permalink', $_product->is_visible() ? $_product->get_permalink( $cart_item ) : '', $cart_item, $cart_item_key );

                            if ( empty( $product_permalink ) ) {
                                $product_name = '<span class="nm-cart-panel-product-title">' . wp_kses_post( $product_name ) . '</span>';
                            } else {
                                $product_permalink = esc_url( $product_permalink );
                                $thumbnail = '<a href="' . $product_permalink . '">' . $thumbnail . '</a>';
                                $product_name = '<a href="' . $product_permalink . '" class="nm-cart-panel-product-title">' . wp_kses_post( $product_name ) . '</a>';
                            }

                            $product = wc_get_product($product_id);

                            ?>
                            <li id="nm-cart-panel-item-<?php echo esc_attr( $cart_item_key ); ?>" class="woocommerce-mini-cart-item <?php echo esc_attr( apply_filters( 'woocommerce_mini_cart_item_class', 'mini_cart_item', $cart_item, $cart_item_key ) ); ?>">
                                <div class="nm-cart-panel-item-thumbnail">
                                    <div class="nm-cart-item-loader nm-loader"></div>
                                    <div class="nm-cart-panel-thumbnail-wrap">
                                        <?php echo $thumbnail; ?>
                                        <div class="nm-cart-panel-thumbnail-loader nm-loader"></div>
                                    </div>
                                </div>
                                <div class="nm-cart-panel-item-details">
                                    <?php echo apply_filters( 'woocommerce_cart_item_remove_link',
                                        sprintf(
                                            '<a href="%s" class="remove remove_from_cart_button" aria-label="%s" data-product_id="%s" data-cart_item_key="%s" data-product_sku="%s"><i class="nm-font nm-font-close2"></i></a>',
                                            esc_url( wc_get_cart_remove_url( $cart_item_key ) ),
                                            esc_attr( sprintf( __( 'Remove %s from cart', 'woocommerce' ), wp_strip_all_tags( $product_name ) ) ),
                                            esc_attr( $product_id ),
                                            esc_attr( $cart_item_key ),
                                            esc_attr( $_product->get_sku() )
                                        ), $cart_item_key );
                                    ?>
                                    <?php echo $product_name; ?>
                                    <?php echo wc_get_formatted_cart_item_data( $cart_item ); ?>
                                    <div class="nm-cart-panel-quantity-pricing">
                                        <?php if ( $_product->is_sold_individually() ) : ?>
                                            <?php echo apply_filters( 'woocommerce_widget_cart_item_quantity', '<span class="quantity">' . esc_html__( 'Qty', 'woocommerce' ) . ': ' . $cart_item['quantity'] . '</span>', $cart_item, $cart_item_key ); ?>
                                        <?php else: ?>
                                            <div class="product-quantity" data-title="<?php esc_html_e( 'Quantity', 'woocommerce' ); ?>">
                                                <?php
                                                    $product_quantity = woocommerce_quantity_input( array(
                                                        'input_name'  => "cart[{$cart_item_key}][qty]",
                                                        'input_value' => $cart_item['quantity'],
                                                        'max_value'   => $_product->backorders_allowed() ? '' : $_product->get_stock_quantity(),
                                                        'min_value'   => '1',
                                                        'nm_mini_cart_quantity' => true 
                                                    ), $_product, false );

                                                    echo apply_filters( 'woocommerce_widget_cart_item_quantity', $product_quantity, $cart_item, $cart_item_key );
                                                ?>
                                            </div>
                                        <?php endif; ?>

                                        <div class="nm-cart-panel-item-price">
                                            <?php if ( $price_html = $product->get_price_html() ) : ?>
                                                <span class="price"><?php echo $price_html; ?></span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </li>
                            <?php
                        }
                    }

                    do_action( 'woocommerce_review_order_after_cart_contents' );
                ?>
            <?php else: ?>
                <li class="empty">
                    <i class="nm-font nm-font-close2"></i>
                    <span><?php esc_html_e( 'No products in the cart.', 'woocommerce' ); ?></span>
                </li>
            <?php endif; ?>
        </ul>

        <?php do_action( 'woocommerce_custom_checkout_counpon' ); ?>
        <table class="shop_table">
            <tfoot>
                <tr class="cart-subtotal">
                    <th><?php esc_html_e( 'Subtotal', 'woocommerce' ); ?></th>
                    <td><?php wc_cart_totals_subtotal_html(); ?></td>
                </tr>

                <?php foreach ( WC()->cart->get_coupons() as $code => $coupon ) : ?>
                    <tr class="cart-discount coupon-<?php echo esc_attr( sanitize_title( $code ) ); ?>">
                        <th><?php wc_cart_totals_coupon_label( $coupon ); ?></th>
                        <td><?php wc_cart_totals_coupon_html( $coupon ); ?></td>
                    </tr>
                <?php endforeach; ?>

                <?php if ( WC()->cart->needs_shipping() && WC()->cart->show_shipping() ) : ?>
				<?php
				// Get available shipping methods
				$available_methods = WC()->shipping->get_packages()[0]['rates'];
				$chosen_methods = WC()->session->get('chosen_shipping_methods');
				$chosen_method = !empty($chosen_methods[0]) ? $chosen_methods[0] : '';

				// Only display the chosen method
				if (!empty($available_methods[$chosen_method])) {
					echo '<tr class="shipping">';
					echo '<th>' . esc_html__('Shipping', 'woocommerce') . '</th>';
					echo '<td data-title="Shipping">' . wp_kses_post($available_methods[$chosen_method]->label . ': ' . wc_price($available_methods[$chosen_method]->cost)) . '</td>';
					echo '</tr>';
				}
				?>
			<?php endif; ?>


                <?php foreach ( WC()->cart->get_fees() as $fee ) : ?>
                    <tr class="fee">
                        <th><?php echo esc_html( $fee->name ); ?></th>
                        <td><?php wc_cart_totals_fee_html( $fee ); ?></td>
                    </tr>
                <?php endforeach; ?>

                <?php if ( wc_tax_enabled() && ! WC()->cart->display_prices_including_tax() ) : ?>
                    <?php if ( 'itemized' === get_option( 'woocommerce_tax_total_display' ) ) : ?>
                        <?php foreach ( WC()->cart->get_tax_totals() as $code => $tax ) : ?>
                            <tr class="tax-rate tax-rate-<?php echo esc_attr( sanitize_title( $code ) ); ?>">
                                <th><?php echo esc_html( $tax->label ); ?></th>
                                <td><?php echo wp_kses_post( $tax->formatted_amount ); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else : ?>
                        <tr class="tax-total">
                            <th><?php echo esc_html( WC()->countries->tax_or_vat() ); ?></th>
                            <td><?php wc_cart_totals_taxes_total_html(); ?></td>
                        </tr>
                    <?php endif; ?>
                <?php endif; ?>

                <?php do_action( 'woocommerce_review_order_before_order_total' ); ?>

                <tr class="order-total">
                    <th><?php esc_html_e( 'Total', 'woocommerce' ); ?></th>
                    <td><?php wc_cart_totals_order_total_html(); ?></td>
                </tr>

                <?php do_action( 'woocommerce_review_order_after_order_total' ); ?>
            </tfoot>
        </table>
    </div>
</div>


add_action( 'admin_menu', 'my_custom_menu_page' );
function my_custom_menu_page() {
add_menu_page(
__( 'Custom Menu Title', 'textdomain' ),
'Custom Menu',
'manage_options',
'custompage',
'my_custom_menu_page_content',
'dashicons-admin-generic',
);
}

add_action( 'admin_menu', 'my_custom_submenu_page' );
function my_custom_submenu_page() {
add_submenu_page(
'custompage',
__( 'Custom Submenu Title', 'textdomain' ),
'Custom Submenu',
'manage_options',
'customsubmenu',
'my_custom_submenu_page_content'
);
}
function hide_dashboard_widgets() {
    echo '<style>#dashboard-widgets-wrap { display: none !important; }</style>';
}
add_action('admin_head', 'hide_dashboard_widgets');
.checkbox-lg .custom-control-label::before, 
.checkbox-lg .custom-control-label::after {
  top: .8rem;
  width: 1.55rem;
  height: 1.55rem;
}

.checkbox-lg .custom-control-label {
  padding-top: 13px;
  padding-left: 6px;
}


.checkbox-xl .custom-control-label::before, 
.checkbox-xl .custom-control-label::after {
  top: 1.2rem;
  width: 1.85rem;
  height: 1.85rem;
}

.checkbox-xl .custom-control-label {
  padding-top: 23px;
  padding-left: 10px;
}
    // array to hold list of PDF files to be merged
    $files = array("a.pdf", "b.pdf", "c.pdf");
    $pageCount = 0;
    // initiate FPDI
    $pdf = new FPDI();

    // iterate through the files
    foreach ($files AS $file) {
        // get the page count
        $pageCount = $pdf->setSourceFile($file);
        // iterate through all pages
        for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
            // import a page
            $templateId = $pdf->importPage($pageNo);
            // get the size of the imported page
            $size = $pdf->getTemplateSize($templateId);

            // create a page (landscape or portrait depending on the imported page size)
            if ($size['w'] > $size['h']) {
                $pdf->AddPage('L', array($size['w'], $size['h']));
            } else {
                $pdf->AddPage('P', array($size['w'], $size['h']));
            }

            // use the imported page
            $pdf->useTemplate($templateId);

            $pdf->SetFont('Helvetica');
            $pdf->SetXY(5, 5);
            $pdf->Write(8, 'Generated by FPDI');
        }
    }
<?php 
  function my_scripts_method() {
  wp_enqueue_script(
      'custom-script',
      get_stylesheet_directory_uri() . '/js/unused-javascript.js',
      array( 'jquery' )
   );
  }

  add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
?>
<?php
/**
 * The Template for displaying product archives, including the main shop page which is a post type archive
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/archive-product.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see https://docs.woocommerce.com/document/template-structure/
 * @package WooCommerce\Templates
 * @version 3.4.0
 */

defined( 'ABSPATH' ) || exit;

get_header( 'shop' );

/**
 * Hook: woocommerce_before_main_content.
 *
 * @hooked woocommerce_output_content_wrapper - 10 (outputs opening divs for the content)
 * @hooked woocommerce_breadcrumb - 20
 * @hooked WC_Structured_Data::generate_website_data() - 30
 */
do_action( 'woocommerce_before_main_content' );

?>
<div class="container-fluid">
<header class="woocommerce-products-header">
	<?php if ( apply_filters( 'woocommerce_show_page_title', true ) ) : ?>
		<h1 class="woocommerce-products-header__title page-title"><?php woocommerce_page_title(); ?></h1>
	<?php endif; ?>

	<?php
	/**
	 * Hook: woocommerce_archive_description.
	 *
	 * @hooked woocommerce_taxonomy_archive_description - 10
	 * @hooked woocommerce_product_archive_description - 10
	 */
	do_action( 'woocommerce_archive_description' );
	?>
</header>

<div class="row">
	<div class="col-lg-3">
		<?php
		/**
		 * Hook: woocommerce_sidebar.
		 *
		 * @hooked woocommerce_get_sidebar - 10
		 */
		do_action( 'woocommerce_sidebar' );
		?>
	</div>
	<div class="col-lg-9">


<?php
if ( woocommerce_product_loop() ) {

	/**
	 * Hook: woocommerce_before_shop_loop.
	 *
	 * @hooked woocommerce_output_all_notices - 10
	 * @hooked woocommerce_result_count - 20
	 * @hooked woocommerce_catalog_ordering - 30
	 */
	do_action( 'woocommerce_before_shop_loop' );

	woocommerce_product_loop_start();

	if ( wc_get_loop_prop( 'total' ) ) {
		while ( have_posts() ) {
			the_post();

			/**
			 * Hook: woocommerce_shop_loop.
			 */
			do_action( 'woocommerce_shop_loop' );

			wc_get_template_part( 'content', 'product' );
		}
	}

	woocommerce_product_loop_end();

	/**
	 * Hook: woocommerce_after_shop_loop.
	 *
	 * @hooked woocommerce_pagination - 10
	 */
	do_action( 'woocommerce_after_shop_loop' );
} else {
	/**
	 * Hook: woocommerce_no_products_found.
	 *
	 * @hooked wc_no_products_found - 10
	 */
	do_action( 'woocommerce_no_products_found' );
}

/**
 * Hook: woocommerce_after_main_content.
 *
 * @hooked woocommerce_output_content_wrapper_end - 10 (outputs closing divs for the content)
 */
do_action( 'woocommerce_after_main_content' );

?>
	</div>
</div>
</div>
<?php

get_footer( 'shop' );

?>
function custom_modify_query( $query ) {
    if ( ! is_admin() && $query->is_main_query() ) {
        if ( is_shop() ) {
            $query->set( 'posts_per_page', 12 );
        }
    }
}
add_action( 'pre_get_posts', 'custom_modify_query' );
// Check product has sale
function is_product_on_sale($product_id) {
    $product = wc_get_product($product_id);

    if ($product->is_on_sale()) {
        return true; 
    }

    if ($product->is_type('variable')) {
        $variants = $product->get_children();

        foreach ($variants as $variant_id) {
            $variant = wc_get_product($variant_id);
            if ($variant->is_on_sale()) {
                return true;
            }
        }
    }

    return false;
}
// Check product has sale
function count_sale_products() {
    $transient_key = 'count_sale_products';
    $cached_count = get_transient($transient_key);
    if ($cached_count !== false) {
        return $cached_count;
    } else {
        $products = wc_get_products(['return' => 'ids', 'status' => 'publish', 'limit' => -1, 'type' => array('simple', 'variable', 'bundle', 'external', 'grouped')]);
        $saleProduct = [];
        foreach ($products as $product_id) {
            if (is_product_on_sale($product_id)) {
                $saleProduct[] = $product_id;
            }
        }
        $sale_count = count($saleProduct);
        set_transient($transient_key, $sale_count, 5 * MINUTE_IN_SECONDS);
        return $sale_count;
    }
}
function get_discounted_variants_of_product($product_id) {
    $product = wc_get_product($product_id);

    if ($product->is_type('variable')) {
        $variants = $product->get_children();

        $discounted_variants = array();

        foreach ($variants as $variant_id) {
            $variant = wc_get_product($variant_id);
			//print_r($variant->status); die;
			if( $variant->status == 'publish')
				$discounted_variants[] = array(
					'id' => $variant->get_id(),
					'sale_price' => $variant->get_sale_price(),
					'regular_price' => $variant->get_regular_price(),
					'name' => $variant->get_name(),
					'sku' => $variant->get_sku(),
				);
        }

        return $discounted_variants;
    }
    return false;
}

function getStockStatusCountProduct($instock = true){
	$stock_status = 'instock';
	if(!$instock) $stock_status = 'outofstock';
	$args = array(
		'stock_status' => $stock_status,
		'limit' => -1,
		'status' => 'publish',
		'type' => array('simple', 'variable'),
	);
	$products = wc_get_products( $args );
	return count($products);
}
function customRatingScoreHTML($productID){
	$product = wc_get_product($productID);
	$average      = $product->get_average_rating();
	$rating_whole = floor($average);
	$rating_fraction = $average - $rating_whole;
	$flug = 0;
	for($i = 1; $i <= 5; $i++){
		if( $i <= $rating_whole ){
			echo '<i class="fas fa-star"></i>';
		}
		else{
			if( $rating_fraction > 0 && $flug == 0 ){
				 echo '<i class="fas fa-star-half-alt"></i>';
				$flug = 1;
			}
			else{
				echo '<i class="far fa-star empty"></i>';
			}
		}
	}
}
function customShopGridShortcode($atts=[]){
	ob_start();
	$availability = isset($_GET['availability'])?$_GET['availability']:'instock';
	$category = isset($_GET['category'])?$_GET['category']:'';
	$tag = isset($_GET['tg'])?$_GET['tg']:'';
	//$on_sale = isset($_GET['on_sale'])?$_GET['on_sale']:'';
	$orderBy = isset($_GET['orderby'])?$_GET['orderby']:'';
	$keyword = isset($_GET['s'])?$_GET['s']:'';
	$paged = max(get_query_var('paged'),1);
	$args = [
		'post_type' => ['product'],
		'paged' => $paged,
		'posts_per_page' => 12,
	];
	if(!empty($category) && $category!= 'all')
		$args['tax_query'] = [
			'relation' => 'AND',  
			[
				'taxonomy' => 'product_cat',
				'field' => 'slug',
				'terms' => array( $category ), 
			],
		];
	if(!empty($tag)){
		if(array_key_exists ('tax_query',$args)){
			$args['tax_query'][] = [
				'taxonomy' => 'product_tag',
				'field' => 'slug',
				'terms' => array( $tag ), 
			];
		}
		else{
			$args['tax_query'] = [
				'relation' => 'AND',  
				[
					'taxonomy' => 'product_tag',
					'field' => 'slug',
					'terms' => array( $tag ), 
				],
			];
		}
	}
// 	if(!empty($on_sale) && $on_sale == 1){
		
// 	}
	if(!empty($availability)){
		if($availability == 'sale'){
			$products = wc_get_products( ['return' => 'ids','status' => 'publish','limit' => -1,'type' => array('simple', 'variable', 'bundle','external','grouped')] );
			$saleProduct = [];
			foreach($products as $vv){
				if(is_product_on_sale($vv)){
					$saleProduct[] = $vv;
				}
			}
			if(!empty($saleProduct))
				$args['post__in'] = $saleProduct;
			else
				$args['post__in'] = [0];
			
// 			if(array_key_exists('tax_query',$args)){
// 				$args['tax_query'][] = [
// 					 'key' => '_sale_price',
// 					 'value' => '',
// 					 'compare' => '!='
// 				];
// 			}
// 			else{
// 				$args['tax_query'] = [
// 					'relation' => 'AND',  
// 					[
// 						'key' => '_sale_price',
//                 		'value' => '',
//                 		'compare' => '!='
// 					],
// 				];
// 			}
		}
		else{
			$products = wc_get_products( ['stock_status' => $availability,'return' => 'ids','status' => 'publish','limit' => -1,'type' => array('simple', 'variable', 'bundle','external','grouped')] );
			if(!empty($products))
				$args['post__in'] = $products;
			else
				$args['post__in'] = [0];
		}
		
		//print_r($products);
		
	}
	if(!empty($orderBy)){
		if($orderBy == 'popularity'){
			$args['meta_key'] = 'total_sales';
			$args['orderby'] = 'meta_value_num';
			$args['order'] = 'DESC';
		}
		if($orderBy == 'rating'){
			$args['meta_key'] = '_wc_average_rating';
			$args['orderby'] = 'meta_value_num';
			$args['order'] = 'DESC';
		}
		if($orderBy == 'date'){
			$args['orderby'] = 'date';
			$args['order'] = 'DESC';
		}
		if($orderBy == 'price'){
			$args['meta_key'] = '_price';
			$args['orderby'] = 'meta_value_num';
			$args['order'] = 'ASC';
		}
		if($orderBy == 'price-desc'){
			$args['meta_key'] = '_price';
			$args['orderby'] = 'meta_value_num';
			$args['order'] = 'DESC';
		}
	}
	if(!empty($keyword)){
		$args['s'] = $keyword;
	}
	if(isset($_GET['dev']))
		print_r($args);
	$the_query = new WP_Query( $args );
?>

<div class="customShopGrid-wrap">
	<form id="frmFilterProduct" method="GET" action="">
		<div class="frmFilterProduct-ajax">
			<?php 
				$sort_arr = [
						'menu_order' => __('Default Sorting'),	
						'popularity' => __('Best Selling'),
						'rating' => __('Average Rating'),
						'date' => __('Latest Product'),
						'price' => __('Price Low To High'),
						'price-desc' => __('Price High To Low'),
				];
			?>
			<div class="customShopGrid-order-wrap">
				<div class="customShopGrid-order orderbyPC">
					<span>Sort By:</span>
					<select id="orderby" class="slOrder" name="orderby">
						<?php foreach($sort_arr as $key => $value):?>
						<option value="<?php echo $key; ?>" <?php if($orderBy == $key) echo 'selected'?>><?php echo $value; ?></option>
						<?php endforeach; ?>
					</select>
				</div>
			</div>
	<div class="customShopGrid">
		
		<div class="customShopGrid-left">
			<div class="customShopGrid-filter">
				<div class="customShopGrid-filter-top customShopGrid-filter-space">
					<h2 class="customShopGrid-filter-heading">Filter Products</h2>
					<img src="https://vancitylabs.co/wp-content/uploads/2024/04/setting-ic.svg" />
				</div>
				<div class="customShopGrid-filter-list">
					
					<div class="customShopGrid-filter-group">
						<div class="customShopGrid-filter-group-head customShopGrid-filter-space">
							<h3 class="customShopGrid-filter-heading">Availability</h3>
						</div>
						<div class="customShopGrid-filter-group-content">
							<ul>
								<li>
									<label class="custom-checkbox">
										<input id="Availability-instock" class="filter-checkbox" type="checkbox" name="availability" value="instock" <?php if($availability == 'instock') echo 'checked' ?> />
										<span style='font-size: 18px'>In Stock (<?php echo getStockStatusCountProduct()?>)</span>
									</label>
								</li>
								<li>
									<label class="custom-checkbox">
										<input id="Availability-outstock" class="filter-checkbox" type="checkbox" name="availability" value="outofstock" <?php if($availability == 'outofstock') echo 'checked' ?> />
										<span style='font-size: 18px'>Out of Stock (<?php echo getStockStatusCountProduct(false)?>)</span>
									</label>
								</li>
								<li>
									<label class="custom-checkbox">
										<input id="Availability-outstock" class="filter-checkbox" type="checkbox" name="availability" value="sale" <?php if($availability == 'sale') echo 'checked' ?> />
										<span style='font-size: 18px'>On Sale (<?php echo count_sale_products();?>)</span>
									</label>
								</li>
							</ul>
						</div>
					</div>
					<!--end group-->
					<?php  
						$cats = get_terms([
							'taxonomy' => 'product_cat',
							'hide_empty' => true,
							'parent'   => 0,
						]);
						if(!empty($cats)):
					?>
					<div class="customShopGrid-filter-group">
						<div class="customShopGrid-filter-group-head customShopGrid-filter-space">
							<h3 class="customShopGrid-filter-heading">Categories</h3>
						</div>
						<div class="customShopGrid-filter-group-content">
							<ul>
								<li>
									<label class="custom-checkbox">	
										<input class="filter-checkbox" type="checkbox" name="category" value="all" <?php if($category == 'all') echo 'checked' ?> />
										<span style='font-size: 18px'>All</span>
									</label>
								</li>
								<?php 
									foreach ($cats as $key => $value): 
									$childs = get_term_children( $value->term_id, 'product_cat' );
									$isChildOpen = false;
									if(!empty($childs)): 
										foreach($childs as $child):
											$child = get_term_by('id',$child,'product_cat');
											
											//print_r($category);
											if($category == $child->slug){
												$isChildOpen =  true;
												break;
											}
										endforeach;
									endif;
									
								?>
									<li class="<?php if(!empty($childs)) echo 'has-child'; ?>">
										<?php if(!empty($childs)):?>
											<div class="custom-checkbox">
										<?php else: ?>	
											<label class="custom-checkbox">	
										<?php endif;?>	
											<input class="filter-checkbox" type="checkbox" name="category" value="<?php echo $value->slug ?>" <?php if($category == $value->slug) echo 'checked' ?> />
												
											<span style='font-size: 18px'><?php echo $value->name ?> (<?php echo $value->count ?>)</span>
										<?php if(!empty($childs)):?>
											</div>
										<?php else: ?>
											</label>
										<?php endif;?>			
										<?php if(!empty($childs)): ?>
										<ul class="customShopGrid-filter-group-content-child" style="<?php if(!$isChildOpen) echo 'display: none;'?>">
											<?php foreach($childs as $child): $child = get_term_by('id',$child,'product_cat'); if($child->count > 0): ?>
												<li>
													<label class="custom-checkbox">
														<input class="filter-checkbox" type="checkbox" name="category" value="<?php echo $child->slug ?>" <?php if($category == $child->slug) echo 'checked' ?> />
														<span style='font-size: 18px'><?php echo $child->name;  ?> (<?php echo $child->count ?>)</span>
													</label>
												</li>
											<?php endif; endforeach ?>
										</ul>
										<?php endif;?>
									</li>
								<?php endforeach ?>
							</ul>
						</div>
					</div>
					<!--end group-->
					<?php endif; ?>
					
					<div class="customShopGrid-filter-reset">
						<a class="customShopGrid-filter-reset-button" href="<?php echo get_permalink( wc_get_page_id( 'shop' ) )?>">Reset Filters</a>
					</div>
				</div>
			</div>
		</div>
		<div class="customShopGrid-right">
			<div class="customShopGrid-order show-mb-flex" hidden>
				<h3 class="customShopGrid-filter-heading">Sort by:</h3>
				<div class="orderbyMB">
				</div>
			</div>
			<!--end group-->
			<?php if ( !empty($keyword) ) :?>
				<p class="customShopGrid-seach-keyword-label">Search results for <span>"<?php echo $keyword; ?>"</span> <a href="https://vancitylabs.co/shop/">Remove</a></p>
			<?php endif; ?>
			<div class="customShopGrid-list">
				
				<?php if ( $the_query->have_posts() ) :?>
				<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
				<div class="customShopGrid-product">
					<div class="customShopGrid-product-inner">
					   <div class="customShopGrid-product-image-wrap">
						   <?php 
						   		$product = wc_get_product(get_the_ID());
								$product_type = $product->get_type();
								if(!$product->is_in_stock()):
						   ?>
						  		<span class="customShopGrid-product-stockout customShopGrid-product-label">Out of stock</span>  
						   <?php endif; ?>
						   <?php if(is_product_on_sale(get_the_ID())):?>
						   		<span class="customShopGrid-product-has-sale customShopGrid-product-label">Sale</span>  
						   <?php endif; ?>
						  <div class="customShopGrid-product-image">
							 <a href="<?php the_permalink();?>" tabindex="0"> 
							 	<?php the_post_thumbnail('medium')?>
							 </a>
						  </div>
					   </div>
					   <div class="customShopGrid-product-content">
						  <div class="customShopGrid-product-content-inner">
							  <div class="customShopGrid-product-ratting-wrap">
								<div class="top-rated-rating">
									<?php 
							   			$types = get_the_terms(get_the_ID(),'product-type');
										$type = '';
										if(!empty($types)) $type = reset($types);
										if(is_object($type)):
											$color = get_field('color',$type);
									?>
								   <span class="customShopGrid-product-type" style="<?php if($color) echo 'background:'.$color;?>"><?php echo $type->name;?></span>
									<?php endif; ?>
								   <span class="customShopGrid-product-ratting">
								   		<span class="customShopGrid-product-user-ratting">
								   			<?php customRatingScoreHTML(get_the_ID());?>              
									   </span>
									   <span class="customShopGrid-product-user-ratting-count" hidden>(<?php echo $product->get_rating_count(); ?>)</span>
									</span>
									<?php 
										$thc = get_field('thc');
										if($thc > 0):
									?>
									<span class="customShopGrid-product-thc"><b>THC</b> <?php echo $thc.'%'?></span>
									<?php endif; ?>
								</div>
							 </div>
							 <h4 class="customShopGrid-product-title"><a href="<?php the_permalink();?>" tabindex="0"><?php the_title();?></a></h4>
							 
							 <?php 
								$add_to_card_id = get_the_ID();
							  	$discounted_variants = get_discounted_variants_of_product(get_the_ID());
								if($discounted_variants):
									$add_to_card_id = $discounted_variants[0]['id'];
							 ?>
							  <select class="customShopGrid-product-list-variable">
							  	<?php 
										foreach($discounted_variants as $key => $value):
											//print_r($value);
											$variable_price = ($value['sale_price']> 0)?$value['sale_price'] : $value['regular_price'];
											$name_parts = explode(' - ', $value['name']);
											//$variable_price = 0;
								?>
								  <option value="<?php echo $value['id']?>" <?php if(strtolower(end($name_parts)) == '28g'){$add_to_card_id = $value['id']; echo 'selected';}?>><?php echo end($name_parts);?> - $<?php echo $variable_price;?></option>
								<?php endforeach;?>
							  </select>
							  <?php else: ?>
							  <div class="customShopGrid-product-price">
								  <?php woocommerce_template_loop_price();?>
							  </div>
							  <?php endif;?>
							  <div class="wrap-btn">
								  <?php if($product_type !== 'bundle'):?>
								 	<a class="pb-btn-style add_to_cart_button ajax_add_to_cart" href="<?php site_url();?>?add-to-cart=<?php echo $add_to_card_id;?>&quantity=1" data-quantity="1" data-product_id="<?php echo $add_to_card_id;?>"><span>Add to cart</span> <img src="https://vancitylabs.co/wp-content/uploads/2024/04/right-arrow.svg" /></a>
								  <?php else: ?>
								  	<a class="pb-btn-style" href="<?php the_permalink(); ?>"><span>Buy Now</span> <img src="https://vancitylabs.co/wp-content/uploads/2024/04/right-arrow.svg" /></a>
								  <?php endif;?>
							  </div>
						  </div>
					   </div>
					</div>
				</div>
				<?php endwhile;?>
				<?php else: ?>
					<p>No product found!</p>
				<?php endif;wp_reset_postdata();?>
				
			</div>
			<?php if($the_query->max_num_pages > 1):?>
			<div class="customShopGrid-pagenavi">
				<?php echo paginate_links(array(
					'total'   => $the_query->max_num_pages,
					'current' => $paged,
					'prev_text' => '<img src="'.CHILD_THEME_URI.'/images/prev-arrow-green.svg" />',
					'next_text' => '<img src="'.CHILD_THEME_URI.'/images/next-arrow-green.svg" />'
				));?>
			</div>
			<?php endif;?>
		</div>
	</div>
	</div>
	</form>
	<script type="text/javascript">
		(function($){
			var sortDiv = $('body').find('#orderby');
			//var spinner = $('')
			$('body').on('change','.filter-checkbox',function(){
				$(this).parents('li').siblings().find('.filter-checkbox').prop('checked', false)
				$('#frmFilterProduct').submit();
			})
			$('body').on('click','.customShopGrid-filter-group-head',function(e){
				$(this).toggleClass('close')
				$(this).parent().find('.customShopGrid-filter-group-content').slideToggle();
			})
			$('body').on('change','.slOrder',function(){
				$('#frmFilterProduct').submit();
			})
			$('body').on('click','.customShopGrid-filter-top',function(e){
				$(this).toggleClass('close')
				$(this).parent().find('.customShopGrid-filter-list').slideToggle();
			})
			$('body').on('click','li.has-child .custom-checkbox',function(e){
				var $div = $(this);
				var divOffset = $div.offset();
				var clickX = e.pageX - divOffset.left;
				if (clickX <= 28) {
					$(this).parents('ul').find('.filter-checkbox').prop('checked', false);
					$(this).find('.filter-checkbox').prop('checked', true)
					$('#frmFilterProduct').submit();
				}
				else{
					$(this).parent().find('.customShopGrid-filter-group-content-child').slideToggle();
				}
			})
			function moveSortDiv(){
				if($(window).innerWidth() < 768){
					if(!$('.orderbyMB .slOrder').length)
						sortDiv.appendTo('.orderbyMB');
				}
				else{
					if(!$('.orderbyPC .slOrder').length)
						sortDiv.appendTo('.orderbyPC');
				}
			}
			moveSortDiv();
			$(window).on('resize',function(){
				moveSortDiv();
			})
			function customAjaxSend(form,fullUrl){
				history.pushState({}, '', fullUrl);
				$.ajax({
					url: fullUrl,
					method: form.attr('method'),
					data: form.serialize(),
					dataType: 'html',
					beforeSend: function () {
						$('.customShopGrid-list').html(`<div class="cspinner">
				<div class="loadingio-spinner" style="/* display: none; */">
					<div class="loadingio-spinner-spinner-gakt1tin5n">
						<div class="ldio-7ufvexzivn">
							<div></div>
							<div></div>
							<div></div>
							<div></div>
							<div></div>
							<div></div>
							<div></div>
							<div></div>
							<div></div>
							<div></div>
							<div></div>
							<div></div>
						</div>
					</div>
				</div>
			</div>`);
						$('.cspinner .loadingio-spinner').show();
						$('.customShopGrid-pagenavi').css('display','none');
					},
					success: function(response) {
						 	const html = $(response);
							const items = html.find('.frmFilterProduct-ajax');
							$('#frmFilterProduct').html(items);
							$('.cspinner .loadingio-spinner').hide();
							$('.customShopGrid-pagenavi').css('display','flex');
// 							if (items.length) {
// 								$('.project-box').html(items);
// 							} else {
// 								$('.project-box').html('<p>Aucun résultat trouvé</p>');
// 							}
							//console.log(response);
							moveSortDiv();
					},
					error: function(jqXHR, textStatus, errorThrown) {
						console.log('Error submitting form');
						console.log(textStatus, errorThrown);
					}
				});
			}
			$('#frmFilterProduct').on('submit', function(e) {
				e.preventDefault(); 
				var form = $(this); 
				var url = form.attr('action'); 
				var fullUrl = url + '?' + form.serialize();
				history.pushState({}, '', fullUrl);
				let currentUrl = window.location.href;
				let newUrl = currentUrl.replace(/page\/\d+\//, '');
				customAjaxSend(form, newUrl);
			});
			$('body').on('click','.customShopGrid-pagenavi a',function(e){
				e.preventDefault();
				var form = $('#frmFilterProduct'); 
				var fullUrl = $(this).attr('href');
				$('html, body').animate({
					scrollTop: $(".customShopGrid-right").offset().top - 300
				}, 1000); // 1000 milliseconds for the scroll animation
				customAjaxSend(form, fullUrl);
// 				setTimeout(function() {
					
// 				}, 200); // 1000 milliseconds delay before starting the scroll
				
			})
		})(jQuery)
	</script>
</div>
<?php	return ob_get_clean();
}
add_shortcode('customShopGrid','customShopGridShortcode');
$current_user = wp_get_current_user();
$analytics_link = get_field('analytics_link', 'user_' . $current_user->ID);
function custom_external_add_to_cart_button($button, $product) {
    // Check if the product is of type 'external'
    if ($product->is_type('external')) {
        // Direct URL to the Amazon icon image
        $icon_url = 'https://mejormovil.es/wp-content/themes/woodmart/images/amazon-icon.png';
        // Define the button text
        $button_text = 'See Prices';

        // Create the button HTML with the Amazon icon and new text
        $button = sprintf(
            '<a href="%s" class="button product_type_external add-to-cart-loop customize-unpreviewable" data-product_id="%s" aria-label="%s" rel="nofollow">
                <img src="%s" style="width: 20px; height: auto; margin-right: 5px; vertical-align: middle;" alt="Amazon Icon"/> %s
            </a>',
            esc_url($product->add_to_cart_url()), // URL for the product
            esc_attr($product->get_id()), // Product ID
            esc_attr($product->add_to_cart_description()), // ARIA label
            esc_url($icon_url), // Amazon icon URL
            esc_html($button_text) // Button text
        );
    }
    // Return the modified button HTML
    return $button;
}
// Apply the filter to modify the external product button
add_filter('woocommerce_loop_add_to_cart_link', 'custom_external_add_to_cart_button', 10, 2);
/**
 * @snippet       Remove Zoom, Gallery @ Single Product Page
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @testedwith    WooCommerce 5
 * @community     https://businessbloomer.com/club/
 */
  
//add_action( 'wp', 'bbloomer_remove_zoom_lightbox_theme_support', 99 );
  
function bbloomer_remove_zoom_lightbox_theme_support() { 
    //remove_theme_support( 'wc-product-gallery-zoom' );
    //remove_theme_support( 'wc-product-gallery-lightbox' );
    remove_theme_support( 'wc-product-gallery-slider' );
}

////Remove actions for single product
remove_action('woocommerce_before_main_content','woocommerce_breadcrumb',20);
remove_action('woocommerce_single_product_summary','woocommerce_template_single_meta',40);
remove_action('woocommerce_single_product_summary','woocommerce_template_single_excerpt',20);
remove_action('woocommerce_after_single_product_summary','woocommerce_output_product_data_tabs',10);
remove_action('woocommerce_after_single_product_summary','woocommerce_upsell_display',15);
remove_action('woocommerce_after_single_product_summary','woocommerce_output_related_products',20);
//Add actions for single product
add_action('woocommerce_single_product_summary','woocommerce_template_single_excerpt',35);

function addTHCForSingleProduct(){
	$thc = get_field('thc');
	if(!empty($thc)) echo '<h4 class="single-product-thc">'.$thc.'</h4>';
}
add_action('woocommerce_single_product_summary','addTHCForSingleProduct',6);
function customTabForSingleProduct(){
?>
<div class="rst-accordion-description">
	<?php if($ingredient = get_field('ingredient_field_name')):?>
	<div class="rst-item-accordion-description">
		<h3 class="rst-heading-item-accordion-description rst-heading-item-toggle">
			Ingredients
			<span>
				<img src="https://sweedies.co/wp-content/uploads/2024/05/arrows-down.png" />
			</span>
		</h3>
		<div class="rst-content-item-accordion-description">
			<?php echo $ingredient; ?>
		</div>
	</div>
	<?php endif;?>
	<?php  $lab_test_report = get_field('lab_test_report');if(!empty($lab_test_report)):?>
	<div class="rst-item-accordion-description">
		<a class="rst-heading-item-accordion-description" href="<?php echo $lab_test_report['url']; ?>" download>
			Lab test report
			<span>
				<img src="https://sweedies.co/wp-content/uploads/2024/05/PDF-Print-Icon.png" />
			</span>
		</a>
	</div>
	<?php endif;?>
</div>
<script>
	(function($){
		$('.rst-heading-item-toggle').click(function(){
			if($(this).hasClass('active')){
				$(this).parent().find('.rst-content-item-accordion-description').slideUp();
				$(this).removeClass('active');
			}else{
				$('.rst-content-item-accordion-description').slideUp();
				$(this).parent().find('.rst-content-item-accordion-description').slideDown();
				$('.rst-heading-item-toggle').removeClass('active');
				$(this).addClass('active');
			}
			return false;
		});
	})(jQuery)
</script>
<?php
}
add_action('woocommerce_single_product_summary','customTabForSingleProduct',45);

function customBestSellerForShop(){
?>
<?php 
	$args = [
		'post_type' => 'product',
		'posts_per_page' => 15,
		'meta_key' => 'total_sales',
		'orderby' => 'meta_value_num',
		'order' => 'DESC',
	];
	$the_query = new WP_Query($args);
	if($the_query->have_posts()):
?>
<div class="customBestSellerForSingleProduct" style="clear: both;">
	<div class="customBestSellerForSingleProduct-head">
		<h2 class="nt-heading">
			Best Sellers
		</h2>
	</div>
	<div class="customBestSellerForSingleProduct-list">
		<div class="slider-product custom-slider-product-bestSellers">
			<div class="swiper-wrapper">
				<?php
                while ($the_query->have_posts()):
                    $the_query->the_post();
                    $product = wc_get_product(get_the_ID());
                    $categories = wp_get_post_terms(get_the_ID(), 'product_cat');
                    $category_name = !empty($categories) ? $categories[0]->name : '';
                    $rating_count = $product->get_rating_count();
                    $average = $product->get_average_rating();
                    $regular_price = $product->get_regular_price();
                    $sale_price = $product->get_sale_price();
                    ?>

                    <div class="swiper-slide">
                        <div class="slider-product-item">
                            <a class="product-link" href="<?php the_permalink(); ?>">
                                <div class="slider-product-image">
                                    <?php echo woocommerce_get_product_thumbnail('shop_catalog'); ?>

                                    <div class="add-to-cart-btn">
                                        <?php //echo $this->get_add_to_cart_button(get_the_ID()); ?>
                                    </div>
                                </div>
                            </a>
                            <div class="slider-product-details">
                                <div class="product-category"><?php echo esc_html($category_name); ?></div>
								<a href="<?php the_permalink(); ?>">
									<h2 class="slider-product-title">
										<?php the_title(); ?>
									</h2>
								</a>
                                <div class="slider-product-description"><?php echo wp_trim_words(get_the_excerpt(), 15); ?></div>
								<div class="product-rating">
									<?php
									$rating = $average; 
									$full_stars = floor($rating);
									$half_star = ($rating - $full_stars >= 0.5) ? 1 : 0;
									$empty_stars = 5 - $full_stars - $half_star;

									
									for ($i = 0; $i < $full_stars; $i++) {
										echo '<i class="fa-solid fa-star"></i>';
									}

									
									if ($half_star) {
										echo '<i class="fa-solid fa-star-half-alt"></i>';
									}

									
									for ($i = 0; $i < $empty_stars; $i++) {
										echo '<i class="fa-regular fa-star"></i>';
									}
									?>
									<span class="rating-count">(<?php echo $rating_count; ?>)</span>
								</div>
								<div class="slider-product-prices">
                                    <?php if ($sale_price): ?>
                                        <span class="slider-product-new-price"><?php echo wc_price($sale_price); ?></span>
                                        <span class="slider-product-old-price"><?php echo wc_price($regular_price); ?></span>
                                    <?php else: ?>
                                        <span class="slider-product-new-price"><?php echo wc_price($regular_price); ?></span>
                                    <?php endif; ?>
                                </div>
                                
                            </div>
                        </div>
                    </div>

                <?php endwhile; ?>
			</div>
			<div class="swiper-pagination"></div>
		</div>
		<div class="swiper-button-prev"></div>
        <div class="swiper-button-next"></div>
	</div>
</div>
<script>
	jQuery(document).ready(function ($) {

		var swiper_bestSellers = new Swiper(".custom-slider-product-bestSellers", {
			slidesPerView: 3,
			slidesPerGroup: 1,
			centeredSlides: true,
			loop: true,
			autoplay: {
				delay: 5000,
			},
			spaceBetween: 24,
// 			pagination: {
// 				el: ".swiper-pagination",
// 				clickable: true,
// 			},
			navigation: {
				nextEl: '.swiper-button-next',
				prevEl: '.swiper-button-prev',
			},
			breakpoints: {
				1025: {
					slidesPerView: 3,
					centeredSlides: true,
				},
				768: {
					slidesPerView: 2,
					centeredSlides: true,
				},
				320: {
					slidesPerView: 1.5,
					centeredSlides: true,
				},
			}
		});


	});

	jQuery(document).ready(function($) {
		$('.slider-product .slider-product-item ').matchHeight();
	});


</script>
<?php
	endif; wp_reset_postdata();
}
add_action('woocommerce_after_single_product','customBestSellerForSingleProduct',25);

function customReviewForSingleProduct(){
?>
<div class="customReviewForSingleProduct">
	<div class="customReviewForSingleProduct-head">
		<h2 class="nt-heading">
			Customer reviews
		</h2>
	</div>
	<div class="customReviewForSingleProduct-content">
		<?php echo do_shortcode('[Woo_stamped_io type="widget"]');?>
	</div>
</div>
<?php	
}
add_action('woocommerce_after_single_product','customBestSellerForShop',30);
$file = fopen('myCSVFile.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
  //$line is an array of the csv elements
  print_r($line);
}
fclose($file);
\Drupal::service('file_system')->realpath(file_default_scheme() . '://');
$app = requir_once __DIR__.'/../bootstrap/app.php';
$app = require_once __DIR__.'/../bootstrap/app.php';
public function exportUserSummary($workflow_id, Request $request)
{
$isValid = self::handleValidateUrl($workflow_id);
if ($isValid !== true) {
return $isValid;
}
$search_start_date = $request->start_date;
$search_end_date = $request->end_date;
$search_limit = $request->limit ?: 100;
$search_page = $request->page ?: 1;

$search_offset = ($search_page - 1) * $search_limit;

// Fetch user list

$rawList = SasageHelper::$companyObj->fetch_users($search_limit, $search_offset);
$userList = collect($rawList)->map(function ($obj) {
return collect($obj)->except(SasageHelper::$userHiddenProps);
});

// Fetch tracking data for all users
$trackingObj = new \Sasage\Tracking(SasageHelper::$sasageAuthentication);

$types = ['shoot', 'measure', 'data_input', 'confirm', 'sasage'];
$trackingList = [];
$fetchFailed = false;

foreach ($types as $type) {
$tempTrackingList = [];
$results = $trackingObj->fetch_user_daily_tracking($workflow_id, $type, $search_start_date, $search_end_date, -1, -1);
if (isset($results['errors'])) {
$fetchFailed = true;
break;
}
$tempTrackingList = array_merge($tempTrackingList, $results);
$trackingList = array_merge($trackingList, $tempTrackingList);
}
if ($fetchFailed) {
// Fetch failed
return response()->json([
'message' => 'Failed to fetch tracking.',
], 500);
}

// Init user summary props
foreach ($userList as $userIndex => $user) {
foreach ($types as $type) {
$user[$type . '_duration'] = 0;
$user[$type . '_total'] = 0;
$userList[$userIndex] = $user;
}
}

// Mapping all data in tracking list to user by user.id and tracking.created_by
foreach ($trackingList as $tracking) {
foreach ($userList as $userIndex => $user) {
if ($user['id'] === $tracking['created_by']) {
$user[$tracking['type'] . '_duration'] = $tracking['duration'];
$user[$tracking['type'] . '_total'] = count($tracking['product_ids']);
$userList[$userIndex] = $user;
}
}
}

// Create CSV file
$filename = "user_summary_{$workflow_id}_" . date('Ymd_His') . ".csv";
$handle = fopen($filename, 'w');
$header = [
'username',
'averageDuration',
'averageShootDuration',
'averageMeasureDuration',
'averageDataInputDuration',
'averageConfirmDuration'
];
fputcsv($handle, $header);

foreach ($userList as $user) {
fputcsv($handle, [
$user['username'],
$user['sasage_duration'],
$user['shoot_duration'],
$user['measure_duration'],
$user['data_input_duration'],
$user['confirm_duration'],
]);
}

fclose($handle);

return response()->download($filename);
}
<div class="team-content">
                                <?php
                                    $content = apply_filters( 'the_content', get_the_content() );
                                    $first_paragraph = substr($content, 0, strpos($content, "</p>"));
                                    echo $first_paragraph;

                                    // check if $content has more than one paragrah and if it does get content after first </p>
                                    if (substr_count($content, '<p>') > 1) {
                                        $remaining_paragraphs = substr($content, strpos($content, "</p>") + 4); ?>
                                        <div class="more-content" style="display: none;">
                                        <?php echo $remaining_paragraphs; ?>
                                        </div>
                                        <div class="learn-more-toggle"><button class="learn-more" id="learnmore">Learn More</button></div>
                                        <script>
                                            jQuery(document).ready(function($){
                                                $('#learnmore').click(function(){
                                                    $('.more-content').toggleClass('show');
                                                    $(this).text() == 'Learn More' ? $(this).text('Show Less') : $(this).text('Learn More');
                                                });
                                            });
                                        </script>
                                    <?php } ?>
                            </div>
php artisan make:controller SiteController
 if ($_FILES['file']['size'] == 0) {
          //se não existir a imagem coloa uma padrão
          $file = "assets/upload/adverts/no-photo.jpg";
        } else {

          $file = $Resources->uploadFile('assets/upload/images/adverts/', $_FILES['file']);
          if ($file == "error") {
            header("Location: " . BASE_URL . "users/advertise");
            exit;
          }
        }
heroku-php-nginx -C nginx.conf web/
from openai import OpenAI 
import os

MODEL="gpt-4o"
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))

# 1 - Basic Chat

completion = client.chat.completions.create(
  model=MODEL,
  messages=[
    {"role": "system", "content": "You are a helpful assistant. Help me with my math homework!"},
    {"role": "user", "content": "Hello! Could you solve 2+2?"}
  ]
)

print("Assistant: " + completion.choices[0].message.content)

# 2 - Image Processing: Base64
import base64

IMAGE_PATH = "triangle.png"

def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")

base64_image = encode_image(IMAGE_PATH)

response = client.chat.completions.create(
    model=MODEL,
    messages=[
        {"role": "system", "content": "You are a helpful assistant that responds in Markdown. Help me with my math homework!"},
        {"role": "user", "content": [
            {"type": "text", "text": "What's the area of the triangle?"},
            {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{base64_image}"}
            }
        ]}
    ],
    temperature=0.0,
)

print(response.choices[0].message.content)

# 3 - Image Processing: URL
response = client.chat.completions.create(
    model=MODEL,
    messages=[
        {"role": "system", "content": "You are a helpful assistant that responds in Markdown. Help me with my math homework!"},
        {"role": "user", "content": [
            {"type": "text", "text": "What's the area of the triangle?"},
            {"type": "image_url", "image_url": {"url": "https://upload.wikimedia.org/wikipedia/commons/e/e2/The_Algebra_of_Mohammed_Ben_Musa_-_page_82b.png"}
            }
        ]}
    ],
    temperature=0.0,
)

print(response.choices[0].message.content)

# 4 - Summarization: Video Summary
import cv2
from moviepy.editor import VideoFileClip
import time
import base64

VIDEO_PATH = "keynote_recap.mp4"

def process_video(video_path, seconds_per_frame=2):
    base64Frames = []
    base_video_path, _ = os.path.splitext(video_path)

    video = cv2.VideoCapture(video_path)
    total_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
    fps = video.get(cv2.CAP_PROP_FPS)
    frames_to_skip = int(fps * seconds_per_frame)
    curr_frame=0

    while curr_frame < total_frames - 1:
        video.set(cv2.CAP_PROP_POS_FRAMES, curr_frame)
        success, frame = video.read()
        if not success:
            break
        _, buffer = cv2.imencode(".jpg", frame)
        base64Frames.append(base64.b64encode(buffer).decode("utf-8"))
        curr_frame += frames_to_skip
    video.release()

    audio_path = f"{base_video_path}.mp3"
    clip = VideoFileClip(video_path)
    clip.audio.write_audiofile(audio_path, bitrate="32k")
    clip.audio.close()
    clip.close()

    print(f"Extracted {len(base64Frames)} frames")
    print(f"Extracted audio to {audio_path}")
    return base64Frames, audio_path

base64Frames, audio_path = process_video(VIDEO_PATH, seconds_per_frame=1)

response = client.chat.completions.create(
    model=MODEL,
    messages=[
    {"role": "system", "content": "You are generating a video summary. Please provide a summary of the video. Respond in Markdown."},
    {"role": "user", "content": [
        "These are the frames from the video.",
        *map(lambda x: {"type": "image_url", 
                        "image_url": {"url": f'data:image/jpg;base64,{x}', "detail": "low"}}, base64Frames)
        ],
    }
    ],
    temperature=0,
)
print(response.choices[0].message.content)

# 5 - Summarization: Audio Summary
transcription = client.audio.transcriptions.create(
    model="whisper-1",
    file=open(audio_path, "rb"),
)

response = client.chat.completions.create(
    model=MODEL,
    messages=[
    {"role": "system", "content":"""You are generating a transcript summary. Create a summary of the provided transcription. Respond in Markdown."""},
    {"role": "user", "content": [
        {"type": "text", "text": f"The audio transcription is: {transcription.text}"}
        ],
    }
    ],
    temperature=0,
)
print(response.choices[0].message.content)

# 6 - Summarization: Audio + Visual Summary
response = client.chat.completions.create(
    model=MODEL,
    messages=[
    {"role": "system", "content":"""You are generating a video summary. Create a summary of the provided video and its transcript. Respond in Markdown"""},
    {"role": "user", "content": [
        "These are the frames from the video.",
        *map(lambda x: {"type": "image_url", 
                        "image_url": {"url": f'data:image/jpg;base64,{x}', "detail": "low"}}, base64Frames),
                        {"type": "text", "text": f"The audio transcription is: {transcription.text}"}
        ],
    }
],
    temperature=0,
)
print(response.choices[0].message.content)

# 7 - Q&A: Visual Q&A
QUESTION = "Question: Why did Sam Altman have an example about raising windows and turning the radio on?"

qa_visual_response = client.chat.completions.create(
    model=MODEL,
    messages=[
    {"role": "system", "content": "Use the video to answer the provided question. Respond in Markdown."},
    {"role": "user", "content": [
        "These are the frames from the video.",
        *map(lambda x: {"type": "image_url", "image_url": {"url": f'data:image/jpg;base64,{x}', "detail": "low"}}, base64Frames),
        QUESTION
        ],
    }
    ],
    temperature=0,
)
print("Visual QA:\n" + qa_visual_response.choices[0].message.content)

# 8 - Q&A: Audio Q&A
qa_audio_response = client.chat.completions.create(
    model=MODEL,
    messages=[
    {"role": "system", "content":"""Use the transcription to answer the provided question. Respond in Markdown."""},
    {"role": "user", "content": f"The audio transcription is: {transcription.text}. \n\n {QUESTION}"},
    ],
    temperature=0,
)
print("Audio QA:\n" + qa_audio_response.choices[0].message.content)

# 11 - Q&A: Visual + Audio Q&A
qa_both_response = client.chat.completions.create(
    model=MODEL,
    messages=[
    {"role": "system", "content":"""Use the video and transcription to answer the provided question."""},
    {"role": "user", "content": [
        "These are the frames from the video.",
        *map(lambda x: {"type": "image_url", 
                        "image_url": {"url": f'data:image/jpg;base64,{x}', "detail": "low"}}, base64Frames),
                        {"type": "text", "text": f"The audio transcription is: {transcription.text}"},
        QUESTION
        ],
    }
    ],
    temperature=0,
)
print("Both QA:\n" + qa_both_response.choices[0].message.content)
function year_shortcode() {
  $year = date('Y');
  return $year;
}
add_shortcode('year', 'year_shortcode');
$profile = '<p>イリノイ州シカゴにて、アイルランド系の家庭に、9</p>';
$dom = new DOMDocument();

// This version preserves the original characters
$contentType = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8">';
$dom->loadHTML($contentType . $profile);
echo $dom->saveHTML();

// This version will HTML-encode high-ASCII bytes
$dom->loadHTML('<meta charset="utf8">' . $profile);
echo $dom->saveHTML();

// This version will also HTML-encode high-ASCII bytes,
// and won't work for LIBXML_DOTTED_VERSION >= 2.12.0
$dom->loadHTML('<?xml encoding="utf-8" ?>' . $profile);
echo $dom->saveHTML();
<?php echo do_shortcode('[gravityform id="1" title="false" ajax="true"]') ?>
<div class="related-post">
  <div class="container">
    <h2 id="recent">Related Articles</h2>
    <div class="row">
      <?php
      $current_post_type = get_post_type($post);
      // The query arguments
      $args = array(
        'posts_per_page' => 3,
        'order' => 'rand',
        'orderby' => 'ID',
        'post_type' => 'post',
        'post_status' => 'publish',
        'numberposts' => -1,
        'post__not_in' => array($post->ID)
      );

      // Create the related query
      $rel_query = new WP_Query($args);

      // Check if there is any related posts
      if ($rel_query->have_posts()):
        ?>


        <?php
        // The Loop
        while ($rel_query->have_posts()):
          $rel_query->the_post();
          $post_tags = get_the_tags();
          ?>
          <div class="col-md-4 col-sm-6 col-12 related-col">

            <?php the_post_thumbnail(); ?>
            <div class="taxonomy-post_tag wp-block-post-terms">
              <?php
              if ($post_tags) {
                if (count($post_tags) > 0) {
                  foreach ($post_tags as $key => $val) {
                    ?>
                    <a href="<?php echo get_permalink(); ?>">
                      <?php echo $val->name; ?>
                    </a>
                    <?php
                  }
                }
              }
              ?>
            </div>
            <div class="wp-block-post-date"> <time>
                <?php echo get_the_date() ?>
              </time></div>
            <a href="<?php the_permalink() ?>">
              <h3 class="entry-title">
                <?php the_title() ?>
              </h3>
            </a>

          </div>
          <?php
        endwhile;
        ?>

        <?php
      endif;

      // Reset the query
      wp_reset_query();

      ?>
    </div>
  </div>
</div>
<?php
/*
Plugin Name: Dokan Product Categories Additional Fees
Plugin URI: https://example.com
Description: Adds an "Additional Fees" field to WooCommerce product categories and displays additional fees for orders with products from multiple vendors based on the "Additional Fees" value.
Version: 1.0
Author: Your Name
Author URI: https://example.com
*/

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

function enqueue_sweetalert2() {
    wp_enqueue_style('sweetalert2', 'https://cdn.jsdelivr.net/npm/sweetalert2@11.7.3/dist/sweetalert2.min.css');
    wp_enqueue_script('sweetalert2', 'https://cdn.jsdelivr.net/npm/sweetalert2@11.7.3/dist/sweetalert2.all.min.js', array('jquery'), null, true);
}
add_action('wp_enqueue_scripts', 'enqueue_sweetalert2');

// Enqueue the JavaScript file


// Save the "Additional Fees" field value when adding/editing a product category
add_action('created_term', 'save_additional_fees_field', 10, 3);
add_action('edit_term', 'save_additional_fees_field', 10, 3);
function save_additional_fees_field($term_id, $tt_id, $taxonomy)
{
   if ('product_cat' !== $taxonomy) {
       return;
   }

   $additional_fees = isset($_POST['additional_fees']) ? sanitize_text_field($_POST['additional_fees']) : '';
   update_term_meta($term_id, 'additional_fees', $additional_fees);
}

// Add the "Additional Fees" field to the product category add/edit page
add_action('product_cat_add_form_fields', 'add_additional_fees_field');
add_action('product_cat_edit_form_fields', 'edit_additional_fees_field', 10, 2);
function add_additional_fees_field()
{
   ?>
   <div class="form-field term-additional-fees-wrap">
       <label for="additional-fees"><?php esc_html_e('Additional Fees', 'woocommerce'); ?></label>
       <input type="text" name="additional_fees" id="additional-fees" value="">
   </div>
   <?php
}

function edit_additional_fees_field($term, $taxonomy)
{
   $additional_fees = get_term_meta($term->term_id, 'additional_fees', true);
   ?>
   <tr class="form-field term-additional-fees-wrap">
       <th scope="row"><label for="additional-fees"><?php esc_html_e('Additional Fees', 'woocommerce'); ?></label></th>
       <td><input type="text" name="additional_fees" id="additional-fees" value="<?php echo esc_attr($additional_fees); ?>"></td>
   </tr>
   <?php
}

/**
* Display Additional Fees message in the cart
*/
add_action('woocommerce_cart_totals_before_order_total', 'display_additional_fees_in_cart');
function display_additional_fees_in_cart()
{
   $product_id = get_the_ID();
   $product_categories = wp_get_post_terms($product_id, 'product_cat', array('fields' => 'ids'));

   // Iterate through the categories and get the additional fees
   $additional_fees = 0;
   foreach ($product_categories as $category_id) {
       $category_additional_fees = get_term_meta($category_id, 'additional_fees', true);
       if (!empty($category_additional_fees)) {
           $additional_fees = max($additional_fees, $category_additional_fees);
       }
   }

   // Display the additional fees if they exist
   if ($additional_fees > 0) {
       echo '<div class="woocommerce-notices-wrapper">';
       echo '<ul class="woocommerce-error" role="alert">';
       echo '<li>' . esc_html__('رسوم إضافية:', 'woocommerce') . ' ' . wc_price($additional_fees) . '</li>';
       echo '</ul>';
       echo '</div>';
   }
}

/**
* Display Additional Fees message on the product page
*/
add_action('woocommerce_before_add_to_cart_button', 'display_additional_fees_message');
function display_additional_fees_message() {
    global $product;

    // Get the product categories
    $product_categories = wp_get_post_terms($product->get_id(), 'product_cat', array('fields' => 'ids'));

    // Iterate through the categories and get the additional fees
    $additional_fees = 0;
    foreach ($product_categories as $category_id) {
        $category_additional_fees = get_term_meta($category_id, 'additional_fees', true);
        if (!empty($category_additional_fees)) {
            $additional_fees = max($additional_fees, $category_additional_fees);
        }
    }

    // Get the vendor ID for this product
    $vendor_id = get_post_field('post_author', $product->get_id());

    // Check if there are products from other vendors in the cart
    $other_vendors = false;
    foreach (WC()->cart->get_cart() as $cart_item) {
        $product_id = $cart_item['product_id'];
        $item_vendor_id = get_post_field('post_author', $product_id);
        if ($item_vendor_id != $vendor_id) {
            $other_vendors = true;
            break;
        }
    }

    // Display the message if additional fees exist and there are products from other vendors in the cart
    if ($additional_fees > 0 && $other_vendors) {
        ?>
        <script type="text/javascript">
        (function($) {
            $('form.cart').on('submit', function(e) {
                e.preventDefault();
                Swal.fire({
                    title: '<?php esc_html_e('رسوم إضافية', 'woocommerce'); ?>',
                    html: '<?php echo sprintf(esc_html__('سيتم تطبيق رسوم إضافية بقيمة %s على طلبك.', 'woocommerce'), wc_price($additional_fees)); ?>',
                    icon: 'warning',
                    confirmButtonText: '<?php esc_html_e('موافق', 'woocommerce'); ?>'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $(this).unbind('submit').submit();
                    }
                });
            });
        })(jQuery);
        </script>
        <?php
    }
}

add_action('wp_ajax_display_multi_vendor_warning', 'display_multi_vendor_warning');
add_action('wp_ajax_nopriv_display_multi_vendor_warning', 'display_multi_vendor_warning');
function display_multi_vendor_warning() {
    $product_ids = $_POST['product_ids'];

    $vendors = array();
    foreach ($product_ids as $product_id) {
        $vendor_id = get_post_field('post_author', $product_id);
        $vendors[$vendor_id] = true;
    }

    if (count($vendors) > 1) {
        $response = array(
            'success' => true,
            'message' => esc_html__('سلة التسوق الخاصة بك تحتوي على منتجات من عدة بائعين. قد تطبق رسوم إضافية.', 'woocommerce')
        );
    } else {
        $response = array(
            'success' => false,
            'message' => ''
        );
    }

    wp_send_json($response);
}

/**
 * Display a warning message if cart contains products from multiple vendors
 */
function add_additional_fees_script_to_footer() {
    ?>
    <script type="text/javascript">
    (function($) {
        var $woocommerce_div = $('div.woocommerce');

        function check_and_display_multi_vendor_warning() {
            var product_ids = [];
            $('div.woocommerce-cart-form__cart-item').each(function() {
                var $product_id = $(this).data('product_id');
                product_ids.push($product_id);
            });

            $.ajax({
                type: 'POST',
                url: '<?php echo admin_url('admin-ajax.php'); ?>',
                data: {
                    action: 'display_multi_vendor_warning',
                    product_ids: product_ids
                },
                success: function(response) {
                    if (response.success) {
                        $message = response.message;
                        if ($message) {
                            $woocommerce_div.prepend('<div class="woocommerce-notices-wrapper">' +
                                '<ul class="woocommerce-error" role="alert">' +
                                '<li>' + $message + '</li>' +
                                '</ul>' +
                                '</div>');
                        } else {
                            $woocommerce_div.find('.woocommerce-notices-wrapper').remove();
                        }
                    }
                },
                error: function() {
                    console.log('Error displaying multi-vendor warning');
                }
            });
        }

        $(document).ready(function() {
            check_and_display_multi_vendor_warning();
        });

        $woocommerce_div.on('updated_wc_div', function() {
            check_and_display_multi_vendor_warning();
        });
    })(jQuery);
    </script>
    <?php
}
add_action('wp_footer', 'add_additional_fees_script_to_footer');
//=========================================================================================================
function calculate_additional_fees() {
    $additional_fees = 0;

    foreach (WC()->cart->get_cart() as $cart_item) {
        $product_id = $cart_item['product_id'];
        $product_categories = wp_get_post_terms($product_id, 'product_cat', array('fields' => 'ids'));

        foreach ($product_categories as $category_id) {
            $category_additional_fees = get_term_meta($category_id, 'additional_fees', true);
            if (!empty($category_additional_fees)) {
                $additional_fees = max($additional_fees, $category_additional_fees);
            }
        }
    }

    return $additional_fees;
}
add_action('woocommerce_cart_calculate_fees', 'add_additional_fees_to_cart_total');
function add_additional_fees_to_cart_total(WC_Cart $cart) {
    $additional_fees = calculate_additional_fees();

    if ($additional_fees > 0) {
        $cart->add_fee(__('رسوم إضافية', 'woocommerce'), $additional_fees);
    }
}

//=================================================================================
/**
 * Display additional fees in order details
 */
add_action('woocommerce_admin_order_data_after_order_details', 'display_additional_fees_order_meta');
function display_additional_fees_order_meta($order) {
    $additional_fees = get_post_meta($order->get_id(), 'additional_fees', true);

    if (!empty($additional_fees)) {
        ?>
        <div class="order_data_column">
            <h4><?php esc_html_e('Additional Fees', 'woocommerce'); ?></h4>
            <p><?php echo wc_price($additional_fees); ?></p>
        </div>
        <?php
    }
}

/**
 * Save additional fees meta for the order
 */
add_action('woocommerce_checkout_create_order_line_item', 'save_additional_fees_order_meta', 10, 4);
function save_additional_fees_order_meta($item, $cart_item_key, $values, $order) {
    $additional_fees = calculate_additional_fees();

    if ($additional_fees > 0) {
        $order->update_meta_data('additional_fees', $additional_fees);
    }
}
composer require robmorgan/phinx
composer require symfony/yaml
composer require fzaninotto/faker


migrations:
phinx create ClearTableData
vendor\bin\phinx migrate
vendor\bin\phinx rollback



vendor\bin\phinx seed:create AddUser
vendor\bin\phinx seed:run
vendor\bin\phinx seed:run -s ClienteSeed
<?php
    if (get_post_field('post_name', get_the_ID()) != 'your-doctors') {
      ?>
      <div class="our-specilist__btn is-style-light-btn">
        <a href="<?php echo site_url('/your-doctors'); ?>" class="btn">
          View All Doctors
        </a>
      </div>
      <?php
    }
    ?>
<?php echo 'Hello world'; ?>
// Assuming you have a model for the table you want to insert into
$model = new YourModel;
$model->packages = json_encode(request('packages')); // Store the selected packages as a JSON array
$model->save();


===================
  $packages = json_decode($model->packages);
git clone -b minha-branch https://gitlab.com/seu_usuario/seu_repositorio.git

git rm --cached nome_do_arquivo

git rm -r --cached nome_da_pasta
if (config('app.debug')) {
  dump('');
  $this->info('');
}

config('app.debug') ? info('One liner') : null;
$userinfos = $f3->get('SESSION.userinfos');
$codeuser = $userinfos[1]->CheckAuthentificationResult->Code;
$codeResponsableUSer = $userinfos[1]->CheckAuthentificationResult->CodeResponsable;
<?php
function remove_title_tag_on_blog_posts($title_parts)
{
    global $template;
    $templateName =  basename($template);
    if ($templateName === 'single-post.php') {
        $title_tag_blog_post = get_field('title_tag_blog_post');
        if ($title_tag_blog_post) {
            $title_parts['title'] = $title_tag_blog_post;
        }
    }
    return $title_parts;
}

add_filter('document_title_parts', 'remove_title_tag_on_blog_posts', 10);
// Enfold Increase Excerpt Length
add_filter('avf_postgrid_excerpt_length','avia_change_postgrid_excerpt_length', 10, 1);
function avia_change_postgrid_excerpt_length($length)
{
   $length = 120;
   return $length;
}
<?php
// Konfigurasi koneksi ke database
$servername = "localhost"; // Ganti dengan nama server Anda
$username = "adminmaster"; // Ganti dengan username database Anda
$password = "DTCMtolong313"; // Ganti dengan password database Anda
$dbname = "master"; // Ganti dengan nama database Anda

// Membuat koneksi
$conn = new mysqli($servername, $username, $password, $dbname);

// Memeriksa koneksi
if ($conn->connect_error) {
    die("Koneksi gagal: " . $conn->connect_error);
}

// Ambil term dari input pengguna
//$term = $_POST["term"];
$term = mysqli_real_escape_string($conn, $_POST['term']);

// Query untuk mengambil data nama lengkap dari master_data_staff dengan jantina = 0
$sql = "SELECT DISTINCT nama_lengkap FROM master_data_staff WHERE jantina = 0 AND nama_lengkap LIKE '%$term%' LIMIT 10";
$result = $conn->query($sql);

// Menyimpan hasil query dalam bentuk array
$data = array();
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $data[] = $row["nama_lengkap"];
    }
}

// Mengirimkan data dalam format JSON
echo json_encode($data);

// Menutup koneksi database
$conn->close();
?>
function product_dropdown_shortcode() {
    ob_start();

    // Query to get all products
    $products = get_posts(array(
        'post_type' => 'product',
        'posts_per_page' => -1,
    ));

    // Output the dropdown HTML
    ?>
    <select id="product_dropdown">
        <option value="">Select a product</option>
        <?php foreach ($products as $product) : ?>
            <option value="<?php echo esc_attr($product->ID); ?>"><?php echo esc_html($product->post_title); ?></option>
        <?php endforeach; ?>
    </select>
    <script>
        jQuery(function($) {
            // Initialize select2 for searchable dropdown
            $('#product_dropdown').select2();
        });
    </script>
    <?php

    return ob_get_clean();
}
add_shortcode('product_dropdown', 'product_dropdown_shortcode');
function enqueue_select2() {
    // Enqueue Select2 library
    wp_enqueue_script('select2', 'https://cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-beta.1/js/select2.min.js', array('jquery'), '4.1.0-beta.1', true);
    wp_enqueue_style('select2', 'https://cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-beta.1/css/select2.min.css', array(), '4.1.0-beta.1');
}
add_action('wp_enqueue_scripts', 'enqueue_select2');
<!--HTML Code-->
  
  <form id="contact_form" method="post">
    <div class="row">
        <div class="col-md-12 form-group g-mb-20">
            <input type="text" class="form-control" id="txtContactName" name="txtContactName" placeholder="Full Name" tabindex="201" required>
            <div class="error-message" id="txtContactName-error"></div>
        </div>

        <div class="col-md-12 form-group g-mb-20">
            <input type="email" class="form-control" id="txtContactEmail" name="txtContactEmail" placeholder="Email Address" tabindex="202" required>
            <div class="error-message" id="txtContactEmail-error"></div>
        </div>

        <div class="col-md-12 form-group g-mb-20">
            <input type="text" class="form-control" id="txtContactPhone" name="txtContactPhone" placeholder="Contact Number" maxlength="10" tabindex="203" required>
            <div class="error-message" id="txtContactPhone-error"></div>
        </div> 

        <div class="col-md-12 form-group g-mb-40">
            <textarea class="form-control" id="txtContactMessage" name="txtContactMessage" rows="7" placeholder="Message" maxlength="160" tabindex="204" required></textarea>
            <div class="error-message" id="txtContactMessage-error"></div>
        </div>
    </div>
    <input type="submit" class="btn btn-lg u-btn-primary g-font-weight-600 g-font-size-default rounded-0 text-uppercase g-py-15 g-px-30" id="btnContactSubmit" name="btnContactSubmit" value="SUBMIT">
</form>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.min.js"></script>
<script>
	
</script>
<script>
    $(document).ready(function() {
        $('#contact_form').validate({
            rules: {
                txtContactName: "required",
                txtContactEmail: {
                    required: true,
                    email: true
                },
                txtContactPhone: {
                    required: true,
                    digits: true,
                    maxlength: 10
                },
                txtContactMessage: "required"
            },
            messages: {
                txtContactName: "Please enter your full name",
                txtContactEmail: {
                    required: "Please enter your email address",
                    email: "Please enter a valid email address"
                },
                txtContactPhone: {
                    required: "Please enter your contact number",
                    digits: "Please enter only digits",
                    maxlength: "Please enter a valid 10-digit phone number"
                },
                txtContactMessage: "Please enter your message"
            },
            errorPlacement: function(error, element) {
                error.appendTo(element.closest('.form-group').find('.error-message'));
            },
            submitHandler: function(form) {
                var formData = $(form).serialize();
                $.ajax({
                    type: 'POST',
                    url: 'mail.php',
                    data: formData,
                    success: function(response) {
                        $('#contact_form').append('<div class="success-message" style="color: green;">Message sent successfully!</div>');
                        setTimeout(function() {
                            $('#contact_form')[0].reset();
                        }, 4000);
                    },
                    error: function(xhr, status, error) {
                        console.error(xhr.responseText);
                        alert('Error: ' + xhr.responseText);
                    }
                });
            }
        });
    });
</script>

PHP Miler folder should be there
Create folder name with mail.php and add below code there 
<?php
// Include PHPMailer autoload file

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Load Composer's autoloader
require 'phpmailer/vendor/autoload.php';

// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve form data
    $name = $_POST['txtContactName'];
    $email = $_POST['txtContactEmail'];
    $phone = $_POST['txtContactPhone'];
    $message = $_POST['txtContactMessage'];

    // Initialize PHPMailer
    $mail = new PHPMailer(true);
    try {
        // SMTP settings
		$mail->IsSMTP();        // Sets Mailer to send message using SMTP
		$mail->SMTPAuth = true; // Authentication enabled
		$mail->SMTPSecure = 'tls'; // Secure transfer enabled REQUIRED for Gmail
		$mail->Host = 'smtp-relay.brevo.com';
		$mail->Port = 587;
		$mail->Username = 'advanceindiaprojectltd@gmail.com';
		$mail->Password = 'xsmtpsib-e66045ab99d2f28608d548ca33a5a3ac8cc14a6896d682cbdc5418c80154b5eb-6B5QJOyT18GvbzmZ';
		$mail->SMTPOptions = array(
			'ssl' => array(
				'verify_peer' => false,
				'verify_peer_name' => false,
				'allow_self_signed' => true
			)
		);

        // Recipients
        $mail->setFrom($email, $name);
        $mail->addAddress('roshan@teamvariance.com'); // Add recipient email address

        // Content
        $mail->isHTML(true);
        $mail->Subject = 'Contact Form Submission';
		// Construct HTML table for the email body
        $message = '
            <h3 align="center">Details</h3>
            <table border="1" width="100%" cellpadding="5" cellspacing="5">
                <tr>
                    <td width="30%">Name</td>
                    <td width="70%">' . $name . '</td>
                </tr> 
                <tr>
                    <td width="30%">Email</td>
                    <td width="70%">' . $email . '</td>
                </tr>
                <tr>
                    <td width="30%">Phone</td>
                    <td width="70%">' . $phone . '</td>
                </tr>
                <tr>
                    <td width="30%">Message</td>
                    <td width="70%">' . $message . '</td>
                </tr>
            </table>
        ';
        $mail->Body = $message;

        // Send email
        $mail->send();
        
        // Return success message
        echo "success";
    } catch (Exception $e) {
        // Return error message
        echo "error";
    }
}
?>



// Function to create the custom product dropdown shortcode
function custom_product_dropdown_shortcode() {
  ob_start(); // Start output buffering

  // Get the referring URL and selected product name
  $referring_url = wp_get_referer();
  $selected_product_name = '';
  $selected_product_id = ''; // Initialize for product ID selection

  if ($referring_url) {
    $url_parts = parse_url($referring_url);
    if (isset($url_parts['path'])) {
      $path_parts = explode('/', $url_parts['path']);
      $product_index = array_search('product', $path_parts);
      if ($product_index !== false && isset($path_parts[$product_index + 1])) {
        $selected_product_name = $path_parts[$product_index + 1];
        $selected_product_id = $path_parts[$product_index + 1]; // Assuming product ID in URL
      }
    }
  }

  // Create the dropdown with search functionality using Select2
  echo '<select id="product_name" name="product_name">';
  echo '<option value="">Select Product</option>';
  echo '<option data-tokens="Search Products" disabled hidden></option>'; // Search placeholder

  $products = array(); // Store product data for filtering

  $query = new WP_Query(array(
    'post_type' => 'product',
    'post_status' => 'publish',
    'posts_per_page' => '-1'
  ));

  if ($query->have_posts()) :
    while ($query->have_posts()) : $query->the_post();
      $product = wc_get_product(get_the_ID());
      $price = $product->get_price_html();
      $selected = '';
      // Use product name for comparison
      if (get_the_title() === $selected_product_name) {
        $selected = 'selected="selected"';
      }

      $products[] = array(
        'id' => get_the_title(), // Store product name instead of ID
        'text' => get_the_title() 
      );
    endwhile;
  else:
    echo '<option value="">No products found</option>';
  endif;

  wp_reset_postdata();

  foreach ($products as $product) {
    echo '<option value="' . $product['id'] . '" ' . $selected . '>' . $product['text'] . '</option>';
  }

  echo '</select>';

  // Enqueue JavaScript for search functionality
  wp_enqueue_script('select2'); // Assuming you've added the Select2 library
  ?>
  <script>
    jQuery(function($) {
      $('#product_name').select2({
        data: <?php echo json_encode(array_map(function($product) {
          return array('id' => $product['id'], 'text' => $product['text']);
        }, $products)); ?>,
        placeholder: 'Search Products'
      });
    });
  </script>
  <?php

  return ob_get_clean(); // Return the output and clean buffer
}

// Add the shortcode to WordPress
add_shortcode('custom_product_dropdown', 'custom_product_dropdown_shortcode');







//below code is same as above but instead of product name is saving in back the product ID is saving :






// Function to create the custom product dropdown shortcode
function custom_product_dropdown_shortcode() {
  ob_start(); // Start output buffering

  // Get the referring URL and selected product name
  $referring_url = wp_get_referer();
  $selected_product_name = '';
  $selected_product_id = ''; // Initialize for product ID selection

  if ($referring_url) {
    $url_parts = parse_url($referring_url);
    if (isset($url_parts['path'])) {
      $path_parts = explode('/', $url_parts['path']);
      $product_index = array_search('product', $path_parts);
      if ($product_index !== false && isset($path_parts[$product_index + 1])) {
        $selected_product_name = $path_parts[$product_index + 1];
        $selected_product_id = $path_parts[$product_index + 1]; // Assuming product ID in URL
      }
    }
  }

  // Create the dropdown with search functionality using Select2
  echo '<select id="product_name" name="product_name">';
  echo '<option value="">Select Product</option>';
  echo '<option data-tokens="Search Products" disabled hidden></option>'; // Search placeholder

  $products = array(); // Store product data for filtering

  $query = new WP_Query(array(
    'post_type' => 'product',
    'post_status' => 'publish',
    'posts_per_page' => '-1'
  ));

  if ($query->have_posts()) :
    while ($query->have_posts()) : $query->the_post();
      $product = wc_get_product(get_the_ID());
      $price = $product->get_price_html();
      $selected = '';
      // Use product ID for comparison
      if (get_the_ID() === $selected_product_id) {
        $selected = 'selected="selected"';
      }

      $products[] = array(
        'id' => get_the_ID(), // Add ID for selection
        'text' => get_the_title() 
      );
    endwhile;
  else:
    echo '<option value="">No products found</option>';
  endif;

  wp_reset_postdata();

  echo '</select>';

  // Enqueue JavaScript for search functionality
  wp_enqueue_script('select2'); // Assuming you've added the Select2 library
  ?>
  <script>
    jQuery(function($) {
      $('#product_name').select2({
        data: <?php echo json_encode(array_map(function($product) {
          return array('id' => $product['id'], 'text' => $product['text']);
        }, $products)); ?>,
        placeholder: 'Search Products'
      });
    });
  </script>
  <?php

  return ob_get_clean(); // Return the output and clean buffer
}

// Add the shortcode to WordPress
add_shortcode('custom_product_dropdown', 'custom_product_dropdown_shortcode');

ChatGPT








// by below code the search bar for page using shortcode not drodown a searchbar


function product_search_shortcode() {
    ob_start(); ?>

    <div class="product-search-container">
        <input type="text" id="product-search-input" placeholder="Search for a product...">
        <div id="product-search-results"></div>
    </div>

    <script>
    jQuery(document).ready(function($) {
        $('#product-search-input').keyup(function() {
            var searchQuery = $(this).val();

            $.ajax({
                url: '<?php echo admin_url('admin-ajax.php'); ?>',
                type: 'POST',
                data: {
                    'action': 'product_search',
                    'search_query': searchQuery
                },
                success: function(response) {
                    $('#product-search-results').html(response);
                }
            });
        });

        $(document).on('click', '.product-item', function() {
            var selectedProduct = $(this).text();
            $('#product-search-input').val(selectedProduct);
            $('#product-search-results').html('');
        });
    });
    </script>

    <?php
    return ob_get_clean();
}
add_shortcode('product_search', 'product_search_shortcode');

function product_search_callback() {
    $search_query = $_POST['search_query'];

    $products = wc_get_products(array(
        'status' => 'publish',
        'limit' => -1,
        's' => $search_query,
    ));

    if ($products) {
        foreach ($products as $product) {
            echo '<div class="product-item">' . $product->get_name() . '</div>';
        }
    } else {
        echo '<div class="product-item">No products found</div>';
    }

    wp_die();
}
add_action('wp_ajax_product_search', 'product_search_callback');
add_action('wp_ajax_nopriv_product_search', 'product_search_callback');

// ================================
// Extra Footer
// ================================

add_action('ava_before_footer','extra_footer');
    function extra_footer() { ?>
       
<?php }
<input                       
    type="text" 
    placeholder="Start date" 
    class="px-2 py-1 text-sm rounded text-gray-800" 
    x-init="new Pikaday({ field: $el })"
    x-on:change="$wire.startDate = formatDateToYYYYMMDD(new Date($el.value))"
/>
    // Exemple :
    $text = "<script>console.log('salut')</script>";
    echo $text; // Execute le script !
    echo filter_var($text, FILTER_SANITIZE_FULL_SPECIAL_CHARS); // Pas interprèter

    $email = "jean(du22)@toto.fr";
    echo $email; // output : jean(du22)@toto.fr
    echo filter_var($email, FILTER_SANITIZE_EMAIL); // output : jeandu22@toto.fr

    $number = "a10.5";
    echo filter_var($number, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND);

    $arr = [
        'email' => 'jean(a)@<gmail>.com',
        'text' => '<script>const a = 1</script>',
        'number' => 'aa12aaa'
    ];
    print_r(filter_var_array($arr, [
        'email' => FILTER_SANITIZE_EMAIL,
        'text' => [
            'filter' => FILTER_SANITIZE_FULL_SPECIAL_CHARS,
            'flags' =>  FILTER_FLAG_NO_ENCODE_QUOTES
        ],
        'number' => FILTER_SANITIZE_NUMBER_INT
    ]));


    $_POST = filter_input_array(INPUT_POST, [
        'firstname' => FILTER_SANITIZE_FULL_SPECIAL_CHARS,
        'email' => FILTER_SANITIZE_EMAIL,
        'date' => FILTER_SANITIZE_FULL_SPECIAL_CHARS
    ]);
/**
 * 	Show ID in Wordpress
 * 
	Add ID in the action row of list tables for pages, posts,
	custom post types, media, taxonomies, custom taxonomies,
	users amd comments
	
	Inspiration:
	https://wordpress.org/plugins/admin-site-enhancements/
	https://www.itsupportguides.com/knowledge-base/wordpress/using-wordpress-post_row_actions-php-filter/
*/

add_filter('post_row_actions', 'add_custom_action_for_specific_post_type', 11, 2);
add_filter('page_row_actions', 'add_custom_action_for_specific_post_type', 11, 2);
add_filter('cat_row_actions', 'add_custom_action_for_specific_post_type', 11, 2);
add_filter('tag_row_actions', 'add_custom_action_for_specific_post_type', 11, 2);
add_filter('media_row_actions', 'add_custom_action_for_specific_post_type', 11, 2);
add_filter('comment_row_actions', 'add_custom_action_for_specific_post_type', 11, 2);
add_filter('user_row_actions', 'add_custom_action_for_specific_post_type', 11, 2);

/* Output the ID in the action row */
function add_custom_action_for_specific_post_type( $actions, $object ) {
        
	if ( current_user_can( 'edit_posts' ) ) {
		// For pages, posts, custom post types, media/attachments, users
		if ( property_exists( $object, 'ID' ) ) {
			$id = $object->ID;
		}
		// For taxonomies
		if ( property_exists( $object, 'term_id' ) ) {
			$id = $object->term_id;
		}
		// For comments
		if ( property_exists( $object, 'comment_ID' ) ) {
			$id = $object->comment_ID;
		}
		$actions['show-id-now'] = '<span style="color: gray;">ID: ' . $id . '</span>';
	}
	return $actions;
}
if ( is_single() ) {
  $current_post_id = get_queried_object_id();
  $current_category_id = get_the_category( $current_post_id )[0]->cat_ID;

  $args = array(
    'category' => $current_category_id,
    'post__not_in' => array( $current_post_id ),
    'posts_per_page' => 3,
  );

  $related_posts = new WP_Query( $args );

  if ( $related_posts->have_posts() ) {
    echo '<h2>Related Posts:</h2>';
    while ( $related_posts->have_posts() ) {
      $related_posts->the_post();
      echo '<a href="' . get_the_permalink() . '">' . get_the_title() . '</a><br>';
    }
    wp_reset_postdata();
  }
}
wp.domReady(function () {
	wp.blocks.registerBlockStyle('core/button', {
		name: 'link-btn',
		label: 'Link Btn',
	});
});
/**
 * Filters the next, previous and submit buttons.
 * Replaces the form's <input> buttons with <button> while maintaining attributes from original <input>.
 *
 * @param string $button Contains the <input> tag to be filtered.
 * @param object $form Contains all the properties of the current form.
 *
 * @return string The filtered button.
 */
add_filter('gform_submit_button', 'input_to_button', 10, 2);
function input_to_button($button, $form)
{
  $dom = new DOMDocument();
  $dom->loadHTML('<?xml encoding="utf-8" ?>' . $button);
  $input = $dom->getElementsByTagName('input')->item(0);
  $new_button = $dom->createElement('button');
  $new_button->appendChild($dom->createTextNode($input->getAttribute('value')));
  $input->removeAttribute('value');
  foreach ($input->attributes as $attribute) {
    $new_button->setAttribute($attribute->name, $attribute->value);
  }

  $classes = $new_button->getAttribute('class');
  $classes .= " btn is-style-with-arrow";
  $new_button->setAttribute('class', $classes);
  $input->parentNode->replaceChild($new_button, $input);

  return $dom->saveHtml($new_button);
}
/**
 * Attach icon class to the menu title
 *
 * @param $sorted_menu_items
 * @param $args
 * @return mixed
 */
function wti_add_arrow_to_parent_menu_item($sorted_menu_items, $args)
{
	foreach ($sorted_menu_items as $menu_item) {
		if (array_search('menu-item-has-children', $menu_item->classes) != FALSE) {
			$menu_item->title = $menu_item->title . '<svg width="24" height="25" viewBox="0 0 24 25" fill="none" xmlns="http://www.w3.org/2000/svg">
				<path d="M19.9201 9.44995L13.4001 15.97C12.6301 16.74 11.3701 16.74 10.6001 15.97L4.08008 9.44995" stroke="#fff" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
				</svg>';
		}
	}

	return $sorted_menu_items;
}
// Dropdown arrows to parent menu items
add_filter('wp_nav_menu_objects', 'wti_add_arrow_to_parent_menu_item', 10, 2);
/* Remove WooCommerce block styles */
function ya_remove_block_css() {
    wp_dequeue_style( 'wc-block-style' ); // WooCommerce
}
add_action('wp_enqueue_scripts','ya_remove_block_css', 100);
// Avia Layout Builder in custom post types

function avf_alb_supported_post_types_mod( array $supported_post_types )
{
  $supported_post_types[] = 'case_studies';
  return $supported_post_types;
}
add_filter('avf_alb_supported_post_types', 'avf_alb_supported_post_types_mod', 10, 1);

function avf_metabox_layout_post_types_mod( array $supported_post_types )
{
 $supported_post_types[] = 'case_studies';
 return $supported_post_types;
}
add_filter('avf_metabox_layout_post_types', 'avf_metabox_layout_post_types_mod', 10, 1);
public function index(Travel $travel, ToursListRequest $request)
    {
        $tours = $travel->tours()
            ->when($request->priceFrom, function ($query) use ($request) {
                $query->where('price', '>=', $request->priceFrom * 100);
            })
            ->when($request->priceTo, function ($query) use ($request) {
                $query->where('price', '<=', $request->priceTo * 100);
            })
            ->when($request->dateFrom, function ($query) use ($request) {
                $query->where('starting_date', '>=', $request->dateFrom);
            })
            ->when($request->dateTo, function ($query) use ($request) {
                $query->where('starting_date', '<=', $request->dateTo);
            })
            ->when($request->sortBy, function ($query) use ($request) {
                if (! in_array($request->sortBy, ['price'])
                    || (! in_array($request->sortOrder, ['asc', 'desc']))) {
                    return;
                }

                $query->orderBy($request->sortBy, $request->sortOrder);
            })
            ->orderBy('starting_date')
            ->paginate();

        return TourResource::collection($tours);
    }
//in controller datatable
->addColumn('mass_delete', function ($row) {
  $selected = '';

  return  '<input type="checkbox" class="row-select test" value="'.$row->id.'">' ;
})


//in view table
 <th>_<input type="checkbox" value="1" id="select-all-row" data-table-id="incoming-messages-table"></th>

//in view datatable (to disable orderable on first column)
'columnDefs': [ {
  'targets': [0], /* column index */
  'orderable': false, /* true or false */
}]

//in view (action button and)
<button type="submit" class="btn btn-xs btn-primary" id="delete-selected">{{__('admin.delete selected')}}</button>
<form action="{{route('admin.incoming-messages.deleteArray')}}" method="post" id="delete_form">
  @csrf
<div class="inputs">

  </div>
</form>


//in view js
<script>
  $(document).on('click', '#select-all-row', function(e) {
    var table_id = $(this).data('table-id');
    if (this.checked) {
      $('#' + table_id)
        .find('tbody')
        .find('input.row-select')
        .each(function() {
        if (!this.checked) {
          $(this)
            .prop('checked', true)
            .change();
        }
      });
    } else {
      $('#' + table_id)
        .find('tbody')
        .find('input.row-select')
        .each(function() {
        if (this.checked) {
          $(this)
            .prop('checked', false)
            .change();
        }
      });
    }
  });


$(document).on('click', '#delete-selected', function(e){
  e.preventDefault();

  $ids = '';
  $html = '';
  $("input:checkbox:checked").each(function(){
    $ids += $(this).val() + ',';
    $html += '<input type="hidden" id="message_deleted" name="message[]" value="'+$(this).val()+'">';
  })
  $('.inputs').html($html);
  $('form#delete_form').submit() 
})
</script>

Here's a guide on how to start developing poker software, outlining key steps and code structure:

1. Define the Scope of Your Project:

    Game Variants: Choose which poker variants you'll include (e.g., Texas Hold'em, Omaha, 5-Card Draw).
    Features: Decide on essential features like player accounts, gameplay, betting, tournaments, chat, and multi-platform compatibility.
    Target Platforms: Determine if you're developing for web, desktop, mobile, or a combination.

2. Choose Your Programming Language and Development Environment:

    Common Languages: Python, Java, C++, C#, and JavaScript are popular choices for game development.
    Development Environments: Select an IDE (Integrated Development Environment) like Visual Studio Code, PyCharm, or Eclipse for efficient coding.

3. Structure Your Code:

    Classes: Create classes for representing cards, decks, hands, players, game tables, and the game logic itself.
    Functions: Write functions to handle shuffling, dealing, betting, evaluating hands, and managing game flow.

4. Implement Core Functionalities:

    Card Deck: Create a class to represent a deck of cards, with methods for shuffling and dealing cards.
    Player Hand: Implement a class to hold a player's hand, with methods for evaluating hand strength.
    Game Logic: Write the core game logic, including betting rounds, hand comparisons, and pot management.

5. Design the User Interface (UI):

    Visual Design: Create visually appealing UI elements using graphics libraries or frameworks.
    User Interaction: Implement intuitive controls for players to interact with the game.

6. Test Thoroughly:

    Unit Testing: Test individual code units to ensure they function as intended.
    Integration Testing: Verify that different parts of the code work together seamlessly.
    User Testing: Gather feedback from real users to identify bugs and areas for improvement.

7. Deploy and Maintain:

    Deployment: Make your poker software available to users on your chosen platforms.
    Maintenance: Address any bugs or issues, and update the software with new features or improvements over time.
//Les tableaux 
// Opérateurs + 
$a = [1, 2];
$b = [4, 5, 6];

print_r($a + $b); //Output = 1, 2, 6 
//Prends la valeur du tableaux de droite et si pas d'index prends la valeur de gauche

// Opérateurs == ne prends pas en compte l'ordre
// Opérateurs === prends en compte l'ordre

// Spread operator :
print_r([...$a, ...$b]); // [1, 2, 4, 5, 6]
// Le tableaux n'existe plus et on étend les valeurs 

//&$variable Récupère l'adresse mémoire d'une variable

// Assigner une valeur à un tableaux :
// Ajouter une valeur à l'index suivant
$arr = [1];
$arr[] = 2; //Output = [1, 2]
// Equivalence avec le spread :
$arr = [...$arr, 3]; // Assigne un nouveau tableau et spread l'ancien en assignant une nouvelle valeur
$arr = [-1, ...$arr]; //Ajoute une valeur au début
array_push($arr, 4);


// Return a random value
$arr = ['orrange', 'blue', 'yellow'];
$value = array_rand($arr);
echo $arr[$value];

// Remove duplicates
$arr2 = ['test', 'test', 1, 2, 3];
$res = array_unique($arr2);
return [
  ...
  'providers' => [
    ...
    \Intervention\Image\ImageServiceProvider::class,
  ],
  'aliases' => Facade::defaultAliases()->merge([
        ...
        'Image' => \Intervention\Image\Facades\Image::class,
    ])->toArray(),
]
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ImageController extends Controller 
{
    public function compressImage(Request $request) 
    {
        $this->validate($request, [
            'image' => 'required|image|mimes:jpg,jpeg,png,gif,svg|max:2048'
        ]);

        $image = $request->file['image'];
        /* 
            Note: Use $image = base64_decode($request['image'])
            if the image is sent as a base64 encoded image.
        */
        $image_name = time().'_'.$image->getClientOriginalName();
        $path = public_path('uploads/') . "/" . $image_name;

        Image::make($image->getRealPath())->resize(150, 150)->save($path);
      
        return response()->json(
            [
                'data' => 'Image compressed and added'
            ], 
            201
        );
    }
}
add_filter( 'woocommerce_product_export_column_names', 'add_slug_export_column' );
add_filter( 'woocommerce_product_export_product_default_columns', 'add_slug_export_column' );

function add_slug_export_column( $columns ) {
	$columns['slug'] = 'Slug';
 
	return $columns;
}

add_filter( 'woocommerce_product_export_product_column_slug'  , 'add_export_data_slug', 10, 2 );
function add_export_data_slug( $value, $product ) {
    $value = $product->get_slug();
	
    return $value;
}

add_filter( 'woocommerce_csv_product_import_mapping_options', 'add_slug_import_option' );
function add_slug_import_option( $options ) {
  $options['slug'] = 'Slug';
 
  return $options;
}

add_filter( 'woocommerce_csv_product_import_mapping_default_columns', 'add_default_slug_column_mapping' );
function add_default_slug_column_mapping( $columns ) {
  $columns['Slug'] = 'slug';
 
  return $columns;
} 

add_filter( 'woocommerce_product_import_pre_insert_product_object', 'process_import_product_slug_column', 10, 2 );
function process_import_product_slug_column( $object, $data ) {
  if ( !empty( $data['slug'] ) ) {
    $object->set_slug( $data['slug'] );
  }
 
  return $object;
}
function woodmart_post_date( $args ) {
	$has_title = get_the_title() != '';
	$attr      = '';
	if ( ! $has_title && ! is_single() ) {
		$url  = get_the_permalink();
		$attr = 'window.location=\'' . $url . '\';';
	}
	$classes  = '';
	$classes .= ' ' . $args['style'];
	$classes .= woodmart_get_old_classes( ' woodmart-post-date' );
	?>
		<div class="post-date wd-post-date<?php echo esc_attr( $classes ); ?>" onclick="<?php echo esc_attr( $attr ); ?>">
			<span class="post-date-day">
				<?php echo get_the_time( 'd' ); ?>
			</span>
			<span class="post-date-month">
				<?php echo get_the_time( 'M' ); ?>
			</span>
			<span class="post-date-year">
				<?php echo get_the_time( 'Y' ); ?>
			</span>
		</div>
	<?php
}
function mergePdf($pdfArr){
    $pdf = new Mpdf();
    foreach($pdfArr as $currentPdf){
      $pagecount = $pdf->SetSourceFile($currentPdf);
      for($i = 1; $i <= $pagecount; $i++){
        $pdf->AddPage();
        $tplId = $pdf->importPage($i);
        $pdf->useTemplate($tplId);
      }
    }
    //direct show on browser
    $pdf->Output();
    
    //spacefic location save file
    $outputpath = 'location/output.pdf';
    $pdf->Output($outputpath, 'F');
}
function find_order_with_product_for_user($user_id, $product_id) {
	global $wpdb;

	// Get the order IDs for the user
	$order_ids = $wpdb->get_col("
        SELECT DISTINCT order_items.order_id
        FROM wp_woocommerce_order_items as order_items
        LEFT JOIN wp_woocommerce_order_itemmeta as order_itemmeta ON order_items.order_item_id = order_itemmeta.order_item_id
        LEFT JOIN wp_posts as posts ON order_items.order_id = posts.ID
        LEFT JOIN wp_postmeta as postmeta ON postmeta.post_id = posts.ID
        WHERE posts.post_type = 'shop_order'
        AND posts.post_status IN ('wc-processing', 'wc-completed')
        AND order_itemmeta.meta_key = '_product_id'
        AND order_itemmeta.meta_value = '$product_id'
        AND postmeta.meta_key = '_customer_user'
        AND postmeta.meta_value = '$user_id'
    ");

	// If orders are found, return the order IDs
	if ($order_ids) {
		return $order_ids;
	}

	return false;
}
function course_woocommerce_product_downloads_shortcode($atts) {
	// Extract shortcode attributes
	$atts = shortcode_atts(
		array(
			'product_id' => get_the_ID(), // Specify the product ID
		),
		$atts,
		'custom_woocommerce_product_downloads'
	);

	// Check if the product ID is provided
	if (empty($atts['product_id'])) {
		return '';
	}

	// Get the product object
	$product = wc_get_product($atts['product_id']);
	$order_ids = find_order_with_product_for_user(get_current_user_id(), $atts['product_id']);

	// Check if the product is downloadable
	if ($product && $product->is_downloadable() &&  wc_customer_bought_product(get_current_user_id(), get_current_user_id(), get_the_ID())) {
		$order = wc_get_order(current($order_ids));
		$downloads = $order->get_downloadable_items();
		// Check if there are downloads
		if ($downloads) {
			// Output a list of download files
			$output = '<h2>دانلود دوره خریداری شده ' . esc_html($product->get_name()) . '</h2>';
			$output .= '<ul>';
			foreach ($downloads as $download) {
				if($download['product_id'] != $atts['product_id']){
					continue;
				}
				$output .= '<li><a href="' . esc_url($download['download_url']) . '">' . esc_html($download['download_name']) . "</a></li>";
			}
			$output .= '</ul>';
		} else {
			$output = '<p>هیچ فایل دانلودی برای این دوره موجود نیست.</p>';
		}
	} else {
		$output = '<p>برای مشاهده فایل ها لطفا ابتدا دوره را خریداری کنید</p>';
	}

	return $output;
}
add_shortcode('course_woocommerce_product_downloads', 'course_woocommerce_product_downloads_shortcode');
function find_order_with_product_for_user($user_id, $product_id) {
	global $wpdb;

	// Get the order IDs for the user
	$order_ids = $wpdb->get_col("
        SELECT DISTINCT order_items.order_id
        FROM wp_woocommerce_order_items as order_items
        LEFT JOIN wp_woocommerce_order_itemmeta as order_itemmeta ON order_items.order_item_id = order_itemmeta.order_item_id
        LEFT JOIN wp_posts as posts ON order_items.order_id = posts.ID
        LEFT JOIN wp_postmeta as postmeta ON postmeta.post_id = posts.ID
        WHERE posts.post_type = 'shop_order'
        AND posts.post_status IN ('wc-processing', 'wc-completed')
        AND order_itemmeta.meta_key = '_product_id'
        AND order_itemmeta.meta_value = '$product_id'
        AND postmeta.meta_key = '_customer_user'
        AND postmeta.meta_value = '$user_id'
    ");

	// If orders are found, return the order IDs
	if ($order_ids) {
		return $order_ids;
	}

	return false;
}
function course_woocommerce_product_downloads_shortcode($atts) {
	// Extract shortcode attributes
	$atts = shortcode_atts(
		array(
			'product_id' => get_the_ID(), // Specify the product ID
		),
		$atts,
		'custom_woocommerce_product_downloads'
	);

	// Check if the product ID is provided
	if (empty($atts['product_id'])) {
		return '';
	}

	// Get the product object
	$product = wc_get_product($atts['product_id']);
	$order_ids = find_order_with_product_for_user(get_current_user_id(), $atts['product_id']);

	// Check if the product is downloadable
	if ($product && $product->is_downloadable() &&  wc_customer_bought_product(get_current_user_id(), get_current_user_id(), get_the_ID())) {
		$order = wc_get_order(current($order_ids));
		$downloads = $order->get_downloadable_items();
		// Check if there are downloads
		if ($downloads) {
			// Output a list of download files
			$output = '<h2>دانلود دوره خریداری شده ' . esc_html($product->get_name()) . '</h2>';
			$output .= '<ul>';
			foreach ($downloads as $download) {
				if($download['product_id'] != $atts['product_id']){
					continue;
				}
				$output .= '<li><a href="' . esc_url($download['download_url']) . '">' . esc_html($download['download_name']) . "</a></li>";
			}
			$output .= '</ul>';
		} else {
			$output = '<p>هیچ فایل دانلودی برای این دوره موجود نیست.</p>';
		}
	} else {
		$output = '<p>برای مشاهده فایل ها لطفا ابتدا دوره را خریداری کنید</p>';
	}

	return $output;
}
add_shortcode('course_woocommerce_product_downloads', 'course_woocommerce_product_downloads_shortcode');
brasero
sqlite3
postgres
firefox
chrome
chromium
emacs terminal
wezterm nigthly terminal
alacrity
tilix
dolphin
archivos
thunderbird
telegram
postman
discover
visual studio code 
la batalla por wesnoth
muon ssh clien
anydesk

una imagen es el empaquetador que contiene las dependencias el codigo y es lo que se comparte

un container son capas tras capas de imagenes

existen tres tipos de virtualizaciones en las VM virtualmachine
1.- para virtualizacion
en la paravirtualizacion intenta entregar la mayor cantidad de acceso del sistema anfitrion de su hardware a los cientes en el contenedor

2.- virtualizacion parcial
donde algunos componentes del hardware se virtualizan para en sistema operativo cliente

3.- virtualizacion completa:
donde absolutamente todos los componentes o hardware que esta utilizando el sistema operativo cliente son virtualizados de esta manera los sistemas operativos cliente no acceden en los absoluto al hardware

para todos los casos anteriores docker va a ser absolutamente superior y va a utilizar el kernel del sistema opetativo anfitrion y esto se traduce en rendimiento, los contenedores de docker parten casi que instantaneamente, obteniendo un rendimiento muy superior a todas las alternativas mencionadas anteriormente fin de la teoria


docker desktop es una maquina virtual se encuentra optimizada
corre linux
ejecuta containers
permite acceder al sistema de archivos y tambien a la red(interna y externa)

docker desktop no es una unica herramienta viene con otras herramientas que nos sirven para trabajar con nuestras imagenes y tambien con nuestros containers dentro de estas herramientes tenemos 

docker compose, docker cli ademas de otras herramientas

puede correr de manera nativa en windows con la herramienta WSL2(windows subsystem for linux)


existe una alternativa de instalacion para windows,linux y mac

para windows una sola opcion solamente es descargarlo y presionar siguiente siguiente siguente y listo

para mac existen dos alternatinas pulsar la de la derecha en la pagina web de docker

para linux docker ya tiene paquetes de instalacion pre compilados dependiendo de la version de linux que estes utilizando utiliza la alternativa que mas te funcione

que es dockerHUB: es un repositorio de imagenes o contenedores disponibles para comenzar a trabajar oficiales para utilizar

proceso para instalarlo
* docker images : devuelve un listado completo de todas las imagenes que hallamos descargado en nuestra maquina
donde repositorio te muestra el nombre de la imagen que se halla descargado, cada repositorio puede tener una o mas etiquetas con la version de la imagen

para descargar una imagen tenemos dos alternativas con el siguiente comando
1.-descargar la version que nosotros queremos
2.- no especificar nada esto va a descargar la ultima version de la imagen que queramos descargar
ejemplo:
* docker pull node

este comando te descargara cada una de las capas que componen la imagen de manera que si tenemos que descargar otra imagen y sus capas ya han sido descargadas por otro imagen las capas ya descargadas anteriormente ya no se volveran a descargar de esta manera de aprovecha espacio y tambien las distintas imagenes para optimizar un poco mas el espacio que estas van a utilizar en el disco duro

para descargar una version especifica de una imagen
* docker pull node:18

la imagen id es la misma que las otras versiones relativamente similares lo que cambia es la etiqueta de la version

para descargar la imagende mysql 
en mac se debe colocar 
* docker pull --platform linux/x86_64 mysql

normal es 

* docker pull mysql

tambien podemos indicar una version

* docker pull mysql:numeroversion

para eliminar una imagen en ejecucion el comando es

* docker image rm nombredelaimagen

la imagen de docker pull no necesita tantas configuraciones

Despues de descargar una imagen se procede a crear un contenedor

* docker create mongo (forma corta)

* docker container create mongo (forma larga) 

nos devuelve un id del contenedor (este id nos sirve para crear un contenedor)
el comando para ejecutar un contenedor es:

* docker start idContenedor (donde idcontenedor es el codigo id largo del contenedor) esto nos devuelve el id del contenedor nuevamente

* docker ps : este comando es como docker iamges pero se usa para ver los contenedores creados, cuando se crea un contenedor se le agrega un nombre de manera arbitraria al contenedor y ese nombre se puede usar en lugar del idcortocontenedor para eliminar el contenedor

* docker ps -a para ver todos los contenedores incluso los que no se estan ejecutando

para detener el contenedor se debe usar el comando

* docker stop idcortocontenedor

para asignar un nombre a un contenedor:

* docker create --name nombreContenedor esto nos devuelve el idlargo del contenedor indicando que ya se ha creado el contenedor

y como ya le hemos asignado un nombre al contenedor podemos iniciarlo con:

* Docker start nombreContenedorAsignado

para poder guardar datos dentro de un contenedor se debe mapear el puerto local al puerto del contenedor:

* docker create -p27017:27017 --name nombreContenedor nombreImagenBase donde lo que esta antes del : es el puerto de la maquina nuestra la maquina local y lo que esta despues del : es el puerto interno del contenedor, siempre asignale un puerto a cada contenedor creado por que si dejas que docker asigne un puerto los va a asignar por encima del puerto 50mil

con el comando 
docker logs nombreContenedor  puedes ver todos los logs que este nos muestra y tambien puedes verlo con

* docker logs --follow nombreContenedor la diferencia es que este se queda escuchando y mostrando los logs en tiempo real

el comando docker run hace tres cosas 
1.-descarga la imagen
2.-crea el contenedor
3.-inicia el contenedor

* ejemplo docker run mongo
docker run mongo

los siguientes dos comandos devulven el id del contenedor creado
docker run -d mongo este nos asigna un nombre arbitrariamente por docker
docker run --name nombreContenedor -p27017:27017 -d imagenbase este comando nos permite crear un contenedor mas personalizado

luego para ver el contenedor usa el comando 
* docker ps

configuracion del archivo dockerfile
tomar una aplicacion de docker un meterla dentro de un container
el archivo dockerfile no puede tener otro nombre se tiene que llamar dockerfile, este archivo se utiliza para que nosotros podamos construir nuestros containers, aqui nosotros vamos a escribir las instrucciones que necesita nuestro contenedor para poder crearse,m todas las imagenes que nosotros creemos siempre se tienen que basar en alguna otra imagen

ejemplo
* FROM node:etiquetaversion

RUN mkdir -p /home/app --esto es donde vamos a meter el codigo fuente de nuestra aplicacion, esta ruta no es una ruta fisita en nuestra maquina sino que es una ruta en el contenedor 

COPY . /home/app

EXPOSE 3000 ruta donde se va a ejecutar la aplicacion

CMD ["node","/home/app/index.js"]

ahora vamos a aprender a crear redes en docker

* docker ls : lista todas las redes existentes

* docker network create mired : este comando creara una nueva red dentro de docker este nos devolvera el id de la red creada

* docker network rm mired este comando elimina la red creada anteriormente

el siguiente comando recibe dos argumentos (nombreDadoPorMI,rutanodenosencontramos ) y se utiliza para construir contenedores en base a un archivo dockerfile

* docker build -t miapp:etiquetaversiondadapormi .

*docker create -P27017:27017 --name monguito --network mired -e MONGO_INITDB_ROOT_USERNAME=nico -e MONGO_INIT_DB_ROOT_PASSWORD=password mongo

ahora para colocar el contenedor de la aplicacion que nosotros acabamos de colocar dentro de una imagen

*docker create -p3000 --name chanchito --network mired miapp:1

*luego escribir docker ps -a

luego de hacer esto debemos arrancar los dos contenedores que creamos y que estan dentro de una misma red
sudo docker start monguito
sudo docker start chanchito

resumen de pasos para poder crear contenedores y tambien conectarlos
descargar la imagen
crear una red
crear el contenedor
	asignar puertos 
    asignar un nombre
    variables de entorno
    especificar la red
    indicar la imagen:consuetiqueta
todo esto por cada contenedor

para automatizar todo los pasos anteriores existe la herramienta docker compose
para esto debemos crear y editar un archivo con extension.yml

la estructura de este archivo es la siguiente
version:"3.9"
services:
	chanchito:
		build: .
        ports:
			-"3000:3000"
		links:
			-monguito
	monguito:
		imagen:mongo
        	ports:"27017:27017"
		environment:
			- MONGO_INITDB_ROOT_USERNAME=nico
			- MONGO_INITDB_ROOT_PASSWORD=password

ahora para ejecutar un archivo docker yml o docker compose se utiliza el siguiente comando:
docker compose up

luego verificas las imagenes creadadas con 

*docker images

con el comando 
docker compose down que es lo contrario de docker compose up, para eliminartodo lo que se creo anteriormente con docker compose up

para trabajar con volumenes vamos al final del archivo compose 
version:"3.9"
services:
	chanchito:
		build: .
        ports:
			-"3000:3000"
		links:
			-monguito
	monguito:
		imagen:mongo
        	ports:"27017:27017"
		environment:
			- MONGO_INITDB_ROOT_USERNAME=nico
			- MONGO_INITDB_ROOT_PASSWORD=password
		volumes:
			-mongo-data:/data/db
            # mysql -> var/lib/mysql
            # postgres -> var/lib/postgresql/data
volumes:
	mongo_data:

para crear multiples ambientes de desarrollo mientras estamos trabajando con docker
primero debemos crear un archivo con extension.dev ejemplo dockerfile.yml ya que el archivo que teniamos anterior mente quizas queramos usarlo para produccion ejemplo dockerfile.dev la estructura este este archivo es parecida al archivo dockerfile anterior con algunas diferencias

FROM node:18

RUN npm i -g nodemon
RUN mkdir -p /home/app

WORKDIR /home/app

EXPOSE 3000

CMD ["nodemon","index.js"]

ademas de este archivo demos crear un archivo compose para desarrollo tambien al cual llamaremos docker-compose-dev.yml con la siguiente estructura
version:"3.9"
services:
	chanchito:
		build: 
        context: .
        dockerfile:dockerfile.dev
        ports:
			-"3000:3000"
		links:
			-monguito
		volumes: 
			- .:/home/app
	monguito:
		imagen:mongo
        	ports:"27017:27017"
		environment:
			- MONGO_INITDB_ROOT_USERNAME=nico
			- MONGO_INITDB_ROOT_PASSWORD=password
		volumes:
			-mongo-data:/data/db
            # mysql -> var/lib/mysql
            # postgres -> var/lib/postgresql/data
volumes:
	mongo_data:

para provar el archivo que acabamos de construir utilizamos el siguiente comando, un archivo docker compose completamente customisado que no sea docker-compose.yml

docker compose -f docker-compose-dev.yml up
$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: success,
  dataType: dataType
});
sudo apt-get install alacritty
      //				tilix
		//				wezterm-nightly  --esto se consigue como un archivo app
// Loop through each item in the order
                        // This loop processes each individual item within the order to extract its specific info
                        foreach ($order->get_items() as $item_id => $item) {

                            // Retrieve the ID of the product associated with the current item in the order
                            $product_id = $item->get_product_id();
                            // Check if the current item's product ID matches the product ID we're processing in this loop iteration
                            if ($product_id == $pid) {
                                // Get the total price and subtotal price specific to this order item
                                // These values are specific to each item in the order, rather than the order as a whole
                                $line_total = wc_get_order_item_meta($item_id, '_line_total', true);
                                $line_subtotal = wc_get_order_item_meta($item_id, '_line_subtotal', true);
                                // ... extract other relevant data ... for now the amounts are ok
            
                                // Build the report entry for this product
                                array_push($order_data,[
                                    'order_id'         => $order_id,
                                    'customer_first'   => $order->get_billing_first_name(),
                                    'customer_last'    => $order->get_billing_last_name(),
                                    'order_created'    => date("d/m/Y",strtotime($order->get_date_created())),
                                    'email'            => $order->get_billing_email(),
                                    'phone'            => $order->get_billing_phone(),
                                    'orders_status'    => $order_status,
                                    'invoice_no'       => $formatted_invoice_number,
                                    'credit_note'      => $credit_note,
                                    'invoice_date'     => $invoice_date,
                                    'credit_note_date' => $credit_note_date,//date("d/m/Y",strtotime($credit_note_date)),
                                    'wooco_currency'   => $currency_symbol,
                                    'gross'            => round($line_subtotal,2),
                                    'discount'         => round($order->get_total_discount(),2),
                                    'net_total'        => round($line_total,2),
                                    'course_id'        => self::get_product_sku($pid),
                                    'course_start'     => $course_start,
                                    'course_ends'      => $course_end,
                                    'student_id'       => $assign_student_id_value
                                ]);
                            }  
                        }
// func that is going to set our title of our customer magically
function w2w_customers_set_title( $data , $postarr ) {

    // We only care if it's our customer
    if( $data[ 'post_type' ] === 'w2w-customers' ) {

        // get the customer name from _POST or from post_meta
        $customer_name = ( ! empty( $_POST[ 'customer_name' ] ) ) ? $_POST[ 'customer_name' ] : get_post_meta( $postarr[ 'ID' ], 'customer_name', true );

        // if the name is not empty, we want to set the title
        if( $customer_name !== '' ) {

            // sanitize name for title
            $data[ 'post_title' ] = $customer_name;
            // sanitize the name for the slug
            $data[ 'post_name' ]  = sanitize_title( sanitize_title_with_dashes( $customer_name, '', 'save' ) );
        }
    }
    return $data;
}
add_filter( 'wp_insert_post_data' , 'w2w_customers_set_title' , '99', 2 );
function update_post( $post_id ) {
   $post = array(
     'ID'         => $post_id,
     'post_title' => '#'.$post_id,
     'post_name'  => $post_id,
   );
   wp_update_post( $post );
   update_post_meta($post_id, 'order', $post_id);
}
add_action('save_post_booking', 'update_post', 20);
/*
* Plugin Name: Course Taxonomy
* Description: A short example showing how to add a taxonomy called Course.
* Version: 1.0
* Author: developer.wordpress.org
* Author URI: https://codex.wordpress.org/User:Aternus
*/

function wporg_register_taxonomy_course() {
	 $labels = array(
		 'name'              => _x( 'Courses', 'taxonomy general name' ),
		 'singular_name'     => _x( 'Course', 'taxonomy singular name' ),
		 'search_items'      => __( 'Search Courses' ),
		 'all_items'         => __( 'All Courses' ),
		 'parent_item'       => __( 'Parent Course' ),
		 'parent_item_colon' => __( 'Parent Course:' ),
		 'edit_item'         => __( 'Edit Course' ),
		 'update_item'       => __( 'Update Course' ),
		 'add_new_item'      => __( 'Add New Course' ),
		 'new_item_name'     => __( 'New Course Name' ),
		 'menu_name'         => __( 'Course' ),
	 );
	 $args   = array(
		 'hierarchical'      => true, // make it hierarchical (like categories)
		 'labels'            => $labels,
		 'show_ui'           => true,
		 'show_admin_column' => true,
		 'query_var'         => true,
		 'rewrite'           => [ 'slug' => 'course' ],
	 );
	 register_taxonomy( 'course', [ 'post' ], $args );
}
add_action( 'init', 'wporg_register_taxonomy_course' );
<?php
$args = array(
	'post_type'      => 'product',
	'posts_per_page' => 10,
);
$loop = new WP_Query($args);
while ( $loop->have_posts() ) {
	$loop->the_post();
	?>
	<div class="entry-content">
		<?php the_title(); ?>
		<?php the_content(); ?>
	</div>
	<?php
}
mv mover y tambien sirve para cambiar el nombre
mv nombrearchivoacambiar nuevomobre.ext && mv nuevonombre.ext /rutadondeguardarlo
principio de la tabla:
[
  'class' => 'yii\grid\ActionColumn',
            'contentOptions' => ['style' => 'text-align:center; width:2%; vertical-align:middle;'],
 ]
Final de la tabla:
'class' => 'yii\grid\ActionColumn',
            'contentOptions' => ['style' => 'text-align:center; width:2%; vertical-align:middle;'],
  
listas:
'id_reporte' => [
            'attribute' => 'id_reporte',
            'headerOptions' => ['style' => 'text-align:center; width:5%;text-color:white;'],
            'contentOptions' => ['style' => 'text-align:center; vertical-align:middle; white-space: pre-line;'],
            'label' => 'Tipo de Reporte',
            'filter' => app\models\Reportes::lista(),
            'format' => 'html',
            'value' => function ($data) {
                $s = app\models\Reportes::find()->where(['id_reporte' => $data->id_reporte])->one();
                $desc_reporte = ($s) ? $s->desc_reporte : '';
                $desc_reporte = nl2br($desc_reporte);
                $desc_reporte = wordwrap($desc_reporte, 20, "<br>\n");
                return $desc_reporte;
            }
        ],

campos:
'attribute' => 'fecha_hora',
            'value' => 'fecha_hora',
            'headerOptions' => ['style' => 'text-align:center; width:10%;text-color:white;'],
            'contentOptions' => ['style' => 'text-align:center; vertical-align:middle;'],
add_action('wp_ajax_add_product_to_cart', 'add_product_to_cart_ajax');
add_action('wp_ajax_nopriv_add_product_to_cart', 'add_product_to_cart_ajax');

function add_product_to_cart_ajax() {
    $product_id = isset($_POST['product_id']) ? intval($_POST['product_id']) : 0;
    $quantity = isset($_POST['quantity']) ? intval($_POST['quantity']) : 1;

    if ($product_id > 0) {
        WC()->cart->add_to_cart($product_id, $quantity);
        wp_send_json('Product added to cart');
    } else {
        wp_send_json('Invalid product');
    }
}

//second custom code to direct checkout.

add_filter('woocommerce_add_to_cart_redirect', 'custom_add_to_cart_redirect');

function custom_add_to_cart_redirect($url) {
    global $woocommerce;
    $checkout_url = wc_get_checkout_url();

    return $checkout_url;
}
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="style.css">

  </head>

  <body>
      <button onclick="changeColor()">Repaint!</button>
  </body>
  
      <script>
        function getRandomColor(){
          let letters = '0123456789ABCDEF';
          let color = '#';
          for (let i = 0; i < 6; i++) {
            color += letters[Math.floor(Math.random() * 16)];
          }
          return color;
        }
        function changeColor(){
          let newColor = getRandomColor();
          document.body.style.backgroundColor = newColor;
        }
    </script>
  
</html>
function custom_product_price($price, $product) {
    // Change the price for product with ID 46
    if ($product && $product->get_id() === 46) {
        $price = '500.00'; // Set the desired price
    }

    return $price;
}

add_filter('woocommerce_get_price_html', 'custom_product_price', 10, 2);
add_filter('woocommerce_cart_item_price', 'custom_product_price', 10, 2);
add_filter('woocommerce_cart_item_subtotal', 'custom_product_price', 10, 3);
    
// Form to add a record   to display products dropdown v1.2 starts
echo '<form id="add-record-form" style="display: flex; flex-direction: row;">
<div class="main_container" style="margin-right: 20px;">
    <label for="product_name">Product Name:</label>
    <select id="product_name" name="product_name">';
    
// Retrieve product names from the database
$query = new WP_Query(array(
    'post_type' => 'product',
    'post_status' => 'publish',
    'posts_per_page' => '-1'
));

if ($query->have_posts()) :
    while ($query->have_posts()) : $query->the_post();
        echo '<option value="' . get_the_title() . '">' . get_the_title() . '</option>';
    endwhile;
    wp_reset_postdata();
else:
    echo '<option value="">No products found</option>';
endif;

echo '</select>
</div>';

// v1.2 stops
// Modify quantity input and add remove icon
add_filter('woocommerce_checkout_cart_item_quantity', 'bbloomer_checkout_item_quantity_input', 9999, 3);

function bbloomer_checkout_item_quantity_input($product_quantity, $cart_item, $cart_item_key) {
    $product = apply_filters('woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key);
    $product_id = apply_filters('woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key);

    if (!$product->is_sold_individually()) {
        $product_quantity = woocommerce_quantity_input(array(
            'input_name'  => 'shipping_method_qty_' . $product_id,
            'input_value' => $cart_item['quantity'],
            'max_value'   => $product->get_max_purchase_quantity(),
            'min_value'   => '0',
        ), $product, false);

        // Add remove icon
        $product_quantity .= '<a href="#" class="remove-product" data-product-key="' . $cart_item_key . '">x</a>';

        $product_quantity .= '<input type="hidden" name="product_key_' . $product_id . '" value="' . $cart_item_key . '">';
    }

    return $product_quantity;
}

// Add JavaScript to handle product removal
add_action('wp_footer', 'add_product_removal_script');

function add_product_removal_script() {
    ?>
    <script>
        document.addEventListener('click', function (event) {
            if (event.target.classList.contains('remove-product')) {
                event.preventDefault();
                const productKey = event.target.getAttribute('data-product-key');
                const form = event.target.closest('form');

                if (form && productKey) {
                    // Remove the product from the cart via AJAX
                    jQuery.ajax({
                        type: 'POST',
                        url: wc_checkout_params.ajax_url,
                        data: {
                            action: 'remove_product_from_cart',
                            product_key: productKey
                        },
                        success: function (response) {
                            // Reload the checkout page to reflect the updated cart
                            window.location.reload();
                        }
                    });
                }
            }
        });
    </script>
    <?php
}
add_action('wp_ajax_remove_product_from_cart', 'remove_product_from_cart');

function remove_product_from_cart() {
    if (isset($_POST['product_key'])) {
        $product_key = sanitize_text_field($_POST['product_key']);
        WC()->cart->remove_cart_item($product_key);
        echo 'success';
    }

    wp_die();
}


// Detect Quantity Change and Recalculate Totals
add_action('woocommerce_checkout_update_order_review', 'bbloomer_update_item_quantity_checkout');

function bbloomer_update_item_quantity_checkout($post_data) {
    parse_str($post_data, $post_data_array);
    $updated_qty = false;
    $updated_remove = false;

    foreach ($post_data_array as $key => $value) {
        if (substr($key, 0, 20) === 'shipping_method_qty_') {
            $id = substr($key, 20);
            WC()->cart->set_quantity($post_data_array['product_key_' . $id], $post_data_array[$key], false);
            $updated_qty = true;
        } elseif (substr($key, 0, 15) === 'remove_product_') {
            $cart_item_key = substr($key, 15);
            WC()->cart->remove_cart_item($cart_item_key);
            $updated_remove = true;
        }
    }

    if ($updated_qty || $updated_remove) {
        WC()->cart->calculate_totals();
    }
}
<?php

require 'vendor/autoload.php';

// Create a client with a base URI

$client = new \GuzzleHttp\Client(['base_uri' => 'https://rbt5.namnguyen68.repl.co']);

// Send a request

$response = $client->request('GET', 'html/begin');

$body = $response->getBody();

echo $body;

// Send a request

$response = $client->request('GET', 'title/a');

$body = $response->getBody();

echo $body;

// Send a request

$response = $client->request('GET', 'body/begin');

$body = $response->getBody();

echo $body;

?>

<?php

// Create a client with a base URI

$client = new \GuzzleHttp\Client(['base_uri' => 'https://rbt5.namnguyen68.repl.co']);

// Send a request

$response = $client->request('GET', 'html/end');

$body = $response->getBody();

echo $body;

?>

alt + z = ajuta la lineas de codigo para que se vea la linea completa en la pantalla
ctrl + shift + a= comenta varias lineas de cdigo
ctrl + f = buscar en el codigo o buscar en archivos debo seleccionar el lugar en donde voy a buscar
ctrl + shift + p = abre la paleta de comandos
DOCTYPE: html
  html lang="en"
    head
    #text: ⏎␣␣
      title
      #text: Sample page
      #text: ⏎␣
    #text: ⏎␣
    body
    #text: ⏎␣␣
      h1
      #text: Sample page
      #text: ⏎␣␣
      p
        #text: This is a
        a href="demo.html"
      	 #text: simple
      #text: sample.
      #text: ⏎␣␣
      #comment: this is a comment
     #text: ⏎␣⏎
$my_repeater = get_field('cosa_facciamo_home');

            // Verifica se il campo ripetitore esiste
            if ($my_repeater) :
                
                // Loop attraverso le istanze del campo ripetitore
                foreach ($my_repeater as $item) :
                    // Recupera il campo di gruppo all'interno del ripetitore
                    $my_group = $item['cosa_facciamo_items'];

                    // Recupera i valori all'interno del campo di gruppo
                    $field_value_1 = $my_group['titolo_cosa-facciamo'];
                    $field_value_2 = $my_group['testo_cosa_facciamo'];

                    // Puoi ora utilizzare questi valori come desideri
                    echo 'Valore del campo personalizzato 1: ' . $field_value_1 . '<br>';
                    echo 'Valore del campo personalizzato 2: ' . $field_value_2 . '<br>';
                endforeach;
            endif;
function edit_button_shortcode() {
    // Check if the user is logged in
    if (is_user_logged_in()) {
        global $wpdb;
        $user_id = get_current_user_id();

        // Check if the user's ID exists in the wp_fluentform_submissions table
        $results = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}fluentform_submissions WHERE user_id = %d", $user_id));

        // If the user's ID exists in the table, display the "Edit" button
        if ($results) {
            return '<a href="YOUR_EDIT_URL_HERE" class="edit-button">Edit</a>';
        }
    }
    return '';  // If the user is not logged in or their ID doesn't exist in the table, return an empty string
}
add_shortcode('edit_button', 'edit_button_shortcode');
brew install shivammathur/php/php@8.2

brew unlink php@7.4 && brew link --force --overwrite php@8.2

add_filter( 'woocommerce_checkout_cart_item_quantity', 'bbloomer_checkout_item_quantity_input', 9999, 3 );
  
function bbloomer_checkout_item_quantity_input( $product_quantity, $cart_item, $cart_item_key ) {
   $product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
   $product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );
   if ( ! $product->is_sold_individually() ) {
      $product_quantity = woocommerce_quantity_input( array(
         'input_name'  => 'shipping_method_qty_' . $product_id,
         'input_value' => $cart_item['quantity'],
         'max_value'   => $product->get_max_purchase_quantity(),
         'min_value'   => '0',
      ), $product, false );
      $product_quantity .= '<input type="hidden" name="product_key_' . $product_id . '" value="' . $cart_item_key . '">';
   }
   return $product_quantity;
}
 
// ----------------------------
// Detect Quantity Change and Recalculate Totals
 
add_action( 'woocommerce_checkout_update_order_review', 'bbloomer_update_item_quantity_checkout' );
 
function bbloomer_update_item_quantity_checkout( $post_data ) {
   parse_str( $post_data, $post_data_array );
   $updated_qty = false;
   foreach ( $post_data_array as $key => $value ) {   
      if ( substr( $key, 0, 20 ) === 'shipping_method_qty_' ) {         
         $id = substr( $key, 20 );   
         WC()->cart->set_quantity( $post_data_array['product_key_' . $id], $post_data_array[$key], false );
         $updated_qty = true;
      }     
   }  
   if ( $updated_qty ) WC()->cart->calculate_totals();
}
define( 'RECOVERY_MODE_EMAIL', 'myemail@example.com' );
add_filter('woocommerce_add_to_cart_redirect', 'custom_add_to_cart_redirect');

function custom_add_to_cart_redirect($url) {
    global $woocommerce;
    $checkout_url = wc_get_checkout_url();

    return $checkout_url;
}
function custom_checkout_text_change( $translated_text, $text, $domain ) {
    if ( $domain === 'woocommerce' && $text === 'Billing details' ) {
        $translated_text = 'Billing Details';
    }
    return $translated_text;
}
add_filter( 'gettext', 'custom_checkout_text_change', 20, 3 );
for "laravel-mix": "^6.0.49",

"scripts": {
    "dev": "npm run development",
    "development": "mix",
    "watch": "mix watch",
    "watch-poll": "mix watch -- --watch-options-poll=1000",
    "hot": "mix watch --hot",
    "prod": "npm run production",
    "production": "mix --production"
},




"scripts": {
    "dev": "npm run development",
    "development": "mix",
    "watch": "mix watch",
    "watch-poll": "mix watch -- --watch-options-poll=1000",
    "hot": "mix watch --hot",
    "prod": "npm run production",
    "production": "mix --production"
},
require_once __DIR__ . '/vendor/autoload.php';

$klein = new \Klein\Klein();

$klein->respond('GET', 'name/[:name]', function ($request) {
    return 'Hello ' . $request->name;
});

$klein->dispatch();
function bulk_modifier_page() {
    global $wpdb;

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['csv_file'])) {
        // Check if a CSV file is uploaded successfully
        if ($_FILES['csv_file']['error'] == UPLOAD_ERR_OK) {
            $file = $_FILES['csv_file']['tmp_name'];

            // Read the CSV file
            $csv_data = array_map('str_getcsv', file($file));
            $csv_headers = array_shift($csv_data); // Get headers

            // Define the mapping of CSV columns to database columns for wp_za_groups table
            $group_column_mapping = array(
                'group_name' => 'title',
                'priority' => 'priority',
                'apply_to' => 'apply_to',
                'author_id' => 'admin_id',
                'created_at' => 'created_at',
                'created_at_gmt' => 'created_at_gmt',
                'updated_at' => 'updated_at',
                'updated_at_gmt' => 'updated_at_gmt'
            );

            // Define the mapping of CSV columns to database columns for wp_za_types table
            $type_column_mapping = array(
                'title_name' => 'title',
                'type' => 'type',
                'status' => 'status',
                'description' => 'description',
                'required' => 'required',
                'display_description_on_expansion' => 'display_description_on_expansion',
                'hide_description' => 'hide_description',
                'tooltip_description' => 'tooltip_description',
                'created_at' => 'created_at',
                'created_at_gmt' => 'created_at_gmt',
                'updated_at' => 'updated_at',
                'updated_at_gmt' => 'updated_at_gmt'
            );

            // Define the mapping of CSV columns to database columns for wp_za_values table
            $value_column_mapping = array(
                'addons_title' => 'title',
                'price' => 'price',
                'description_value' => 'description',
                'sku' => 'sku',
            );

            // Insert data into the wp_za_groups, wp_za_types, wp_za_values, wp_za_products_to_groups, and wp_za_categories_to_groups tables
            foreach ($csv_data as $row) {
                // Prepare data for wp_za_groups table
                $group_data = array();
                foreach ($csv_headers as $key => $header) {
                    if (isset($group_column_mapping[$header])) {
                        $group_data[$group_column_mapping[$header]] = $row[$key];
                    }
                }

                // Set default values for created_at, created_at_gmt, updated_at, updated_at_gmt
                $group_data['created_at'] = current_time('mysql');
                $group_data['created_at_gmt'] = current_time('mysql', true);
                $group_data['updated_at'] = current_time('mysql');
                $group_data['updated_at_gmt'] = current_time('mysql', true);

                // Insert data into the wp_za_groups table
                $wpdb->insert($wpdb->prefix . 'za_groups', $group_data);
                $group_id = $wpdb->insert_id; // Get the group ID

                // Prepare data for wp_za_types table
                $type_data = array(
                    'group_id' => $group_id,
                    'step' => 0, // Default value
                    'accordion' => 'open', // Default value
                );

                // Map CSV columns to database columns for wp_za_types table and set default values
                foreach ($csv_headers as $key => $header) {
                    if (isset($type_column_mapping[$header])) {
                        if ($header === 'status' && !isset($type_data['status'])) {
                            // Set default status if not present in CSV
                            $type_data['status'] = 'enable';
                        } elseif ($header === 'description' && !isset($type_data['description'])) {
                            // Set default description if not present in CSV
                            $type_data['description'] = 'none';
                        } elseif ($header === 'required' && !isset($type_data['required'])) {
                            // Set default required value if not present in CSV
                            $type_data['required'] = 0;
                        } elseif ($header === 'display_description_on_expansion' && !isset($type_data['display_description_on_expansion'])) {
                            // Set default display_description_on_expansion value if not present in CSV
                            $type_data['display_description_on_expansion'] = 0;
                        } elseif ($header === 'hide_description' && !isset($type_data['hide_description'])) {
                            // Set default hide_description value if not present in CSV
                            $type_data['hide_description'] = 0;
                        } elseif ($header === 'tooltip_description' && !isset($type_data['tooltip_description'])) {
                            // Set default tooltip_description value if not present in CSV
                            $type_data['tooltip_description'] = 0;
                        } else {
                            $type_data[$type_column_mapping[$header]] = $row[$key];
                        }
                    }
                }

                // Set default values for created_at, created_at_gmt, updated_at, updated_at_gmt
                $type_data['created_at'] = current_time('mysql');
                $type_data['created_at_gmt'] = current_time('mysql', true);
                $type_data['updated_at'] = current_time('mysql');
                $type_data['updated_at_gmt'] = current_time('mysql', true);

                // Insert data into the wp_za_types table
                $wpdb->insert($wpdb->prefix . 'za_types', $type_data);
                $type_id = $wpdb->insert_id; // Get the type ID

                // Prepare data for wp_za_values table
                $value_data = array(
                    'type_id' => $type_id,
                    'step' => $wpdb->get_var("SELECT COUNT(*) FROM " . $wpdb->prefix . "za_values WHERE type_id = $type_id") + 1, // Increment step
                );

                // Map CSV columns to database columns for wp_za_values table and set default values
                foreach ($csv_headers as $key => $header) {
                    if (isset($value_column_mapping[$header])) {
                        if ($header === 'description_value' && !isset($value_data['description'])) {
                            // Set default description if not present in CSV
                            $value_data['description'] = 'no value';
                        } elseif ($header === 'checked' && !isset($value_data['checked'])) {
                            // Set default checked value if not present in CSV
                            $value_data['checked'] = 0;
                        } elseif ($header === 'hide_description' && !isset($value_data['hide_description'])) {
                            // Set default hide_description value if not present in CSV
                            $value_data['hide_description'] = 0;
                        } else {
                            $value_data[$value_column_mapping[$header]] = $row[$key];
                        }
                    }
                }

                // Set default values for created_at, created_at_gmt, updated_at, updated_at_gmt
                $value_data['created_at'] = current_time('mysql');
                $value_data['created_at_gmt'] = current_time('mysql', true);
                $value_data['updated_at'] = current_time('mysql');
                $value_data['updated_at_gmt'] = current_time('mysql', true);

                // Insert data into the wp_za_values table
                $wpdb->insert($wpdb->prefix . 'za_values', $value_data);
                $value_id = $wpdb->insert_id; // Get the value ID

                // Prepare data for wp_za_products_to_groups table
                $product_names = explode(',', $row[array_search('products_name', $csv_headers)]);
                foreach ($product_names as $product_name) {
                    $product_id = $wpdb->get_var("SELECT ID FROM " . $wpdb->posts . " WHERE post_title = '$product_name' AND post_type = 'product'");

                    if ($product_id) {
                        $product_to_group_data = array(
                            'product_id' => $product_id,
                            'group_id' => $group_id,
                        );

                        // Insert data into the wp_za_products_to_groups table
                        $wpdb->insert($wpdb->prefix . 'za_products_to_groups', $product_to_group_data);
                    }
                }

                // Prepare data for wp_za_categories_to_groups table
                $category_names = explode(',', $row[array_search('category_names', $csv_headers)]);
                foreach ($category_names as $category_name) {
                    // Get the category ID based on the category name
                    $category_id = $wpdb->get_var($wpdb->prepare("SELECT term_id FROM $wpdb->terms WHERE name = %s", $category_name));

                    if ($category_id) {
                        $category_to_group_data = array(
                            'category_id' => $category_id,
                            'group_id' => $group_id,
                        );

                        // Insert data into the wp_za_categories_to_groups table
                        $wpdb->insert($wpdb->prefix . 'za_categories_to_groups', $category_to_group_data);
                    }
                }
            }

            echo '<div class="updated"><p>Data imported successfully!</p></div>';
        } else {
            echo '<div class="error"><p>Error uploading CSV file.</p></div>';
        }
    }

    // Display the upload form
    ?>
   
    <div class="wrap">
        <h2>Bulk Modifier Upload</h2>
        <form method="post" action="" enctype="multipart/form-data">
            <input type="file" name="csv_file">
            <input type="submit" class="button button-primary" value="Upload CSV & Apply">
        </form>
    </div>
    
    <?php
}
aptitude search bash-completion
           //   bash sh-sequence-bash-completion
Ejecutamos este comando -basta con copy&paste- en la consola "sudo gedit /etc/bash.bashrc".
Descomentamos las tres últimas líneas de ese fichero que se ha abierto, quedando así:
if [ -f /etc/bashcompletion ]; then
. /etc/bashcompletion
fi

Una vez esté todo como el código que os mostramos podremos guardar de nuevo el fichero. Un apunte: antes de la primera línea hay un comentario que podéis dejar o eliminar. Yo personalmente os diría que no lo eliminéis para que sepáis para que sirve ese fichero en un futuro. Probad a comenzar a escribir un comando y pulsad TAB, veréis como se completa el comando automáticamente.

Un ejemplo muy básico para probar esta función es escribir "cd /h" y pulsar el tabulador, automáticamente debería aparecer "cd /home" en pantalla. Le dais a enter y ya tendréis el comando ejecutado.
https://code.visualstudio.com/docs/editor/tasks#vscode
<script type="application/ld+json">
    "@context" : "https://schema.org/",
    {{ $slot }}
</script>
function remove_core_updates(){
global $wp_version;
return (object) array(
'last_checked' => time(),
'version_checked' => $wp_version,
'updates' => array()
);
}
add_filter('pre_site_transient_update_core', 'remove_core_updates');
add_filter('pre_site_transient_update_plugins', 'remove_core_updates');
add_filter('pre_site_transient_update_themes', 'remove_core_updates');
{
    "editor.fontFamily": "Fira Code",
    "editor.fontLigatures": true,
    "window.zoomLevel": 1,
    "git.openRepositoryInParentFolders": "never",
    "security.workspace.trust.untrustedFiles": "open",
    "workbench.iconTheme": "material-icon-theme",
    "prettier.bracketSameLine": true,
    "editor.wordWrap": "on",
    "screencastMode.fontSize":20,
    "editor.tabSize": 2,
    "screencastMode.verticalOffset": 3,
    "settingsSync.ignoredExtensions": [
        "ms-ceintl.vscode-language-pack-es"
    ],
    "application.shellEnvironmentResolutionTimeout": 25,
    "workbench.colorTheme": "Night Owl",
    "launch": {
        "configurations": [
            
 
        ]
    }
}
Html:
Nota;para colocar el codigo Html solamente tipea !.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <div id="app">
    {{mensaje}}
    <hr>
    <input type="button" @click="mostrar=!mostrar" value="Click">
    <input v-if="mostrar" v-model="mensaje2">
  </div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
</body>
</html>

JavaScript:
const app = new Vue ({
el:"#app",
  data: {
    mensaje:"Aja",
    mensaje2:"Hola Bomboncito",
    mostrar:false
  }
})
Salida:
add_action( 'woocommerce_product_options_pricing', 'genius_set_percentage_discount' );
 
function genius_set_percentage_discount() {
   global $product_object;
   woocommerce_wp_select(
      array(
         'id' => '_pc_discount',
         'value' => get_post_meta( $product_object->get_id(), '_pc_discount', true ),
         'label' => 'Discount %',
         'options' => array(
            '0' => '0',
            '10' => '10',
            '25' => '25',
            '50' => '50',
         ),
      )
   );
}
 
add_action( 'save_post_product', 'genius_save_percentage_discount' );
   
function genius_save_percentage_discount( $product_id ) {
    global $typenow;
    if ( 'product' === $typenow ) {
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
      if ( isset( $_POST['_pc_discount'] ) ) {
            update_post_meta( $product_id, '_pc_discount', $_POST['_pc_discount'] );
        }
    }
}
  
add_filter( 'woocommerce_get_price_html', 'genius_alter_price_display', 9999, 2 );
  
function genius_alter_price_display( $price_html, $product ) {
    if ( is_admin() ) return $price_html;
    if ( '' === $product->get_price() ) return $price_html;
    if ( get_post_meta( $product->get_id(), '_pc_discount', true ) && get_post_meta( $product->get_id(), '_pc_discount', true ) > 0 ) {
        $orig_price = wc_get_price_to_display( $product );
        $price_html = wc_format_sale_price( $orig_price, $orig_price * ( 100 - get_post_meta( $product->get_id(), '_pc_discount', true ) ) / 100 );
    }
    return $price_html;
}
  
add_action( 'woocommerce_before_calculate_totals', 'genius_alter_price_cart', 9999 );
  
function genius_alter_price_cart( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
        $product = $cart_item['data'];
      if ( get_post_meta( $product->get_id(), '_pc_discount', true ) && get_post_meta( $product->get_id(), '_pc_discount', true ) > 0 ) {
           $price = $product->get_price();
           $cart_item['data']->set_price( $price * ( 100 - get_post_meta( $product->get_id(), '_pc_discount', true ) ) / 100 );
      }
    }
}
<?php include 'FILENAME';?>
<?php Pjax::begin(); 
    $gridColumns = [
[
                'attribute' => 'avance',
                'headerOptions' => ['style' => 'text-align:center; '],
                'contentOptions' => ['style' => 'text-align:center; vertical-align:middle;'],
                'format' => 'raw',
                'value' => function($model) {
                    $string = $model->observacion;
                    $wrappedString = wordwrap($string, 40, "\n");
                    return '<div style="max-height: 80px; overflow: auto; max-width: 200px;">' . nl2br($wrappedString) . '</div>';
                },
                
            ],
            [
                'attribute' => 'observacion',
                'headerOptions' => ['style' => 'text-align:center; '],
                'contentOptions' => ['style' => 'text-align:center; vertical-align:middle;'],
                'format' => 'raw',
                'value' => function($model) {
                    $string = $model->observacion;
                    $wrappedString = wordwrap($string, 40, "\n");
                    return '<div style="max-height: 80px; overflow: auto; max-width: 200px;">' . nl2br($wrappedString) . '</div>';
                },
            ],
]; ?>
    Route::get('/notification', function () {
        $documentManagerFiles = DocumentManagerFile::where('ocr_project_id', 1)->where('revision', '>', 0 )->take(5)->get();
        // dd($documentManagerFiles);
        return (new DocumentManagerFileCreatedNotification($documentManagerFiles))
                    ->toMail(Auth::user());
    });
response = zoho.people.getRecords("P_Department");
$to = "recipient@example.com";
$subject = "Test Email";
$message = "This is a test email sent using PHP's mail() function.";
$headers = "From: sender@example.com";

if (mail($to, $subject, $message, $headers)) {
    echo "Email sent successfully.";
} else {
    echo "Email sending failed.";
}
    <?php
    $file_data = "Stuff you want to add\n";
    $file_data .= file_get_contents('database.txt');
    file_put_contents('database.txt', $file_data);
    ?>
$fp_source = fopen('database.txt', 'r');
$fp_dest = fopen('database_temp.txt', 'w'); // better to generate a real temp filename
fwrite($fp_dest, 'new content');
while (!feof($fp_source)) {
    $contents .= fread($fp_source, 8192);
    fwrite($fp_dest, $contents);
}
fclose($fp_source);
fclose($fp_dest);
unlink('database.txt');
rename('database_temp.txt','database.txt');
<?php
// error_reporting(E_ALL);
// ini_set('display_errors', 1);
error_reporting(0);
date_default_timezone_set('Asia/Kolkata');
function get($url)
{
  // Initialize a CURL session.
  $ch = curl_init();

  // Return Page contents.
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

  //grab URL and pass it to the variable.
  curl_setopt($ch, CURLOPT_URL, $url);

  $result = curl_exec($ch);

  return $result;
}

$user = $_POST['user'];
$offer = $_POST['offer'];
$cname = $_POST['cname'];
$event = $_POST['event'];

$rp = get('https://nextpower.cashinmedia.in/api/v1/checkRefer/0a51d09c-f329-4436-89d5-bdbb52bea07c/' . $offer . '?number=' . $user . '');

// JSON response from the URL
$response = $rp;

// Decode the JSON response
$response_data = json_decode($response, true);

$totalClicks = $response_data['clicks'];

$count = $response_data['count'];

// Extract the 'data' section from the response
$data = $response_data['data'];

// Check if there's any data to display
if (count($data) > 0) {
  // Echo the table header
//     echo '<table border="1">
//         <tr>
//             <th>Click</th>
//             <th>User Amount</th>
//             <th>Refer Amount</th>
//             <th>User</th>
//             <th>Refer</th>
//             <th>Event</th>
//             <th>Status</th>
//             <th>Payment Status</th>
//             <th>Payment Message</th>
//             <th>Created At</th>
//         </tr>';

  //     // Loop through each data entry and display in table rows
//     foreach ($data as $entry) {
//     $userEncoded = preg_replace('/\d{5}(?=\d{4}$)/', 'xxxxx', $entry['user']);

  //     echo '<tr>';
//     echo '<td>' . $entry['click'] . '</td>';
//     echo '<td>' . $entry['userAmount'] . '</td>';
//     echo '<td>' . $entry['referAmount'] . '</td>';
//     echo '<td>' . $userEncoded . '</td>'; // Display encoded user
//     echo '<td>' . $entry['refer'] . '</td>';
//     echo '<td>' . $entry['event'] . '</td>';
//     echo '<td>' . $entry['status'] . '</td>';
//     echo '<td>' . $entry['referPaymentStatus'] . '</td>';
//     echo '<td>' . $entry['payMessage'] . '</td>';
//     echo '<td>' . $entry['createdAt'] . '</td>';
//     echo '</tr>';
// }

  //     // Close the table
//     echo '</table>';
// } else {
//     // If there's no data, show a JavaScript alert
//     echo '<script>alert("No data found.");</script>';
// }
  ?>
  <html lang="en" dir="ltr">


  <head>
    <meta charset="utf-8">
    <title>FokatCash</title>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600&display=swap">
    <link rel="stylesheet" href="report.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" charset="utf-8"></script>
    <meta name="viewport" content="width=device-width">
  </head>
  <style>
    .data-table td,
    .data-table th {
      font-size: 17px;
      /* Adjust the value as needed */
    }

    .credited {
      color: #FFA500;
      /* Orange color */
    }
  </style>

  <body>
    <center>
      <div class="login-form">
        <h1>
          <font color='#0f0f0f'>REPORT
        </h1>
        <center>

  </body>

  </html>

  <div class="statics">
    <center><br>
      <fieldset>Refferer:
        <?php echo $user; ?>
        <hr>Camp:
        <?php echo $cname; ?>
        <hr>Total Clicks:
        <?php echo $totalClicks; ?>
        <hr>Total Conversions: <span id="totalLeads">Calculating...</span> <!-- Placeholder for total leads -->
        <hr>
        <font color="#008000"> Cashback Sent: Rs. <span id="totalAcceptedReferAmount">Calculating...</span> </font>
        <!-- Placeholder for total refer amount -->
        <hr>
        <font color="#FFA500">Pending Cashback : Rs.<span id="totalPendingReferAmount">Calculating...</span></font>
        <hr>
      </fieldset><br><br>
      <table class="data-table">
        <tr>

          <th>Camp Name</th>
          <th>Refer Amount</th>
          <!--<th>Refer Status</th>-->
          <th>Cashback Status</th>
          <th>Time</th>
        </tr>
        <?php
        foreach ($data as $entry) {
          $userEncoded = preg_replace('/\d{5}(?=\d{4}$)/', 'xxxxx', $entry['user']);
          $dateTime = new DateTime($entry['createdAt']);

          // Convert to IST timezone
          $dateTime->setTimezone(new DateTimeZone('Asia/Kolkata'));

          // Format the time in desired format
          $istTimeFormatted = $dateTime->format('Y-m-d H:i:s');

          if ($entry['referPaymentStatus'] === 'REJECTED' || $entry['referPaymentStatus'] === 'BLOCKED') {
            continue;
          }

          if ($entry['referPaymentStatus'] == 'ACCEPTED' || $entry['referPaymentStatus'] == 'UNKNOWN' || $entry['referPaymentStatus'] == 'FAILURE') {
            $cashbackStatus = '<b><span style="color: #198754;">Credited</span></b>';
          } elseif ($entry['referPaymentStatus'] == 'PENDING') {
            $cashbackStatus = '<b><span style="color: #FFA500;">Processing</span></b>';
          } else {
            // Handle other cases or set a default value for $cashbackStatus
            // For example: $cashbackStatus = 'Unknown Status';
            $cashbackStatus = $entry['referPaymentStatus'];
          }


          if ($entry['referAmount'] > 0) {
            echo '<tr>';
            // echo '<td>' . $entry['click'] . '</td>';
            // echo '<td>' . $entry['userAmount'] . '</td>';
            echo '<td>' . $cname . '</td>';
            echo '<td>' . $entry['referAmount'] . '</td>';
            // echo '<td>' . $userEncoded . '</td>'; // Display encoded user
            // echo '<td>' . $entry['refer'] . '</td>';
            // echo '<td>' . $entry['event'] . '</td>';
            // echo '<td>' . $entry['status'] . '</td>';
            echo '<td>' . $cashbackStatus . '</td>';
            // echo '<td>' . $entry['payMessage'] . '</td>';
            echo '<td>' . $istTimeFormatted . '</td>';
            echo '</tr>';
          }
        }
        // Close the table
        echo '</table>';
} else {
  // If there's no data, show a JavaScript alert
  ?>
        <html lang="en" dir="ltr">


        <head>
          <meta charset="utf-8">
          <title>FokatCash</title>
          <link rel="stylesheet"
            href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600&display=swap">
          <link rel="stylesheet" href="report.css">
          <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" charset="utf-8"></script>
          <meta name="viewport" content="width=device-width">
        </head>
        <style>
          .data-table td,
          .data-table th {
            font-size: 17px;
            /* Adjust the value as needed */
          }

          .credited {
            color: #FFA500;
            /* Orange color */
          }
        </style>

        <body>
          <center>
            <div class="login-form">
              <h1>
                <font color='#0f0f0f'>REPORT
              </h1>
              <center>

        </body>

        </html>

        <div class="statics">
          <center><br>
            <fieldset>Refferer:
              <?php echo $user; ?>
              <hr>Camp:
              <?php echo $cname; ?>
              <hr>Total Clicks:
              <?php echo $totalClicks; ?>
              <hr>Total Conversions: <span id="totalLeads">Calculating...</span> <!-- Placeholder for total leads -->
              <hr>
              <font color="#008000"> Cashback Sent: Rs. <span id="totalAcceptedReferAmount">Calculating...</span> </font>
              <!-- Placeholder for total refer amount -->
              <hr>
              <font color="#FFA500">Pending Cashback : Rs.<span id="totalPendingReferAmount">Calculating...</span></font>
              <hr>
            </fieldset><br><br>

            <h5>No data Found</h5>
            <?php


}
?>
    </table>
    <!-- ... Your existing code ... -->
    <script>
  // JavaScript to calculate and display the total leads count and total refer amounts
  document.addEventListener("DOMContentLoaded", function () {
    // Calculate the total leads count and total refer amounts based on the payment statuses and refer amount conditions
    var totalLeads = 0;
    var totalAcceptedReferAmount = 0;
    var totalPendingReferAmount = 0;
    var totalFailedReferAmount = 0;
    var totalUnknownReferAmount = 0;
    var event = "<?php echo $event; ?>";

    <?php foreach ($data as $entry): ?>
      <?php if ($entry['referPaymentStatus'] !== 'REJECTED' && $entry['referPaymentStatus'] !== 'BLOCKED' && $entry['referAmount'] > 0): ?>
        totalLeads++;
        <?php if ($entry['referPaymentStatus'] === 'ACCEPTED'): ?>
          totalAcceptedReferAmount += parseFloat(<?php echo $entry['referAmount']; ?>);
        <?php elseif ($entry['referPaymentStatus'] === 'PENDING'): ?>
          totalPendingReferAmount += parseFloat(<?php echo $entry['referAmount']; ?>);
        <?php elseif ($entry['referPaymentStatus'] === 'FAILURE'): ?>
          totalFailedReferAmount += parseFloat(<?php echo $entry['referAmount']; ?>);
        <?php elseif ($entry['referPaymentStatus'] === 'UNKNOWN'): ?>
          totalUnknownReferAmount += parseFloat(<?php echo $entry['referAmount']; ?>);
        <?php endif; ?>
      <?php endif; ?>
    <?php endforeach; ?>

    // Update the HTML content to display the calculated totals
    var totalLeadsElement = document.getElementById("totalLeads");
    totalLeadsElement.textContent = totalLeads;

    var totalAcceptedReferAmountElement = document.getElementById("totalAcceptedReferAmount");
    totalAcceptedReferAmountElement.textContent = totalAcceptedReferAmount.toFixed(2);

    var totalPendingReferAmountElement = document.getElementById("totalPendingReferAmount");
    totalPendingReferAmountElement.textContent = totalPendingReferAmount.toFixed(2);

    var totalFailedReferAmountElement = document.getElementById("totalFailedReferAmount");
    totalFailedReferAmountElement.textContent = totalFailedReferAmount.toFixed(2);

    var totalUnknownReferAmountElement = document.getElementById("totalUnknownReferAmount");
    totalUnknownReferAmountElement.textContent = totalUnknownReferAmount.toFixed(2);
  });
</script>



    <br><br><br>
    <footer id="footer">
      <div class="copyright">
        &copy; Copyright <strong><span>FokatCash</span></strong>
      </div>
    </footer><!-- End Footer -->
</div><!-- End statics div -->
</center><!-- End center div -->
</body><!-- End body tag -->

</html><!-- End HTML document -->
/**
 * Add activity ratio.
 */
function add_activity_ratio() {
  /** @var \Drupal\Core\Entity\EntityLastInstalledSchemaRepositoryInterface $schema_repository */
  $schema_repository = \Drupal::service('entity.last_installed_schema.repository');
  /** @var Drupal\Core\Entity\EntityTypeBundleInfo $entity_bundle_info */
  $entity_bundle_info = \Drupal::service('entity_type.bundle.info');
  /** @var Drupal\Core\Entity\EntityFieldManager $entity_field_manager */
  $entity_field_manager = \Drupal::service('entity_field.manager');
  $definitions = \Drupal::entityTypeManager()->getDefinitions();
  $entities = [];
  foreach ($definitions as $entity_type_id => $definition) {
    if (!$definition instanceof ConfigEntityType) {
      $entities[] = $entity_type_id;
    }
  }
  $spec = [
    'type' => 'numeric',
    'unsigned' => TRUE,
    'precision' => 5,
    'scale' => 2,
  ];
  $database = \Drupal::database();
  $schema = $database->schema();
  foreach ($entities as $entity_type_id) {
    $bundles = $entity_bundle_info->getBundleInfo($entity_type_id);
    foreach ($bundles as $bundle_id => $bundle) {
      $field_definitions = $entity_field_manager->getFieldDefinitions($entity_type_id, $bundle_id);
      foreach ($field_definitions as $field_definition) {
        if ($field_definition->getType() === 'pos_nace_field_type') {
          /** @var Drupal\field\Entity\FieldStorageConfig $storage */
          $storage = $field_definition->getFieldStorageDefinition();
          $storage->setSetting('activity_ratio', FALSE);
          $key_value = \Drupal::keyValue('entity.storage_schema.sql');
          $key_name = $entity_type_id . '.field_schema_data.' . $field_definition->getName();
          $storage_schema = $key_value->get($key_name);
          if ($storage instanceof FieldStorageConfig || $storage->isMultiple()) {
            foreach ([
              $entity_type_id . '__' . $field_definition->getName(),
              $entity_type_id . '_revision' . '__' . $field_definition->getName(),
            ] as $table) {
              $field_name = $field_definition->getName();
              if ($schema->tableExists($table) && !$schema->fieldExists($table, $field_name . '_activity_ratio')) {
                $schema->addField($table, $field_name . '_activity_ratio', $spec);
              }
            }
          }
          else {
            $table = $entity_type_id . '_field_data';
            $field_name = $field_definition->getName();
            if ($schema->tableExists($table) && !$schema->fieldExists($table, $field_name . '__activity_ratio')) {
              $schema->changeField($table, $field_name, $field_name . '__value', [
                'type' => 'varchar',
                'length' => 255,
                'binary' => FALSE,
              ]);
              $schema->addField($table, $field_name . '__activity_ratio', $spec);
              $storage_schema[$table]['fields'][$field_name . '__value'] = [
                'type' => 'varchar',
                'length' => 255,
                'binary' => FALSE,
              ];
              if (isset($storage_schema[$table]['fields'][$field_name])) {
                unset($storage_schema[$table]['fields'][$field_name]);
              }
              $storage_schema[$table]['fields'][$field_name . '__activity_ratio'] = $spec;
            }
          }
          $schema_repository->setLastInstalledFieldStorageDefinition($storage);
          $key_value->set($key_name, $storage_schema);
        }
      }
    }
  }
}
<?php
$month = date('m');
$year = date('Y');

// Get the first day of the month
$firstDayOfMonth = mktime(0, 0, 0, $month, 1, $year);

// Number of days in the month
$numberDays = date('t', $firstDayOfMonth);

// Get the name of the month
$monthName = date('F', $firstDayOfMonth);

// Get the day of the week for the first day of the month
$dayOfWeek = date('D', $firstDayOfMonth);

// Create a table to organize the calendar
echo "<h1>$monthName $year</h1>";
echo "<table>";
echo "<tr><th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th></tr><tr>";

// Pad the calendar with empty cells if the month doesn't start on a Sunday
if($dayOfWeek != 'Sun') {
  $blankDaysBefore = date('w', $firstDayOfMonth);
  for($i = 0; $i < $blankDaysBefore; $i++) {
    echo "<td></td>";
  }
}

// Fill in the rest of the calendar with the days of the month
for($dayCounter = 1; $dayCounter <= $numberDays; $dayCounter++) {
  $currentDay = mktime(0, 0, 0, $month, $dayCounter, $year);
  if(date('w', $currentDay) == 0) {
    echo "</tr><tr>";
  }
  echo "<td>$dayCounter</td>";
}

echo "</tr></table>";
?>
 $j==10<?php
for($i=1;$i<=10;$i++) {
    for($j=1;$j<=10;$j++) {
        if(($i==1 && $j>5) || ($i==10 && $j<=5) || ($j==1 && $i<=5) || ( $j==10 &&  $i>5) || ($j==5) || ($i==5) ) {
            echo "*  ";
        } else {
            echo "   ";
        }
    }
    echo "\n";
}
?>
********************************front-page.php********************************
<div class="popular-products">
    <?php echo do_shortcode('[products limit="4" orderby="popularity"]'); ?>
</div>

********************************function.php********************************
// Customize the classes inside the <ul> element for the products list.
function custom_woocommerce_product_loop_start($loop_output) {
    // Add custom classes to the <ul> element.
    $loop_output = str_replace('products', 'products custom-ul-class', $loop_output);
    return $loop_output;
}
add_filter('woocommerce_product_loop_start', 'custom_woocommerce_product_loop_start', 10, 1);
********************************style.css********************************

/* Custom styles for the popular products list */
ul.products.custom-ul-class {
    /* Add your custom styles here */
}

/**
 * Custom Fonts
 */

 function enqueue_custom_fonts() {
if(!is_admin()) {
wp_register_style('source_sans_pro','https://fonts.googleapis.com/css2?family=Indie+Flower&family=Montserrat:wght@900&family=Roboto:ital,wght@0,400;0,700;1,300;1,400&display=swap' );
wp_register_style('nunito','https://fonts.googleapis.com/css2?family=Nunito:ital,wght@0,400;0,700;1,400;1,700&display=swap' );
wp_enqueue_style('source_sans_pro' );
wp_enqueue_style('nunito' );
};
};

add_action('wp_enqueue_scripts','enqueue_custom_fonts');
// [current_user_display_name]
function display_current_user_display_name () {
    $user = wp_get_current_user();
    $display_name = $user->display_name;
    return $user->display_name;
}
add_shortcode('current_user_display_name', 'display_current_user_display_name');
#!/bin/bash

# Crea la base de datos
createdb 'nombre_de_tu_base_de_datos'

# Conecta a la base de datos
psql 'nombre_de_tu_base_de_datos' << EOF

# Crea la tabla
CREATE TABLE 'nombre_de_tu_tabla' (
  'nombre_de_tu_columna_1' tipo_de_dato_1,
  'nombre_de_tu_columna_2' tipo_de_dato_2,
  'nombre_de_tu_columna_3' tipo_de_dato_3,
  ...
);

# Sal del cliente de PostgreSQL
\q

EOF
#!/bin/bash

# Crea la base de datos
createdb 'nombre_de_tu_base_de_datos'

# Conecta a la base de datos
psql 'nombre_de_tu_base_de_datos' << EOF

# Crea la tabla
CREATE TABLE 'nombre_de_tu_tabla' (
  'nombre_de_tu_columna_1' tipo_de_dato_1,
  'nombre_de_tu_columna_2' tipo_de_dato_2,
  'nombre_de_tu_columna_3' tipo_de_dato_3,
  ...
);

# Sal del cliente de PostgreSQL
\q

EOF
//INDEX.PHP
<?php session_start();
//when login button pushed
if (isset($_POST['login'])){
//    if username and password not empty
    if (!empty($_POST['username']) && !empty($_POST['password'])){
//        store
        $_SESSION['username']  = $_POST["username"];
        $_SESSION['password']  = $_POST["password"];
//    take you to home.php
        header("Location: home.php");
    }else{
        echo "Missing username or password";
    }
}

?>
  
  
  
  
  //HOME.PHP
  <?php
session_start();
//if logout pressed
if (isset($_POST['logout'])){
//    destroys session
    session_destroy();
//    rerouts you to index
    header("Location: index.php");
}
echo $_SESSION['username'] . "<br>";
echo $_SESSION['password'] . "<br>";;



?>
<?php

setcookie("fav_food","pizza", time() + (86400 * 2), "/");
setcookie("fav_drink","water", time() + (86400 * 3), "/");
setcookie("fav_dessert","cookies", time() + (86400 * 4), "/");

foreach ($_COOKIE as $key => $value){
    echo "{$key} = {$value} <br>";
}


if (isset($_COOKIE['fav_food'])){
    echo "BUY SOME {$_COOKIE['fav_food']}";
}else{
    echo "I dont know ypu fav food";
}
<?php
    if (isset($_POST['submit'])){
        $username = filter_input(INPUT_POST, "username", FILTER_SANITIZE_SPECIAL_CHARS);
        echo "Hello {$username}";
    }
?>

<!doctype html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <form action="index.php" method="post">
        <input type="text" name="username" id="username">
        <input type="submit" name="submit">
    </form>

</body>

</html>
<?php
$result = null;
if(isset($_POST['submit'])) {

   $foods = $_POST['foods'];

   foreach ($foods as $food){
       echo "You like {$food} <br>";
   }
}

?>



<form action="index.php" method="post">
    <input type="checkbox" name="foods[]" value="pizza"> pizza <br>
    <input type="checkbox" name="foods[]" value="hamburger">Hamburger <br>
    <input type="checkbox" name="foods[]" value="hotdog"> hotdog <br>
    <input type="checkbox" name="foods[]" value="taco"> taco <br>

    <input type="submit" value="Submit" name="submit">
</form>
sudo apt-get clean all
sudo rm -rf /var/lib/apt/lists/*
sudo apt-get update --fix-missing
sudo apt-get upgrade

instalar dependencias faltantes 
sudo apt -f install
 $taxonomy = 'product_cat'; 
   $primary_cat_id=get_post_meta($product->id,'_yoast_wpseo_primary_' . $taxonomy, true);
    if($primary_cat_id){
       $primary_cat = get_term($primary_cat_id, $taxonomy);
       if(isset($primary_cat->name)) 
           echo $primary_cat->name;
    }
/wp-admin/admin-ajax.php?action=function_name
<?php
// Enter your code here, enjoy!
// function calculateDistance($lat1, $lon1, $lat2, $lon2) {
//     // approximate radius of Earth in km
//     $R = 6371.0;

//     // convert degrees to radians
//     $lat1 = deg2rad($lat1);
//     $lon1 = deg2rad($lon1);
//     $lat2 = deg2rad($lat2);
//     $lon2 = deg2rad($lon2);

//     // calculate the differences in latitude and longitude
//     $dlat = $lat2 - $lat1;
//     $dlon = $lon2 - $lon1;

//     // apply the Haversine formula
//     $a = sin($dlat / 2) ** 2 + cos($lat1) * cos($lat2) * sin($dlon / 2) ** 2;
//     $c = 2 * atan2(sqrt($a), sqrt(1 - $a));

//     // calculate the distance
//     $distance = $R * $c;

//     return $distance;
// }

// // Array of coordinates
// $coordinates = array(
//     array(-14.537804, 40.672439, "NA1"),  // NA1
//     array(-14.532698, 40.674953, "NA2"),  // NA2
//     array(-14.529319, 40.675874, "NA3"),  // NA3
//     array(-14.523059, 40.675931, "NA4"),  // NA4
//     array(-14.459071, 40.674796, "NB5"),  // NB5
//     array(-14.460408, 40.678548, "NB6"),  // NB6
//     array(-14.461540, 40.680757, "NB7")   // NB7
// );

// // Calculate distances between points
// $pointCount = count($coordinates);
// for ($i = 0; $i < $pointCount - 1; $i++) {
//     $coord1 = $coordinates[$i];
//     $coord2 = $coordinates[$i + 1];
    
//     $j = $i + 1;

//     $lat1 = $coord1[0];
//     $lon1 = $coord1[1];
//     $lat2 = $coord2[0];
//     $lon2 = $coord2[1];

//     $distance = calculateDistance($lat1, $lon1, $lat2, $lon2);
//     echo "Distance between point {$coord1[2]} and point {$coord2[2]}: {$distance} km\n";
// }


function calculateDistance($lat1, $lon1, $lat2, $lon2) {
    // approximate radius of Earth in km
    $R = 6371.0;

    // convert degrees to radians
    $lat1 = deg2rad($lat1);
    $lon1 = deg2rad($lon1);
    $lat2 = deg2rad($lat2);
    $lon2 = deg2rad($lon2);

    // calculate the differences in latitude and longitude
    $dlat = $lat2 - $lat1;
    $dlon = $lon2 - $lon1;

    // apply the Haversine formula
    $a = sin($dlat / 2) ** 2 + cos($lat1) * cos($lat2) * sin($dlon / 2) ** 2;
    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));

    // calculate the distance
    $distance = $R * $c;

    return $distance;
}

// Array of coordinates
$coordinates = array(
    array(-14.537804, 40.672439, 'NA1'),
    array(-14.532698, 40.674953, 'NA2'),
    array(-14.529319, 40.675874, 'NA3'),
    array(-14.523059, 40.675931, 'NA4'),
    array(-14.459071, 40.674796, 'NB5'),
    array(-14.460408, 40.678548, 'NB6'),
    array(-14.461540, 40.680757, 'NB7')
);

// Calculate distances between each point
$pointCount = count($coordinates);
for ($i = 0; $i < $pointCount - 1; $i++) {
    $coord1 = $coordinates[$i];
    $lat1 = $coord1[0];
    $lon1 = $coord1[1];

    for ($j = $i + 1; $j < $pointCount; $j++) {
        $coord2 = $coordinates[$j];
        $lat2 = $coord2[0];
        $lon2 = $coord2[1];

        $distance = calculateDistance($lat1, $lon1, $lat2, $lon2);
        echo "Distance between point {$coord1[2]} and point {$coord2[2]}: {$distance} km\n";
    }
}

$digits = 3;
echo rand(pow(10, $digits-1), pow(10, $digits)-1);
 if (!defined('ABSPATH')) exit;

    new My_Cron();

    class My_Cron {

        public function __construct() {
            add_filter('cron_schedules', array($this, 'cron_time_intervals'));
            add_action( 'wp',  array($this, 'cron_scheduler'));
            add_action( 'cast_my_spell', array( $this, 'auto_spell_cast' ) );
        }

        public function cron_time_intervals($schedules)
        {
            $schedules['minutes_10'] = array(
                'interval' => 10 * 60,
                'display' => 'Once 10 minutes'
            );
            return $schedules;
        }

        function cron_scheduler() {
            if ( ! wp_next_scheduled( 'cast_my_spell' ) ) {
                wp_schedule_event( time(), 'minutes_10', 'cast_my_spell');
            }
        }

        function auto_spell_cast(){
            My_Plugin_Class::instance()->launch_spell();
        }
    }
cntrl + shift + t: abrir una ventana del navegador que ya habias cerrado con anterioridad
windows + l: bloquea el ordenador y guarda todo el trabajo
;MainWP Requriement - cURL timeout
default_socket_timeout = 300
;END MainWP Requriement
  // Only from inside the same class
  $this->processSomething([__CLASS__, 'myStaticCallback']);
  // From either inside or outside the same class
  $myObject->processSomething(['\Namespace\MyClass', 'myStaticCallback']);
  $myObject->processSomething(['\Namespace\MyClass::myStaticCallback']); // PHP 5.2.3+
  $myObject->processSomething([MyClass::class, 'myStaticCallback']); // PHP 5.5.0+
get_intermediate_image_sizes(); // get all the image size names.
wp_get_additional_image_sizes(); // get all the additional image size data.
wp_get_registered_image_subsizes(); // get all the image size data.
$post_id = wp_insert_post(array (
   'post_type' => 'your_post_type',
   'post_title' => $your_title,
   'post_content' => $your_content,
   'post_status' => 'publish',
   'comment_status' => 'closed',
   'ping_status' => 'closed',
   'meta_input' => array(
      '_your_custom_1' => $custom_1,
      '_your_custom_2' => $custom_2,
      '_your_custom_3' => $custom_3,
    ),
));
$post_id = wp_insert_post(array (
   'post_type' => 'your_post_type',
   'post_title' => $your_title,
   'post_content' => $your_content,
   'post_status' => 'publish',
   'comment_status' => 'closed',
   'ping_status' => 'closed',
   'meta_input' => array(
      '_your_custom_1' => $custom_1,
      '_your_custom_2' => $custom_2,
      '_your_custom_3' => $custom_3,
    ),
));
$files = scandir('/some/random/folder') ?: [];
$user = $_POST['user'] ?? $_SESSION['user'] ?? $_COOKIE['user'] ?? '';
<?php
    var_dump(5 ?: 0); // 5
    var_dump(false ?: 0); // 0
    var_dump(null ?: 'foo'); // 'foo'
    var_dump(true ?: 123); // true
    var_dump('rock' ?: 'roll'); // 'rock'
?>
   function save_function()
{

    $subject_term = 'subject';
    $my_subject_term = term_exists($subject_term, 'my_custom_taxonomy');   // check if term in website or no
    // Create Term if it doesn't exist
    if (!$my_subject_term) {
        $my_subject_term = wp_insert_term($subject_term, 'my_custom_taxonomy');
    }
    $custom_tax = array(
        'my_custom_taxonomy' => array(
            $my_subject_term['term_taxonomy_id'],
        )
    );

    // MESSAGE FIELDS
    $public_post = array(
        'post_title' => filter_input(INPUT_POST, 'title'),
        'post_author' => 1,
        'post_type' => 'message',
        'post_status' => 'pending',
        'tax_input' => $custom_tax
    );

    $post_id = wp_insert_post($public_post);

    
}
Supongamos que estamos desarrollando una aplicación de gestión de proyectos. Cada proyecto tiene un solo gerente, pero un gerente puede estar a cargo de varios proyectos. Además, cada proyecto puede tener varios miembros del equipo, y cada miembro del equipo puede estar asignado a varios proyectos.

1.-modelo(app/models/Proyecto.php)

<?php

namespace app\models;

use yii\db\ActiveRecord;

class Proyecto extends ActiveRecord
{
    public static function tableName()
    {
        return 'proyectos';
    }

    public function getGerente()
    {
        return $this->hasOne(Gerente::className(), ['id' => 'id_gerente']);
    }

    public function getMiembrosEquipo()
    {
        return $this->hasMany(MiembroEquipo::className(), ['id_proyecto' => 'id']);
    }
}

En este ejemplo, estamos creando un modelo llamado Proyecto que extiende de la clase ActiveRecord de Yii2. Este modelo representa la tabla proyectos de la base de datos PostgreSQL y tiene una relación de uno a uno con la tabla gerentes y una relación de uno a muchos con la tabla miembros_equipo.

2.-Modelo(app/models/Gerente.php)

<?php

namespace app\models;

use yii\db\ActiveRecord;

class Gerente extends ActiveRecord
{
    public static function tableName()
    {
        return 'gerentes';
    }

    public function getProyectos()
    {
        return $this->hasMany(Proyecto::className(), ['id_gerente' => 'id']);
    }
}

En este ejemplo, estamos creando un modelo llamado Gerente que extiende de la clase ActiveRecord de Yii2. Este modelo representa la tabla gerentes de la base de datos PostgreSQL y tiene una relación de uno a muchos con la tabla proyectos.


3.-Modelo(app/models/MiembroEquipo.php)

<?php

namespace app\models;

use yii\db\ActiveRecord;

class MiembroEquipo extends ActiveRecord
{
    public static function tableName()
    {
        return 'miembros_equipo';
    }

    public function getProyecto()
    {
        return $this->hasOne(Proyecto::className(), ['id' => 'id_proyecto']);
    }

    public function getEmpleado()
    {
        return $this->hasOne(Empleado::className(), ['id' => 'id_empleado']);
    }
}

En este ejemplo, estamos creando un modelo llamado MiembroEquipo que extiende de la clase ActiveRecord de Yii2. Este modelo representa la tabla miembros_equipo de la base de datos PostgreSQL y tiene una relación de uno a uno con la tabla proyectos y una relación de uno a uno con la tabla empleados.


4.-Modelo(app/models/Empleado.php)

<?php

namespace app\models;

use yii\db\ActiveRecord;

class Empleado extends ActiveRecord
{
    public static function tableName()
    {
        return 'empleados';
    }

    public function getMiembrosEquipo()
    {
        return $this->hasMany(MiembroEquipo::className(), ['id_empleado' => 'id']);
    }
}

En este ejemplo, estamos creando un modelo llamado Empleado que extiende de la clase ActiveRecord de Yii2. Este modelo representa la tabla empleados de la base de datos PostgreSQL y tiene una relación de uno a muchos con la tabla miembros_equipo.

5.-Controlador(app/controllers/ProyectoController.php)

<?php

namespace app\controllers;

use yii\web\Controller;
use app\models\Proyecto;

class ProyectoController extends Controller
{
    public function actionIndex()
    {
        $proyectos = Proyecto::find()->with('gerente', 'miembrosEquipo.empleado')->all();
        return $this->render('index', ['proyectos' => $proyectos]);
 }
}

En este ejemplo, estamos creando un controlador llamado ProyectoController que tiene un método llamado actionIndex que se encarga de obtener todos los proyectos de la base de datos y sus relaciones con gerentes y miembros del equipo utilizando los modelos Proyecto, Gerente, MiembroEquipo y Empleado. Luego, se renderiza la vista index y se le pasa como parámetro los proyectos obtenidos.

6.-Vista(app/views/proyecto/index.php)

<table>
    <thead>
        <tr>
            <th>ID</th>
            <th>Nombre</th>
            <th>Gerente</th>
            <th>Miembros del equipo</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($proyectos as $proyecto): ?>
            <tr>
                <td><?= $proyecto->id ?></td>
                <td><?= $proyecto->nombre ?></td>
                <td><?= $proyecto->gerente->nombre ?></td>
                <td>
                    <ul>
                        <?php foreach ($proyecto->miembrosEquipo as $miembroEquipo): ?>
                            <li><?= $miembroEquipo->empleado->nombre ?></li>
                        <?php endforeach ?>
                    </ul>
                </td>
            </tr>
        <?php endforeach ?>
    </tbody>
</table>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function() {
        // Código de jQuery aquí
    });
</script>

En este ejemplo, estamos creando una vista llamada index que muestra una tabla con los proyectos, sus gerentes y sus miembros del equipo. También estamos incluyendo la librería de jQuery y un bloque de código jQuery vacío que se ejecutará cuando el DOM esté listo.

7.-Codigo Jquery (app/web/js/mi-script.js)

En este ejemplo, estamos utilizando jQuery para hacer una petición AJAX al servidor cuando el usuario hace clic en una fila de la tabla de proyectos. La petición se realiza al controlador ProyectoController y al método actionGet, que se encarga de obtener los detalles del proyecto con el ID especificado y devolverlos en formato JSON.
Recuerda que debes ajustar los nombres de los archivos y las rutas según la estructura de tu aplicación Yii2 y PostgreSQL.
Espero que esto te ayude a entender cómo podrías implementar relaciones de 1 a 1, 0 a 1 y muchos a muchos utilizando Yii2, PostgreSQL, MVC, OOP y jQuery.

8.- código SQL para crear las tablas utilizadas en el ejemplo de la aplicación web que utiliza Yii2, PostgreSQL, MVC, OOP y jQuery para implementar relaciones de 1 a 1, 0 a 1 y muchos a muchos:

Tabla proyectos ()
CREATE TABLE proyectos (
    id SERIAL PRIMARY KEY,
    nombre VARCHAR(255) NOT NULL,
    id_gerente INTEGER REFERENCES gerentes(id)
);

En esta tabla, estamos creando un campo id que es una clave primaria autoincremental, un campo nombre que almacena el nombre del proyecto y un campo id_gerente que es una clave foránea que hace referencia al campo id de la tabla gerentes.

9.-tabla gerentes

CREATE TABLE gerentes (
    id SERIAL PRIMARY KEY,
    nombre VARCHAR(255) NOT NULL
);

En esta tabla, estamos creando un campo id que es una clave primaria autoincremental y un campo nombre que almacena el nombre del gerente.

10.- tabla miembros_equipo

CREATE TABLE miembros_equipo (
    id_proyecto INTEGER REFERENCES proyectos(id),
    id_empleado INTEGER REFERENCES empleados(id),
    PRIMARY KEY (id_proyecto, id_empleado)
);

En esta tabla, estamos creando dos campos id_proyecto e id_empleado que son claves foráneas que hacen referencia a los campos id de las tablas proyectos y empleados, respectivamente. Además, estamos creando una clave primaria compuesta por ambos campos para asegurarnos de que no haya duplicados.

11.-tabla empleados

CREATE TABLE empleados (
    id SERIAL PRIMARY KEY,
    nombre VARCHAR(255) NOT NULL
);

En esta tabla, estamos creando un campo id que es una clave primaria autoincremental y un campo nombre que almacena el nombre del empleado.

Recuerda que debes ajustar los nombres de las tablas y los campos según la estructura de tu aplicación. Además, debes asegurarte de que las claves foráneas estén correctamente definidas y que las relaciones entre las tablas sean coherentes.

posibles consultas que podrías hacer utilizando el código SQL de la aplicación web que utiliza Yii2, PostgreSQL, MVC, OOP y jQuery para implementar relaciones de 1 a1, 0 a 1 y muchos a muchos:

1.-Obtener todos los proyectos con sus gerentes y miembros del equipo:

SELECT p.nombre AS proyecto, g.nombre AS gerente, e.nombre AS empleado
FROM proyectos p
LEFT JOIN gerentes g ON p.id_gerente = g.id
LEFT JOIN miembros_equipo me ON p.id = me.id_proyecto
LEFT JOIN empleados e ON me.id_empleado = e.id;

En esta consulta, estamos obteniendo todos los proyectos con sus gerentes y miembros del equipo utilizando las tablas proyectos, gerentes, miembros_equipo y empleados. Estamos utilizando un LEFT JOIN para asegurarnos de que se incluyan todos los proyectos, incluso aquellos que no tienen gerente o miembros del equipo.


2.-Obtener todos los proyectos que tienen un gerente asignado:

SELECT p.nombre AS proyecto, g.nombre AS gerente
FROM proyectos p
INNER JOIN gerentes g ON p.id_gerente = g.id;

En esta consulta, estamos obteniendo todos los proyectos que tienen un gerente asignado utilizando las tablas proyectos y gerentes. Estamos utilizando un INNER JOIN para asegurarnos de que solo se incluyan los proyectos que tienen un gerente asignado.

3.-Obtener todos los proyectos en los que trabaja un empleado específico:

SELECT p.nombre AS proyecto, e.nombre AS empleado
FROM proyectos p
INNER JOIN miembros_equipo me ON p.id = me.id_proyecto
INNER JOIN empleados e ON me.id_empleado = e.id
WHERE e.nombre = 'Juan';

En esta consulta, estamos obteniendo todos los proyectos en los que trabaja un empleado específico utilizando las tablas proyectos, miembros_equipo y empleados. Estamos utilizando un INNER JOIN para asegurarnos de que solo se incluyan los proyectos en los que trabaja el empleado específico y estamos utilizando una cláusula WHERE para filtrar por el nombre del empleado.

4.-Obtener todos los empleados que trabajan en un proyecto específico:

SELECT e.nombre AS empleado
FROM empleados e
INNER JOIN miembros_equipo me ON e.id = me.id_empleado
INNER JOIN proyectos p ON me.id_proyecto = p.id
WHERE p.nombre = 'Proyecto A';

En esta consulta, estamos obteniendo todos los empleados que trabajan en un proyecto específico utilizando las tablas empleados, miembros_equipo y proyectos. Estamos utilizando un INNER JOIN para asegurarnos de que solo se incluyan los empleados que trabajan en el proyecto específico y estamos utilizando una cláusula WHERE para filtrar por el nombre del proyecto.
Recuerda que debes ajustar las consultas según la estructura de tu aplicación y las relaciones entre las tablas.

{
   error: {
     message: "Unauthorized"
   }
}


If you removed Auth middleware but still getting unauthorized means there may be route cache. Try using php artisan route:clear and check.


<?php

function isSubstring($string, $substring) 
{
    return strpos($string, $substring) !== false;
}

// Usage example:
$mainString = "Hello, World!";
$substring = "World";
if (isSubstring($mainString, $substring)) {
    echo "The substring '$substring' is found in the main string.";
} else {
    echo "The substring '$substring' is not found in the main string.";
}
function custom_add_attribute_thumbnail_field( $term ) {
    $thumbnail_id = get_term_meta( $term->term_id, '_thumbnail_id', true );
    $image_url = wp_get_attachment_image_url( $thumbnail_id, 'thumbnail' ); // Imposta la dimensione dell'immagine desiderata (esempio: 'thumbnail', 'medium', 'large')
    ?>
    <tr class="form-field">
        <th scope="row" valign="top"><label for="attribute_thumbnail"><?php esc_html_e( 'Attribute Thumbnail', 'text-domain' ); ?></label></th>
        <td>
            <div id="attribute_thumbnail_preview">
                <?php if ( $image_url ) : ?>
                    <img src="<?php echo esc_url( $image_url ); ?>" alt="<?php echo esc_attr( $term->name ); ?>" style="max-width:100px; max-height:100px;">
                <?php endif; ?>
            </div>
            <input type="hidden" id="attribute_thumbnail" name="attribute_thumbnail" value="<?php echo esc_attr( $thumbnail_id ); ?>">
            <button type="button" id="upload_attribute_thumbnail_button" class="button"><?php esc_html_e( 'Upload/Add image', 'text-domain' ); ?></button>
            <button type="button" id="remove_attribute_thumbnail_button" class="button"><?php esc_html_e( 'Remove image', 'text-domain' ); ?></button>
            <script>
                jQuery(document).ready(function($) {
                    // Carica l'immagine
                    $('#upload_attribute_thumbnail_button').click(function() {
                        var custom_uploader = wp.media({
                            title: '<?php esc_html_e( "Choose or Upload Image", "text-domain" ); ?>',
                            button: {
                                text: '<?php esc_html_e( "Use Image", "text-domain" ); ?>'
                            },
                            multiple: false
                        }).on('select', function() {
                            var attachment = custom_uploader.state().get('selection').first().toJSON();
                            $('#attribute_thumbnail').val(attachment.id);
                            $('#attribute_thumbnail_preview').html('<img src="' + attachment.url + '" alt="<?php echo esc_attr( $term->name ); ?>" style="max-width:100px; max-height:100px;">');
                        }).open();
                    });

                    // Rimuovi l'immagine
                    $('#remove_attribute_thumbnail_button').click(function() {
                        $('#attribute_thumbnail').val('');
                        $('#attribute_thumbnail_preview').html('');
                    });
                });
            </script>
            <p class="description"><?php esc_html_e( 'Upload or select an image to set as the attribute thumbnail.', 'text-domain' ); ?></p>
        </td>
    </tr>
    <?php
}
add_action( 'pa_attributo_add_form_fields', 'custom_add_attribute_thumbnail_field', 10, 2 );
add_action( 'pa_attributo_edit_form_fields', 'custom_add_attribute_thumbnail_field', 10, 2 );

function custom_save_attribute_thumbnail( $term_id ) {
    if ( isset( $_POST['attribute_thumbnail'] ) ) {
        $thumbnail_id = absint( $_POST['attribute_thumbnail'] );
        update_term_meta( $term_id, '_thumbnail_id', $thumbnail_id );
    }
}
add_action( 'edited_pa_attributo', 'custom_save_attribute_thumbnail', 10, 2 );
  <?php
  $taxonomy     = 'product_cat';
  $orderby      = 'menu_order';  
  $show_count   = 0;      // 1 for yes, 0 for no
  $pad_counts   = 0;      // 1 for yes, 0 for no
  $hierarchical = 1;      // 1 for yes, 0 for no  
  $title        = '';  
  $empty        = 0;

  $args = array(
         'taxonomy'     => $taxonomy,
         'orderby'      => $orderby,
         'show_count'   => $show_count,
         'pad_counts'   => $pad_counts,
         'hierarchical' => $hierarchical,
         'title_li'     => $title,
         'hide_empty'   => $empty
  );
 $all_categories = get_categories( $args );
 foreach ($all_categories as $cat) {
    if($cat->category_parent == 0) {
        $category_id = $cat->term_id;       
        //echo '<br /><a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</a>';

        $args2 = array(
                'taxonomy'     => $taxonomy,
                'child_of'     => 0,
                'parent'       => $category_id,
                'orderby'      => $orderby,
                'show_count'   => $show_count,
                'pad_counts'   => $pad_counts,
                'hierarchical' => $hierarchical,
                'title_li'     => $title,
                'hide_empty'   => $empty
        );
        $sub_cats = get_categories( $args2 );
        if($sub_cats) {
            foreach($sub_cats as $sub_category) {
                // echo  $sub_category->name ;
                 echo '<br /><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
                echo '<br /><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
            }   
        }
    }       
}
?>
//Disable Comments

add_action('admin_init', function () {
    // Redirect any user trying to access comments page
    global $pagenow;

    if ($pagenow === 'edit-comments.php') {
        wp_redirect(admin_url());
        exit;
    }

    // Remove comments metabox from dashboard
    remove_meta_box('dashboard_recent_comments', 'dashboard', 'normal');

    // Disable support for comments and trackbacks in post types
    foreach (get_post_types() as $post_type) {
        if (post_type_supports($post_type, 'comments')) {
            remove_post_type_support($post_type, 'comments');
            remove_post_type_support($post_type, 'trackbacks');
        }
    }
});

// Close comments on the front-end
add_filter('comments_open', '__return_false', 20, 2);
add_filter('pings_open', '__return_false', 20, 2);

// Hide existing comments
add_filter('comments_array', '__return_empty_array', 10, 2);

// Remove comments page in menu
add_action('admin_menu', function () {
    remove_menu_page('edit-comments.php');
});

// Remove comments links from admin bar
add_action('init', function () {
    if (is_admin_bar_showing()) {
        remove_action('admin_bar_menu', 'wp_admin_bar_comments_menu', 60);
    }
});
<a href="#" class="facebook"> </a>
<a href="#" class="instagram"> </a>
<a href="#" class="pinterest"> </a>
<a href="#" class="email"> </a>
<a href="#" class="youtube"> </a>
<a href="#" class="linkedin"> </a>
// Parse the initial value using Carbon
$dateTime = Carbon::parse($dateTimeString);

// Format the date and time as desired
$formattedDateTime = $dateTime->format('d-m-Y h:i:sA');
// Parse the initial value using Carbon
$dateTime = Carbon::parse($dateTimeString);

// Format the date and time as desired
$formattedDateTime = $dateTime->isoFormat('Do MMMM YYYY h:mm:ssa');
<?php
$usernames = ['username1', 'username2', ...]; // An array of the usernames of the users you want to change the role for
$new_role = 'new_role'; // The new role you want to assign to the users

foreach ($usernames as $username) {
    $user = get_user_by('login', $username);
    if (!empty($user)) {
        $user->set_role($new_role);
    }
}
?>
$oOrder = OrderAPI::getByID( $lLabID );
if( $oOrder ) {
	//$sFeld = $oOrder->getValueByMethod( "KURZ" );
	$oOrderRoot = $oOrder->getWorkflowRootOrderV2(  );
	if( $oOrderRoot ) {
}
VariablesClass::alertMsg(
	// Zeigt eine Meldung an
	$objResponse, // XAJAX Antwort, nicht aendern!
	$lModuleID, // ID des aufrufenden Moduls, nicht aendern!
	"Bitte Auftrag speichern!", // Nachricht
	"TITLE", // Titel der Meldung
	ALERT_ERROR, // Typ der  Meldung  (ALERT_DEFAULT, ALERT_OK, ALERT_WARNING, ALERT_ERROR)
	"" // (optional) Beschriftung des Buttons
);
<?php
$user = get_userdatabylogin('YOUR_USERNAME');
grant_super_admin($user->ID);
?>
implode(', ', array_column($array, 'colName'));
$coordinator = [];
$coordinatorFirstPage = Api::schoolTeacher()->index($schoolId, $filter);
$coordinator[] = $coordinatorFirstPage->data();
$lastPage = $coordinatorFirstPage->meta('last_page') ?? 1;

$promCordinators = Http::pool(function (Pool $pool) use ($lastPage, $schoolId, $filter) {
    for ($c = 2; $c <= $lastPage; $c++) {
        $filter['page'] = $c;
        $pool->withToken(Auth::user()->token())
            ->get(Api::schoolTeacher()->index($schoolId, $filter, true), $filter);
    }
});

foreach ($promCordinators as $wraped) {
    $coordinator[] = json_decode($wraped->getBody(), true)['data'] ?? [];
}

$coordinator = collect($coordinator)->flatten(1)->toArray();
dd($coordinator);
\DB::enableQueryLog(); // Enable query log

// Your Eloquent query executed by using get()

dd(\DB::getQueryLog()); // Show results of log
<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     */
    protected function redirectTo(Request $request): ?string
    {
        return $request->expectsJson() ? null : route('login');
    }

    protected function unauthenticated($request, array $guards)
    {
        abort(response()->json(
            [
                'status' => 'false',
                'message' => 'Unauthenticated',
            ], 401));
    }
}
$tournament = app('App\Http\Controllers\TournamentController')->read_tournament_details($request, $tournament_id)->getData(true);
        
echo gmdate("H:i:s", $time_in_seconds);
$name = implode('.', [
    md5_file($file->getPathname()),
    $file->getClientOriginalExtension()
]);
MyTable::whereDate( 'created_at', '<=', now()->subDays(30))->delete();

<?php

    // Get absolute path
    $path = getcwd(); // /home/user/public_html/test/test.php.   

    $path = substr($path, 0, strpos($path, "public_html"));

    $root = $path . "public_html/";

    echo $root; // This will output /home/user/public_html/
// Get array of all source files
$files = scandir("source");
// Identify directories
$source = "source/";
$destination = "destination/";
// Cycle through all source files
foreach ($files as $file) {
  if (in_array($file, array(".",".."))) continue;
  // If we copied this successfully, mark it for deletion
  if (copy($source.$file, $destination.$file))
  {
      $delete[] = $source.$file;
  }
}
// Delete all successfully-copied files
foreach ($delete as $file)
{
    unlink($file);
}
// Adds a new sortable "last updated" column to posts and pages backend.
function custom_columns($defaults) {
    $defaults['last_updated'] = __('Last Updated', 'your-textdomain');
    return $defaults;
}
add_filter('manage_posts_columns', 'custom_columns');
add_filter('manage_pages_columns', 'custom_columns');

function custom_columns_content($column_name, $post_id) {
    if ($column_name == 'last_updated') {
        $last_updated = get_the_modified_date();
        echo $last_updated;
    }
}
add_action('manage_posts_custom_column', 'custom_columns_content', 10, 2);
add_action('manage_pages_custom_column', 'custom_columns_content', 10, 2);

function custom_columns_sortable($columns) {
    $columns['last_updated'] = 'last_updated';
    return $columns;
}
add_filter('manage_edit-post_sortable_columns', 'custom_columns_sortable');
add_filter('manage_edit-page_sortable_columns', 'custom_columns_sortable');

function custom_columns_orderby($query) {
    if (!is_admin()) {
        return;
    }

    $orderby = $query->get('orderby');

    if ('last_updated' == $orderby) {
        $query->set('orderby', 'modified');
    }
}
add_action('pre_get_posts', 'custom_columns_orderby');
Go to public folder Just delete/remove the storage link inside public/

Then Run the command


 php artisan storage:link

 
the above command will link storage again
/**
 * @snippet       Variable Product Price Range: "From: min_price"
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 6
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
 
add_filter( 'woocommerce_variable_price_html', 'bbloomer_variation_price_format_min', 9999, 2 );
 
function bbloomer_variation_price_format_min( $price, $product ) {
   $prices = $product->get_variation_prices( true );
   $min_price = current( $prices['price'] );
   $max_price = end( $prices['price'] );
   $min_reg_price = current( $prices['regular_price'] );
   $max_reg_price = end( $prices['regular_price'] );
   if ( $min_price !== $max_price || ( $product->is_on_sale() && $min_reg_price === $max_reg_price ) ) {
      $price = 'From: ' . wc_price( $min_price ) . $product->get_price_suffix();
   }
   return $price;
}
     $table->id();
            $table->string('model');
            $table->unsignedBigInteger('manufacturer_id');
            $table->foreign('manufacturer_id')->references('id')->on('manufacturers');
            $table->timestamps();
add_action( 'elementor/theme/register_conditions', function( $conditions_manager ) {
class Subcategory_Archive extends \ElementorPro\Modules\ThemeBuilder\Conditions\Taxonomy {
	private $taxonomy;

	public function get_name() {
		return 'child_of_' . $this->taxonomy->name;
	}

	public function get_label() {
		return sprintf( __( 'Direct Child %s Of', 'elementor-pro' ), $this->taxonomy->labels->singular_name );
	}

	public function __construct( $data ) {
		parent::__construct( $data );

		$this->taxonomy = $data['object'];
	}

	public function is_term() {
		$taxonomy = $this->taxonomy->name;
		$current = get_queried_object();
		return ( $current && isset( $current->taxonomy ) && $taxonomy === $current->taxonomy );
	}

	public function check( $args ) {
		$id = (int) $args['id'];
		/**
		 * @var \WP_Term $current
		 */
		$current = get_queried_object();
		if ( ! $this->is_term() || 0 === $current->parent ) {
			return false;
		}

		while ( $current->parent > 0 ) {
			if ( $id === $current->parent ) {
				return true;
			}
			$current = get_term_by( 'id', $current->parent, $current->taxonomy );
		}

		return $id === $current->parent;
	}
}
$taxonomy = get_taxonomy('product_cat');
$conditions_manager->get_condition( 'product_archive' )->register_sub_condition( new Subcategory_Archive([ 'object' => $taxonomy ]) );
}, 100);
$mysqli = mysqli_connect('localhost', 'DATABASE_USERNAME', 'DATABASE_PASSWORD', 'DATABASE_NAME');
<!DOCTYPE html>
<html>
​
<body>
The content of the body element is displayed in your browser.
</body>
​
</html>
​
exec("java -jar WaveAppender.jar " . implode (' ', $theFiles));
//encrypt user password

//    hash produces a fixed length string
    $hashFormat = "$2y$10$";

//    Random characters
    $salt = "HZTym3F5Ade6tvnVf5rXve";

//    combine the hash and salt
    $hashFormat_salt = $hashFormat . $salt;
    
//    password encrypted
    $password = crypt($password,$hashFormat_salt);
function deleteRow(){
    global $connection;
    $id = $_POST['id'];

    $query = "DELETE FROM users ";
    $query .= "WHERE id = $id ";

    $result = mysqli_query($connection, $query);

    if (!$result) {
        die("Query Failed" . mysqli_error($connection));
    }
}
function updateTable() {
    global $connection;

    $username = $_POST['username'];
    $password = $_POST['password'];
    $id = $_POST['id'];

    $query = "UPDATE users SET ";
    $query .= "username = '$username', ";
    $query .= "password = '$password' ";
    $query .= "WHERE id = $id ";

    $result = mysqli_query($connection, $query);

    if (!$result) {
        die("Query Failed" . mysqli_error($connection));
    }

}

// HTML FILE
<?php
if(isset($_POST['submit'])){
    updateTable();
}

?>
  
  <form action="update.php" method="post">
    <select name="id" id="">

        <?php
        showAllData();

        ?>

    </select>

    <input type="text" name="username">
    <input type="password" name="password">
    <button type="submit" name="submit">Update</button>
</form>
function readAll(){
  // Connect to db
    global $connection;
  // make result global so you can use it in the other file
    global $result;

    $query = "SELECT * FROM USERS";

    $result = mysqli_query($connection, $query);
}


// HTML FILE
<?php
readAll();
while ($row = mysqli_fetch_assoc($result)){
?>

<pre>
    <?php
    print_r($row);
    }
    ?>
</pre>
function create(){
	//If linking to database from external file
    global $connection;

	//Grab form data
    $username = $_POST['username'];
    $password = $_POST['password'];
	
    //Sanatize user input
    $username = mysqli_real_escape_string($connection,$username);
    $password = mysqli_real_escape_string($connection,$password);

	//Query that inserts value into database
    $query = "INSERT INTO users(username,password) ";
    $query .= "VALUES ('$username', '$password')";

    $result = mysqli_query($connection,$query);

    if(!$result){
        die('Query failed' . mysqli_error());
    }
}


//HTML FILE
if (isset($_POST['submit'])) {
    create();

}
<?php

$username = $_POST['username'];
$password = $_POST['password'];

$username = mysqli_real_escape_string($connection,$username);
$password = mysqli_real_escape_string($connection,$password);
<?php
//If file is in the same directory
include "db.php";

//If file is in another directory
include"../includes/navbar.php";
<?php
//hostname,username,password,database
$connection = mysqli_connect('localhost', 'root', '', 'loginapp');

if(!$connection){
die('connection failed')
}
$areasexperiencia = $areasexperiencia;
function unique_key($array,$keyname){
$new_array = array();
foreach($array as $key=>$value){

if(!isset($new_array[$value[$keyname]])){
$new_array[$value[$keyname]] = $value;
}

}
$new_array = array_values($new_array);
return $new_array;
}
$unique_arr = unique_key($areasexperiencia,'nombre');
function download(pdfUrl, fileName) {
        fetch(pdfUrl).then(resp => resp.arrayBuffer()).then(resp => {
            const file = new Blob([resp], {type: 'application/pdf'});
            const fileURL = URL.createObjectURL(file);
            jQuery("#download-button-prev").attr('href', fileURL).attr('download', fileName);
        });
    }

    download(linkUrl, docName);
add_filter( 'woocommerce_price_trim_zeros', '__return_true' );
FROM php:8.1-fpm

RUN apt-get update

COPY . /app
RUN ls -l
RUN php -v
CMD php /app/index.php





















function kh_plugin_settings_page() {

    // Check user capabilities

    if ( ! current_user_can( 'manage_options' ) ) {

        return;

    }

    // Add error/update messages

    settings_errors( 'kh_plugin_messages' );

    ?>

    <div class="wrap">

        <h1><?php echo esc_html( get_admin_page_title() ); ?></h1>

        <form action="options.php" method="post">

            <?php

            // Output security fields for the registered setting "kh_plugin_options"

            settings_fields( 'kh_plugin_options' );

            // Output setting sections and their fields

            do_settings_sections( 'kh_plugin' );

            // Output save settings button

            submit_button( __( 'Save Settings', 'kh_plugin' ) );

            ?>

        </form>

    </div>

    <?php

}

function kh_plugin_settings_init() {

    // Register a new setting for the plugin

    register_setting( 'kh_plugin_options', 'kh_plugin_settings' );

    // Add a new section to the settings page

    add_settings_section(

        'kh_plugin_section',

        __( 'KH Plugin Settings', 'kh_plugin' ),

        'kh_plugin_section_callback',

        'kh_plugin'

    );

    // Add a text field to the settings section

    add_settings_field(

        'kh_plugin_text_field',

        __( 'Text Field', 'kh_plugin' ),

        'kh_plugin_text_field_callback',

        'kh_plugin',

        'kh_plugin_section'

    );

    // Add a checkbox field to the settings section

    add_settings_field(

        'kh_plugin_checkbox_field',

        __( 'Checkbox Field', 'kh_plugin' ),

        'kh_plugin_checkbox_field_callback',

        'kh_plugin',

        'kh_plugin_section'

    );

}

add_action( 'admin_init', 'kh_plugin_settings_init' );

// Callback function for the section

function kh_plugin_section_callback() {

    echo '<p>' . __( 'Configure your KH Plugin settings.', 'kh_plugin' ) . '</p>';

}

// Callback function for the text field

function kh_plugin_text_field_callback() {

    $options = get_option( 'kh_plugin_settings' );

    echo '<input type="text" name="kh_plugin_settings[text_field]" value="' . esc_attr( $options['text_field'] ) . '" />';

function my_plugin_shortcode( $atts ) {

    ob_start();

    

    $defaults = array(

        'form_id' => 0,

        'button_text' => 'Add field',

    );

    $args = shortcode_atts( $defaults, $atts );

    

    $form_fields = get_post_meta( $args['form_id'], 'form_fields', true );

    ?>

    <form id="my-form">

        <?php foreach ( $form_fields as $field ) : ?>

            <div class="form-group">

                <label for="<?php echo esc_attr( $field['name'] ); ?>"><?php echo esc_html( $field['label'] ); ?></label>

                <?php if ( $field['type'] === 'text' ) : ?>

                    <input type="text" name="<?php echo esc_attr( $field['name'] ); ?>" value="<?php echo esc_attr( $field['value'] ); ?>">

                <?php elseif ( $field['type'] === 'textarea' ) : ?>

                    <textarea name="<?php echo esc_attr( $field['name'] ); ?>"><?php echo esc_html( $field['value'] ); ?></textarea>

                <?php elseif ( $field['type'] === 'select' ) : ?>

                    <select name="<?php echo esc_attr( $field['name'] ); ?>">

                        <?php foreach ( $field['options'] as $option ) : ?>

                            <option value="<?php echo esc_attr( $option['value'] ); ?>"<?php selected( $option['value'], $field['value'] ); ?>><?php echo esc_html( $option['label'] ); ?></option>

                        <?php endforeach; ?>

                    </select>

                <?php endif; ?>

            </div>

        <?php endforeach; ?>

        <button type="button" id="add-field"><?php echo esc_html( $args['button_text'] ); ?></button>

    </form>

    <?php

    $output = ob_get_clean();

    return $output;

}

add_shortcode( 'my-plugin-form', 'my_plugin_shortcode' );

the_post_thumbnail( '', array( 'loading' => '' ) );
// A JavaScript module for submitting forms via AJAX

// This module depends on jQuery and the jQuery Form Plugin

var FormSubmission = {

  // Class to add to elements with form errors

  formErrorClass: 'form-error',

  // Adds form errors to the DOM

  appendFormErrors: function(data, form) {

    // Loop through the error data object

    for (var key in data) {

      // Create a new span element for the error message

      var error = $(document.createElement('span')).attr('class', FormSubmission.formErrorClass).text(data[key]);

      // Insert the error message before the input field with the corresponding name

      form.find("input[name='" + key + "']").before(error);

    }

  },

  // Hides the closest modal element to the given form

  closeModal: function(form) {

    form.closest('.modal').modal('hide');

  },

  // Handles the response from the form submission

  postFormSubmission: function(form, isModal, data) {

    // Remove any existing form errors

    FormSubmission.removeFormErrors(form);

    // If the form was submitted successfully

    if (data['success'] == true) {

      // Reset the form and close the modal if it's a modal form

      FormSubmission.resetForm(form, isModal);

    } else {

      // Append the form errors to the DOM

      FormSubmission.appendFormErrors(data['errors'], form);

    }

  },

  // Removes form errors from the DOM

  removeFormErrors: function(form) {

    form.find('.' + FormSubmission.formErrorClass).remove();

  },

  // Calls resetForm with isModal set to false

  resetForm: function(form) {

    FormSubmission.resetForm(form, false);

  },

  // Resets the form and closes the modal if it's a modal form

  resetForm: function(form, isModal) {

    // Remove any existing form errors

    FormSubmission.removeFormErrors(form);

    // Reset the form

    form[0].reset();

    // If it's a modal form, close the modal

    if (isModal == true) {

      FormSubmission.closeModal(form);

    }

  },

  // Calls submitForm with isModal set to false

  submitForm: function(form) {

    FormSubmission.submitForm(form, false);

  },

  // Submits the form via AJAX

  submitForm: function(form, isModal) {

    var url = form.attr('action');

    // Make an AJAX request to the form's action URL

    $.ajax({

      method: "POST",

      url: url,

      data: form.serialize(),

      myForm: form,

      isModal: isModal,

      // Handle the response from the server

      success: function(data) {

        FormSubmission.postFormSubmission($(this).myForm, $(this).isModal, data);

      },

      // Handle any errors

      error: function(jqXHR, textStatus, errorThrown) {

        console.log(textStatus, errorThrown);

      }

    });

  },

  // Submits the form via AJAX with support for file uploads

  submitFormWithFiles: function(form, isModal) {

    var url = form.attr('action');

    // Make an AJAX request to the form's action URL with support for file uploads

    form.ajaxSubmit({

      method: 'POST',

      url: url,

      myForm: form,

      isModal: isModal,

      // Handle the response from the server

      success: function(data) {

        FormSubmission.postFormSubmission($(this).myForm, $(this).isModal, data);

      },

      //

auth()->user()->name;
auth()->id();

be sure that you are logged in. and use that


composer create-project --prefer-dist laravel/laravel:8.6.11 blog


composer create-project laravel/laravel:^8.0 example --ignore-platform-reqs
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$referer = $_SERVER['HTTP_REFERER'];
$language = $_SERVER['HTTP_ACCEPT_LANGUAGE'];

echo "IP address: $ip<br>";
echo "User agent: $user_agent<br>";
echo "Referrer: $referer<br>";
echo "Preferred language(s): $language<br>";
?>
public function stkpush(Request $request)
{
    $url='https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest';

    $curl_post_data=[
        'BusinessShortCode'=>174379,
        'Password'=>$this->lipanampesapassword(),
        'Timestamp'=>Carbon::rawParse('now')->format('YmdHms'),

        'TransactionType'=> "CustomerPayBillOnline",
        'Amount'=>1,
        'PartyA'=>254712345678,
        'PartyB'=>174379,
        'PhoneNumber'=>254712345678,
        'CallBackURL'=>'https://89af-196-202-210-53.eu.ngrok.io/api/mpesa/callbackurl',
        'AccountReference'=>'Waweru Enterprises',
        'TransactionDesc'=>'Paying for Products Bought'
    ];

    $data_string=json_encode($curl_post_data);

    $curl=curl_init();
    curl_setopt($curl,CURLOPT_URL,$url);
    curl_setopt($curl,CURLOPT_HTTPHEADER,array('Content-Type:application/json','Authorization:Bearer '.$this->newaccesstoken()));
    curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($curl,CURLOPT_POST,true);
    curl_setopt($curl,CURLOPT_POSTFIELDS,$data_string);

    $curl_response=curl_exec($curl);
    return $curl_response;
}
<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;

class MempelaiController extends Controller
{
    public function getDataMempelaiPria(Request $request)
    {
        $dataMempelaiPria = $request->user()->mempelai_pria;
        return response()->json([
            'message' => 'success',
            'data' => $dataMempelaiPria
        ]);
    }

    public function getDataMempelaiWanita(Request $request)
    {
        $dataMempelaiWanita = $request->user()->mempelaiWanitaApi;
        return response()->json([
            'message' => 'success',
            'data' => $dataMempelaiWanita
        ]);
    }

    public function storeDataMempelai(Request $request)
    {
        $user = User::find($request->user()->id);
        $dataMempelaiPria = $request->dataMempelaiPria;
        $dataMempelaiWanita = $request->dataMempelaiWanita;
        $dataNull = $request->dataNull;

        if ($dataNull['dataMempelaiPria'] === 'true') {
            $user->MempelaiPriaApi()->create([
                'user_id' => $user->id,
                'nama_lengkap' => ucfirst($dataMempelaiPria['nama_lengkap']),
                'nama_panggilan' => ucfirst($dataMempelaiPria['nama_panggilan']),
                'tempat_lahir' => $dataMempelaiPria['tempat_lahir'],
                'tanggal_lahir' => $dataMempelaiPria['tanggal_lahir'],
                'nama_ayah' => $dataMempelaiPria['nama_ayah'],
                'nama_ibu' => $dataMempelaiPria['nama_ibu'],
                'foto' => 'default',
                'tampilkan_foto' => 'false',
                'instagram' =>  'null',
                'facebook' => 'null',
                'twitter' => 'null',
            ]);
        } else {
            $user->MempelaiPriaApi()->update([
                'user_id' => $user->id,
                'nama_lengkap' => ucfirst($dataMempelaiPria['nama_lengkap']),
                'nama_panggilan' => ucfirst($dataMempelaiPria['nama_panggilan']),
                'tempat_lahir' => $dataMempelaiPria['tempat_lahir'],
                'tanggal_lahir' => $dataMempelaiPria['tanggal_lahir'],
                'nama_ayah' => $dataMempelaiPria['nama_ayah'],
                'nama_ibu' => $dataMempelaiPria['nama_ibu'],
                'foto' => 'default',
                'tampilkan_foto' => 'false',
                'instagram' =>  'null',
                'facebook' => 'null',
                'twitter' => 'null',
            ]);
        }

        if ($dataNull['dataMempelaiWanita'] === 'true') {
            $user->mempelaiWanitaApi()->create([
                'user_id' => $user->id,
                'nama_lengkap' => ucfirst($dataMempelaiWanita['nama_lengkap']),
                'nama_panggilan' => ucfirst($dataMempelaiWanita['nama_panggilan']),
                'tempat_lahir' => $dataMempelaiWanita['tempat_lahir'],
                'tanggal_lahir' => $dataMempelaiWanita['tanggal_lahir'],
                'nama_ayah' => $dataMempelaiWanita['nama_ayah'],
                'nama_ibu' => $dataMempelaiWanita['nama_ibu'],
                'foto' => 'default',
                'tampilkan_foto' => 'false',
                'instagram' =>  'null',
                'facebook' => 'null',
                'twitter' => 'null',
            ]);
        } else {
            $user->mempelaiWanitaApi()->update([
                'user_id' => $user->id,
                'nama_lengkap' => ucfirst($dataMempelaiWanita['nama_lengkap']),
                'nama_panggilan' => ucfirst($dataMempelaiWanita['nama_panggilan']),
                'tempat_lahir' => $dataMempelaiWanita['tempat_lahir'],
                'tanggal_lahir' => $dataMempelaiWanita['tanggal_lahir'],
                'nama_ayah' => $dataMempelaiWanita['nama_ayah'],
                'nama_ibu' => $dataMempelaiWanita['nama_ibu'],
                'foto' => 'default',
                'tampilkan_foto' => 'false',
                'instagram' =>  'null',
                'facebook' => 'null',
                'twitter' => 'null',
            ]);
        }

        return response()->json([
            'message' => 'success',
            'data' => $user
        ]);
    }

    public function storeMempelaiPria(Request $request)
    {
        $user = User::find($request->user()->id);
        $dataMempelaiPria = $request->dataMempelaiPria;

        $user->MempelaiPriaApi()->create([
            'user_id' => $user->id,
            'nama_lengkap' => ucfirst($dataMempelaiPria['nama_lengkap']),
            'nama_panggilan' => ucfirst($dataMempelaiPria['nama_panggilan']),
            'tempat_lahir' => $dataMempelaiPria['tempat_lahir'],
            'tanggal_lahir' => Carbon::parse(strtr($dataMempelaiPria['tanggal_lahir'], '/', '-'))->format('Y-m-d'),
            'nama_ayah' => $dataMempelaiPria['nama_ayah'],
            'nama_ibu' => $dataMempelaiPria['nama_ibu'],
            'foto' => 'default',
            'tampilkan_foto' => 'false',
            'instagram' =>  'null',
            'facebook' => 'null',
            'twitter' => 'null',
        ]);


        return response()->json([
            'message' => 'success',
            'data' => $user
        ]);
    }

    public function updateMempelaiPria(Request $request)
    {
        $user = User::find($request->user()->id);
        $dataMempelaiPria = $request->dataMempelaiPria;

        $user->MempelaiPriaApi()->update([
            'user_id' => $user->id,
            'nama_lengkap' => ucfirst($dataMempelaiPria['nama_lengkap']),
            'nama_panggilan' => ucfirst($dataMempelaiPria['nama_panggilan']),
            'tempat_lahir' => $dataMempelaiPria['tempat_lahir'],
            'tanggal_lahir' => Carbon::parse(strtr($dataMempelaiPria['tanggal_lahir'], '/', '-'))->format('Y-m-d'),
            'nama_ayah' => $dataMempelaiPria['nama_ayah'],
            'nama_ibu' => $dataMempelaiPria['nama_ibu'],
            'foto' => 'default',
            'tampilkan_foto' => 'false',
            'instagram' =>  'null',
            'facebook' => 'null',
            'twitter' => 'null',
        ]);

        return response()->json([
            'message' => 'success',
            'data' => $user
        ]);
    }

    public function storeMempelaiWanita(Request $request)
    {
        $user = User::find($request->user()->id);
        $dataMempelaiWanita = $request->dataMempelaiWanita;

        $user->mempelaiWanitaApi()->create([
            'user_id' => $user->id,
            'nama_lengkap' => ucfirst($dataMempelaiWanita['nama_lengkap']),
            'nama_panggilan' => ucfirst($dataMempelaiWanita['nama_panggilan']),
            'tempat_lahir' => $dataMempelaiWanita['tempat_lahir'],
            'tanggal_lahir' => Carbon::parse(strtr($dataMempelaiWanita['tanggal_lahir'], '/', '-'))->format('Y-m-d'),
            'nama_ayah' => $dataMempelaiWanita['nama_ayah'],
            'nama_ibu' => $dataMempelaiWanita['nama_ibu'],
            'foto' => 'default',
            'tampilkan_foto' => 'false',
            'instagram' =>  'null',
            'facebook' => 'null',
            'twitter' => 'null',
        ]);

        $namaPanggilanMempelaiPria = $user->mempelaiPriaApi->nama_panggilan;

        $user->settingUndanganApi()->create([
            'user_id' => $user->id,
            'domain' => $namaPanggilanMempelaiPria . '-' . $dataMempelaiWanita['nama_panggilan'],
            'judul_undangan' => $namaPanggilanMempelaiPria . ' & ' . $dataMempelaiWanita['nama_panggilan'],
        ]);

        return response()->json([
            'message' => 'success',
            'data' => $user
        ]);
    }

    public function updateMempelaiWanita(Request $request)
    {
        $user = User::find($request->user()->id);
        $dataMempelaiWanita = $request->dataMempelaiWanita;

        $user->mempelaiWanitaApi()->update([
            'user_id' => $user->id,
            'nama_lengkap' => ucfirst($dataMempelaiWanita['nama_lengkap']),
            'nama_panggilan' => ucfirst($dataMempelaiWanita['nama_panggilan']),
            'tempat_lahir' => $dataMempelaiWanita['tempat_lahir'],
            'tanggal_lahir' => Carbon::parse(strtr($dataMempelaiWanita['tanggal_lahir'], '/', '-'))->format('Y-m-d'),
            'nama_ayah' => $dataMempelaiWanita['nama_ayah'],
            'nama_ibu' => $dataMempelaiWanita['nama_ibu'],
            'instagram' => $dataMempelaiWanita['instagram'] ?? 'null',
        ]);

        return response()->json([
            'message' => 'success',
            'data' => $user
        ]);
    }
}
@extends('layouts.master')

@section('title', 'Pendaftaran')

@section('content')
    <x-navigation.navbar />
    <main class="hero min-h-screen bg-base-200">
        <div class="hero-content my-6">
            <section>
                <div class="w-full max-w-xl flex-shrink-0">
                    <ol class="border-l-2 border-blue-600">
                        <li>
                            <div class="flex-start flex items-center">
                                <div class="-ml-2 mr-3 -mt-2 flex h-4 w-4 items-center justify-center rounded-full bg-blue-600">
                                </div>
                                <h4 class="-mt-2 text-xl font-semibold text-gray-800">Daftar Akun</h4>
                            </div>

                            <div class="ml-6" id="pendaftaran">
                                <p class="-ml-1 text-sm text-green-500">Pendaftaran berhasil.</p>
                            </div>
                        </li>

                        <li class="{{ $dataMempelaiPria === null ? 'pb-6' : '' }} pt-6" id="section-mempelai-pria">
                            <div class="flex-start flex cursor-pointer items-center">
                                <div class="-ml-2 mr-3 -mt-2 flex h-4 w-4 items-center justify-center rounded-full bg-blue-600">
                                </div>
                                <h4 class="-mt-2 text-xl font-semibold text-gray-800">Profile Mempelai Pria</h4>
                            </div>
                            <div class="{{ $dataMempelaiPria === null ? '' : 'hidden' }} ml-6" id="form-mempelai-pria">
                                <p class="desc-timeline">Silahkan isi formulir dengan lengkap.</p>
                                @include('user.complete-register.partials.formMempelaiPria')
                            </div>

                            <div class="{{ $dataMempelaiPria === null ? 'hidden' : '' }} ml-6" id="form-mempelai-pria-not-null">
                                <p class="-ml-1 text-sm text-green-500">Informasi profile mempelai pria sudah lengkap.</p>
                            </div>
                        </li>

                        <li class="{{ $dataMempelaiPria === null ? 'hidden' : '' }} pt-6 pb-6" id="section-mempelai-wanita">
                            <div class="flex-start flex cursor-pointer items-center">
                                <div class="-ml-2 mr-3 -mt-2 flex h-4 w-4 items-center justify-center rounded-full bg-blue-600">
                                </div>
                                <h4 class="-mt-2 text-xl font-semibold text-gray-800">Profile Mempelai Wanita </h4>
                            </div>
                            <div class="{{ $dataMempelaiWanita === null ? '' : 'hidden' }} ml-6" id="form-wanita">
                                <p class="desc-timeline">Silahkan isi formulir dengan lengkap.</p>
                                @include('user.complete-register.partials.formMempelaiWanita')
                            </div>

                            <div class="{{ $dataMempelaiWanita === null ? 'hidden' : '' }} ml-6" id="form-mempelai-wanita-not-null">
                                <p class="-ml-1 text-sm text-green-500">Informasi profile mempelai Wanita sudah lengkap.</p>
                            </div>
                        </li>

                    </ol>
                </div>
            </section>
        </div>
    </main>

    <x-toast-alert id="toast-success" type="success" message="Berhasil." />
@endsection

@push('scripts')
    <script>
        flatpickr("#tanggal-lahir-pria", {
            locale: "id",
            dateFormat: "d/m/Y",
        });

        flatpickr("#tanggal-lahir-wanita", {
            locale: "id",
            dateFormat: "d/m/Y",
        });
    </script>
    <script type="module">
        // Variabel
        $('#footer').addClass('hidden')
        var dataMempelaiPria = @json($dataMempelaiPria);
        var dataMempelaiWanita = @json($dataMempelaiWanita);

        var dataNull = {
            'dataMempelaiPria' : dataMempelaiPria !== null ? false : true,
            'dataMempelaiWanita' : dataMempelaiWanita !== null ? false : true,
        }

        if(dataMempelaiPria === null){
            $('html, body').animate({
                scrollTop: $("#section-mempelai-pria").offset().top
            }, 1000);
        } else if(dataMempelaiWanita === null){
            $('html, body').animate({
                scrollTop: $("#section-mempelai-wanita").offset().top
            }, 1000);
        }

        $('#handleStoreDataMempelaiPria').click(function(){
            storeDataMempelaiPria()
        })

        $('#handleStoreDataMempelaiwanita').click(function(){
            storeDataMempelaiWanita()
        })

        function storeDataMempelaiPria() {
            var dataMempelaiPria = {
                id: $('#id-pria').val(),
                nama_lengkap: $('#nama-lengkap-pria').val(),
                nama_panggilan: $('#nama-panggilan-pria').val(),
                tanggal_lahir: $('#tanggal-lahir-pria').val(),
                tempat_lahir: $('#tempat-lahir-pria').val(),
                nama_ayah: $('#nama-ayah-pria').val(),
                nama_ibu: $('#nama-ibu-pria').val(),
                instagram: $('#instagram-pria').val(),
            }

            $.ajax({
                url: `${dataNull.dataMempelaiPria === false ? '/mempelai/update-data-mempelai-pria' : '/mempelai/store-data-mempelai-pria'}`,
                type: 'GET',
                dataType: 'json',
                data: {
                    dataMempelaiPria,
                    dataNull,
                },
                beforeSend: function() {
                    $('.btn-handle').html('Loading...').addClass('opacity-50 cursor-not-allowed');
                },
                error: function(error) {
                    $('.btn-handle').html('Coba lagi').removeClass('opacity-50 cursor-not-allowed').addClass('bg-red-500');
                },
                success: function(response) {
                    $('#toast-success').removeClass('hidden');
                    $('.btn-handle').html('Lanjutkan').removeClass('opacity-50 cursor-not-allowed');
                    setTimeout(() => {
                       $('#toast-success').addClass('hidden')
                    }, 3000);
                    $('#section-mempelai-wanita').removeClass('hidden').addClass('pb-6')
                    $('#section-mempelai-pria').removeClass('pb-6')
                    $('#form-mempelai-pria').addClass('hidden')
                    $('#form-mempelai-pria-not-null').removeClass('hidden')
                    $('html, body').animate({
                        scrollTop: $("#section-mempelai-wanita").offset().top
                    }, 1000);
                    getDataMempelaiPria()
                }
            });
        }

        function storeDataMempelaiWanita(){
            var dataMempelaiWanita = {
                id: $('#id-wanita').val(),
                nama_lengkap: $('#nama-lengkap-wanita').val(),
                nama_panggilan: $('#nama-panggilan-wanita').val(),
                tanggal_lahir: $('#tanggal-lahir-wanita').val(),
                tempat_lahir: $('#tempat-lahir-wanita').val(),
                nama_ayah: $('#nama-ayah-wanita').val(),
                nama_ibu: $('#nama-ibu-wanita').val(),
                instagram: $('#instagram-wanita').val(),
            }

            $.ajax({
                url: `${dataNull.dataMempelaiWanita === false ? '/mempelai/update-data-mempelai-wanita' : '/mempelai/store-data-mempelai-wanita'}`,
                type: 'GET',
                dataType: 'json',
                data: {
                    dataMempelaiWanita,
                    dataNull,
                },
                beforeSend: function() {
                    $('.btn-handle').html('Loading...').addClass('opacity-50 cursor-not-allowed');
                },
                error: function(error) {
                    $('.btn-handle').html('Coba lagi').removeClass('opacity-50 cursor-not-allowed').addClass('bg-red-500');
                },
                success: function(response) {
                    $('#toast-success').removeClass('hidden');
                    $('.btn-handle').html('Lanjutkan').removeClass('opacity-50 cursor-not-allowed');
                    setTimeout(() => {
                       $('#toast-success').addClass('hidden')
                    }, 3000);
                    $('#section-mempelai-wanita').removeClass('pb-6')
                    $('#form-wanita').addClass('hidden')
                    $('html, body').animate({
                        scrollTop: $("#section-mempelai-wanita").offset().top
                    }, 1000);
                    window.location.href = '/dashboard'
                }
            });
        }
</script>
@endpush
function time_elapsed_string($ptime)
{
    $etime = $ptime - time();

    if ($etime < 1)
    {
        return '0 seconds';
    }

    $a = array( 365 * 24 * 60 * 60  =>  'year',
                 30 * 24 * 60 * 60  =>  'month',
                      24 * 60 * 60  =>  'day',
                           60 * 60  =>  'hour',
                                60  =>  '',
                                 1  =>  ''
                );
    $a_plural = array( 'year'   => 'years',
                       'month'  => 'months',
                       'day'    => 'days',
                       'hour'   => 'hours',
                       'minute' => '',
                       'second' => ''
                );

    foreach ($a as $secs => $str)
    {
        $d = $etime / $secs;
        if ($d >= 1)
        {
            $r = round($d);
            return $r . '' . ($r > 1 ? $a_plural[$str] : $str);
        }
    }
}
<?php
// Original Answer
header('Content-Type: application/json');
$request = file_get_contents('php://input');
$req_dump = print_r( $request, true );
$fp = file_put_contents( 'request.log', $req_dump );

// Updated Answer
if($json = json_decode(file_get_contents("php://input"), true)){
   $data = $json;
}
print_r($data);
?>
$data = Project::limit(100)->get();
return ProjectResource::collection($data)->additional(['some_id => 1']);
// Empty data and rules
$validator = \Validator::make([], []);

// Add fields and errors
$validator->errors()->add('fieldName', 'This is the error message');

throw new \Illuminate\Validation\ValidationException($validator);
    $inputs = [
        'email'    => 'foo',
        'password' => 'bar',
    ];

    $rules = [
        'email'    => 'required|email',
        'password' => [
            'required',
            'string',
            'min:10',             // must be at least 10 characters in length
            'regex:/[a-z]/',      // must contain at least one lowercase letter
            'regex:/[A-Z]/',      // must contain at least one uppercase letter
            'regex:/[0-9]/',      // must contain at least one digit
            'regex:/[@$!%*#?&]/', // must contain a special character
        ],
    ];

    $validation = \Validator::make( $inputs, $rules );

    if ( $validation->fails() ) {
        print_r( $validation->errors()->all() );
    }
$event_startdate_raw = intval(get_field('start_date', false, false)) / 1000;
    $event_startdate = new DateTime();
    $event_startdate->setTimestamp($event_startdate_raw)
    $event_startdate->setTimezone(new DateTimeZone(timezone_name_from_abbr('',  get_option('gmt_offset') * 3600, 0)));
    $event_startdate_jMY = $event_startdate->format('j M Y');
// Display Object or Array
public function oa($model)
{
    if (gettype($model) === 'object') {
        dump(get_class($model));
        dump($model->toArray());
    } else {
        dump(gettype($model));
        dump($model);
    }
}
// Display string
public function s($model)
{
    dump($model);
}
<?php
//toXML.php

//create new XML doc
$xmlDoc = new DOMDocument('1.0', 'utf-8');
$xmlDoc->formatOutput = true;

//build XML File  with root element
$xmlRoot = $xmlDoc -> createElement('person');
$xmlDoc->appendChild($xmlRoot);

//build childs of root element
$xmlGender = $xmlDoc->createElement('gender', 'female');
$xmlRoot->appendChild($xmlGender);

$xmlVorname = $xmlDoc->createElement('vorname', 'Eva');
$xmlRoot->appendChild($xmlVorname);

$xmlNachname = $xmlDoc->createElement('nachname', 'Lurch');
$xmlRoot->appendChild($xmlNachname);


$filename = "person.xml";
$xmlDoc->save($filename);

?>
<?php

$dataname = "e2fi1.csv";

$fp = fopen($dataname, "r");

//first line of csv is header, needs to be read out seperately
//fgetcsv macht automatisch weiter bei der nächsten Zeile, merkt sich wo der pointer steht
$row_header = fgetcsv($fp, null, ";");
$row_header_nummer = $row_header[0];
$row_header_vorname = $row_header[1];
$row_header_nachname = $row_header[2];

//create XML
$xml_doc = new DOMDocument('1.0', 'utf-8');
$xml_doc->formatOutput = true;

//build XML file with root element
$xml_root = $xml_doc->createElement('klasse_e2fi1');
$xml_doc->appendChild($xml_root);

//create string from CSV
while (!feof($fp)) {
    $row_a = fgetcsv($fp, null, ";");

    if (empty($row_a)) {
        continue;
    }

    $schueler_nummer = $row_a[0];
    $schueler_vorname = $row_a[1];
    $schueler_nachname = $row_a[2];

    //create sub element for students
    $xml_student = $xml_doc->createElement('schueler');
    $xml_student->setAttribute("nr", $schueler_nummer);
    $xml_root->appendChild($xml_student);

    //create element that fills the
    $xml_vorname = $xml_doc->createElement($row_header_vorname, $schueler_vorname);
    $xml_student->appendChild($xml_vorname);

    $xml_nachname = $xml_doc->createElement($row_header_nachname, $schueler_nachname);
    $xml_student->appendChild($xml_nachname);
}

$xml_filename = "klasse1fi1.xml";
$xml_doc->save($xml_filename);
<?php
require_once('class.excel_xml.php');

$xls = new excel_xml; // initiate the class

$xls->set_titles(array('title one','title two','title three')); // optional: sets the titles of the spreadsheet columns

// adding 6 rows to the spreadsheet

$xls->add_row(array('text',-22.2,'bla bla')); // first row

$xls->add_row(array('1500.3',14.5,'bingo!')); // second row

$xls->add_row(array('2014-11-01',14.5,'a date in cell A4!!')); // third row

$xls->add_row(array('Timestamp in cell C5',14.5,'2014-11-01 12:00:10','extra data, a longer text')); // fourth row

$xls->add_row(array()); // fifth (empty) row

$xls->add_row(array('Time in cell C7',14.5,'12:00:10'));// sixth row

// writes output to file.xml (check please write permissions)
//$xls->output('file'); // comment it out to enable writing

// send the data to the browser
$xls->output();
<?php
/** create XML file */ 
$mysqli = new mysqli("localhost", "root", "", "dbbookstore");
/* check connection */
if ($mysqli->connect_errno) {
   echo "Connect failed ".$mysqli->connect_error;
   exit();
}
$query = "SELECT id, title, author_name, price, ISBN, category FROM books";
$booksArray = array();
if ($result = $mysqli->query($query)) {
    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {
       array_push($booksArray, $row);
    }
  
    if(count($booksArray)){
         createXMLfile($booksArray);
     }
    /* free result set */
    $result->free();
}
/* close connection */
$mysqli->close();
function createXMLfile($booksArray){
  
   $filePath = 'book.xml';
   $dom     = new DOMDocument('1.0', 'utf-8'); 
   $root      = $dom->createElement('books'); 
   for($i=0; $i<count($booksArray); $i++){
     
     $bookId        =  $booksArray[$i]['id'];  
     $bookName = htmlspecialchars($booksArray[$i]['title']);
     $bookAuthor    =  $booksArray[$i]['author_name']; 
     $bookPrice     =  $booksArray[$i]['price']; 
     $bookISBN      =  $booksArray[$i]['ISBN']; 
     $bookCategory  =  $booksArray[$i]['category'];  
     $book = $dom->createElement('book');
     $book->setAttribute('id', $bookId);
     $name     = $dom->createElement('title', $bookName); 
     $book->appendChild($name); 
     $author   = $dom->createElement('author', $bookAuthor); 
     $book->appendChild($author); 
     $price    = $dom->createElement('price', $bookPrice); 
     $book->appendChild($price); 
     $isbn     = $dom->createElement('ISBN', $bookISBN); 
     $book->appendChild($isbn); 
     
     $category = $dom->createElement('category', $bookCategory); 
     $book->appendChild($category);
 
     $root->appendChild($book);
   }
   $dom->appendChild($root); 
   $dom->save($filePath); 
 } 
function createXMLfile($booksArray){
  
   $filePath = 'book.xml';

   $dom     = new DOMDocument('1.0', 'utf-8'); 

   $root      = $dom->createElement('books'); 

   for($i=0; $i<count($booksArray); $i++){
     
     $bookId        =  $booksArray[$i]['id'];  

     $bookName      =   htmlspecialchars($booksArray[$i]['title']);

     $bookAuthor    =  $booksArray[$i]['author_name']; 

     $bookPrice     =  $booksArray[$i]['price']; 

     $bookISBN      =  $booksArray[$i]['ISBN']; 

     $bookCategory  =  $booksArray[$i]['category'];  

     $book = $dom->createElement('book');

     $book->setAttribute('id', $bookId);

     $name     = $dom->createElement('title', $bookName); 

     $book->appendChild($name); 

     $author   = $dom->createElement('author', $bookAuthor); 

     $book->appendChild($author); 

     $price    = $dom->createElement('price', $bookPrice); 

     $book->appendChild($price); 

     $isbn     = $dom->createElement('ISBN', $bookISBN); 

     $book->appendChild($isbn); 
     
     $category = $dom->createElement('category', $bookCategory); 

     $book->appendChild($category);
 
     $root->appendChild($book);

   }

   $dom->appendChild($root); 

   $dom->save($filePath); 

 } 
<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content=
		"width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">

	<link rel="stylesheet" href=
"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
	<title>Attendance Page</title>
</head>

<body>
	<div class="container">
		<div class="row">
			<h2>Attendance</h2>
			<table class="table table-hover">
				<thead>
					<tr>
						<th>Sno.</th>
						<th>Student Name</th>
						<th>Attendance</th>
					</tr>
				</thead>

				<tbody>
					<?php
						include_once('connection.php');
						$a=1;
						$stmt = $conn->prepare("SELECT * FROM kundendaten");
						$stmt->execute();
						$users = $stmt->fetchAll();
						foreach($users as $user)
						{
					?>
					<tr>
						<td>
							<?php echo $user['id']; ?>
						</td>
						<td>
							<?php echo $user['studentname']; ?>
						</td>

						<td>
							<div class="form-check form-check-inline">
								<input class="form-check-input"
										type="radio" name="''"
										
										id="inlineRadio1"
									value="'..$a..'">
								<label class="form-check-label"
									for="inlineRadio1">A</label>
							</div>

							<div class="form-check form-check-inline">
								<input class="form-check-input"
									type="radio" name="'..$a..'"
									id="inlineRadio2" value="option2">

								<label class="form-check-label"
									for="inlineRadio2">P</label>
							</div>
						</td>
					</tr>
					<?php
					}
					?>
				</tbody>
			</table>

			<input class="btn btn-primary"
					type="submit" value="Submit">
		</div>
	</div>
</body>

</html>
.ssh directory: 700 (drwx------)
public key (.pub file): 644 (-rw-r--r--)
private key (id_rsa): 600 (-rw-------)
#  Home directory
lastly your home directory should not be writeable by the group or others (default 755 (drwxr-xr-x)).
 If you are looking for better security and privacy, you can change the default permissions to 750.
request()->validate([
            'name'=>'required',
            'email'=>'required|email',
            'subject'=>'required'
        ]);