/**
 * Theme Name:     Astra Child enfant
 * Author:         Brainstorm Force
 * Template:       astra
 * Text Domain:	   astra-child-enfant
 * Description:    The Astra WordPress theme is lightning-fast and highly customizable. It has over 1 million downloads and the only theme in the world with 5,700+ five-star reviews! It’s ideal for professional web designers, solopreneurs, small businesses, eCommerce, membership sites and any type of website. It offers special features and templates so it works perfectly with all page builders like Spectra, Elementor, Beaver Builder, etc. Fast performance, clean code, mobile-first design and schema markup are all built-in, making the theme exceptionally SEO-friendly. It’s fully compatible with WooCommerce, SureCart and other eCommerce plugins and comes with lots of store-friendly features and templates. Astra also provides expert support for free users. A dedicated team of fully trained WordPress experts are on hand to help with every aspect of the theme. Try the live demo of Astra: https://zipwp.org/themes/astra/
 */
/* === MAROC PACLEAN – My Account (Mobile-first) === */
:root{
  --brand:#4EA3CB;          /* bleu MP */
  --brand-dark:#3a8fb0;
  --ink:#1f2937;            /* texte principal */
  --muted:#6b7280;          /* texte secondaire */
  --bg:#f7fafc;
  --radius:14px;
  --shadow:0 6px 18px rgba(0,0,0,.06);
}

/* Conteneur général */
.woocommerce-account .entry-content,
.woocommerce-MyAccount-content{
  color:var(--ink);
  line-height:1.5;
}

/* Titre */
.woocommerce-account h2, .woocommerce-account h1{
  font-weight:700;
  letter-spacing:.2px;
  margin:8px 0 14px;
}

/* NAV : cartes jolies + grandes zones de tap */
.woocommerce-MyAccount-navigation ul{
  list-style:none;
  margin:0 0 16px;
  padding:0;
  display:grid;
  grid-template-columns:1fr;
  gap:10px;
}
.woocommerce-MyAccount-navigation li a{
  display:flex; align-items:center; gap:10px;
  padding:14px 16px;
  background:#fff;
  border:1px solid #e5e7eb;
  border-radius:var(--radius);
  box-shadow:var(--shadow);
  text-decoration:none;
  color:var(--ink);
  font-weight:600;
  transition:.2s ease;
}
.woocommerce-MyAccount-navigation li a:hover{
  transform:translateY(-1px);
  border-color:var(--brand);
}
.woocommerce-MyAccount-navigation li.is-active a{
  border-color:var(--brand);
  box-shadow:0 0 0 3px rgba(78,163,203,.15);
}

/* Icônes simples (emoji) selon l’onglet */
.woocommerce-MyAccount-navigation-link--dashboard a::before{content:"🏠"; margin-right:6px}
.woocommerce-MyAccount-navigation-link--orders a::before{content:"📦"; margin-right:6px}
.woocommerce-MyAccount-navigation-link--edit-address a::before{content:"🏠"; margin-right:6px}
.woocommerce-MyAccount-navigation-link--edit-account a::before{content:"👤"; margin-right:6px}
.woocommerce-MyAccount-navigation-link--customer-logout a::before{content:"🚪"; margin-right:6px}
/* Tes onglets custom si tu les as créés */
.woocommerce-MyAccount-navigation-link--mp-invoices a::before{content:"🧾"; margin-right:6px}
.woocommerce-MyAccount-navigation-link--mp-support a::before{content:"💬"; margin-right:6px}

/* Contenu : carte propre */
.woocommerce-MyAccount-content{
  background:#fff;
  border:1px solid #e5e7eb;
  border-radius:var(--radius);
  box-shadow:var(--shadow);
  padding:16px;
}

/* Boutons */
.woocommerce a.button, .woocommerce button.button, .woocommerce input.button{
  background:var(--brand);
  border:1px solid var(--brand);
  color:#fff;
  border-radius:12px;
  padding:10px 16px;
  font-weight:700;
  transition:.2s ease;
}
.woocommerce a.button:hover, .woocommerce button.button:hover, .woocommerce input.button:hover{
  background:var(--brand-dark);
  border-color:var(--brand-dark);
}

/* Champs formulaires */
.woocommerce form .form-row input.input-text,
.woocommerce form .form-row textarea,
.woocommerce form .form-row select{
  border-radius:12px;
  border:1px solid #e5e7eb;
  padding:10px 12px;
  background:#fff;
}
.woocommerce form .form-row .password-input{
  position:relative;
}
.woocommerce-password-strength, .woocommerce-password-hint{
  font-size:12px; color:var(--muted);
}

/* Cartes “raccourcis” si tu les affiches dans le dashboard */
.mp-cards{display:grid;grid-template-columns:1fr;gap:10px;margin:12px 0}
.mp-card{display:flex;align-items:center;gap:10px;padding:14px;border:1px solid #e5e7eb;border-radius:var(--radius);box-shadow:var(--shadow);text-decoration:none;color:var(--ink);font-weight:600}
.mp-card:hover{border-color:var(--brand)}

/* Table commandes -> style cartes (mobile) */
.woocommerce-account .my_account_orders .order{
  background:#fff;border:1px solid #e5e7eb;border-radius:12px;box-shadow:var(--shadow);margin-bottom:10px;padding:12px;
}
.woocommerce table.shop_table{
  border:0;border-radius:12px;box-shadow:none;
}
.woocommerce table.shop_table th{
  color:var(--muted); font-weight:600;
}

/* Alerte/notice WooCommerce */
.woocommerce-message, .woocommerce-error, .woocommerce-info{
  border-radius:12px;
  border:none;
  box-shadow:var(--shadow);
}

/* Footer bar promo (bandeau) si tu veux le rendre discret */
.site-footer .notice, .cookie-notice, .promo-bar{
  border-radius:12px;
}

/* Responsive Desktop : grille nav à 2-3 colonnes */
@media (min-width:768px){
  .woocommerce-MyAccount-navigation ul{grid-template-columns:repeat(2,minmax(0,1fr))}
}
@media (min-width:1024px){
  .woocommerce-MyAccount-navigation ul{grid-template-columns:repeat(3,minmax(0,1fr))}
}
/* 1) تسجيل endpoint جديد: /my-account/consommation */
add_action('init', function(){
  add_rewrite_endpoint('consommation', EP_ROOT | EP_PAGES);
});
add_filter('query_vars', function($vars){ $vars[] = 'consommation'; return $vars; });

/* 2) زِد عنصر المينيو فـ My Account */
add_filter('woocommerce_account_menu_items', function($items){
  // نخلي "Consommation" من بعد "orders"
  $new = [];
  foreach($items as $key=>$label){
    $new[$key] = $label;
    if($key==='orders'){ $new['consommation'] = __('Consommation','mpc'); }
  }
  return $new;
});

/* 3) محتوى تبويب consommation: جدول يومي + Top produits + Export CSV  */
add_action('woocommerce_account_consommation_endpoint', function(){
  echo '<h3>Consommation</h3>';
  echo '<p>Sélectionnez la période puis exportez en CSV si besoin.</p>';
  // فورم بسيط لاختيار التاريخ
  echo '<form method="get" style="margin:8px 0;">
          <label>Du <input type="date" name="from" value="'.esc_attr( isset($_GET["from"])?$_GET["from"]:"").'"></label>
          <label>Au <input type="date" name="to" value="'.esc_attr( isset($_GET["to"])?$_GET["to"]:"").'"></label>
          <button type="submit">Afficher</button>
          <a href="?export=consumption_csv">Exporter CSV</a>
        </form>';
  // نادْ الشورتكودات اللي عطيتك قبل (راها بلا CSS)
  echo do_shortcode('[mpc_consumption_table]');
  echo '<h4 style="margin-top:16px;">Top produits</h4>';
  echo do_shortcode('[mpc_top_products limit="10"]');
});
/* زر “Commander à nouveau” وسط لائحة الطلبات فـ My Account */
add_filter('woocommerce_my_account_my_orders_actions', function($actions, $order){
  if ( $order->has_status( array('completed','processing') ) ) {
    $actions['reorder'] = array(
      'url'  => wp_nonce_url( add_query_arg('order_again', $order->get_id() ), 'woocommerce-order_again' ),
      'name' => __('↻ Commander à nouveau','mpc'),
    );
  }
  return $actions;
}, 10, 2);

/* زر سريع في Dashboard: إعادة آخر طلب */
add_action('woocommerce_account_dashboard', function(){
  if( ! is_user_logged_in() ) return;
  $u = wp_get_current_user();
  $orders = wc_get_orders(array(
    'customer_id' => $u->ID,
    'status'      => array('wc-completed','wc-processing'),
    'orderby'     => 'date',
    'order'       => 'DESC',
    'limit'       => 1,
  ));
  if(!empty($orders)){
    $o   = $orders[0];
    $url = wp_nonce_url( add_query_arg('order_again', $o->get_id() ), 'woocommerce-order_again' );
    echo '<p><a href="'.esc_url($url).'">↻ Re-commander la dernière commande (#'.$o->get_id().')</a></p>';
  }
});

/* Champ "Prix unitaire (DH/pc)" في المنتج الأب */
add_action('woocommerce_product_options_general_product_data', function(){
  echo '<div class="options_group">';
  woocommerce_wp_text_input([
    'id'    => 'mpc_unit_price',
    'label' => __('Prix unitaire (DH/pc)','mpc'),
    'type'  => 'text',
    'desc_tip' => true,
    'description' => __('Saisis ici le prix/pc. Le prix du pack des variations sera auto-calculé.', 'mpc'),
  ]);
  echo '</div>';
});
add_action('woocommerce_admin_process_product_object', function($product){
  if( isset($_POST['mpc_unit_price']) ){
    $product->update_meta_data('mpc_unit_price', wc_clean($_POST['mpc_unit_price']));
  }
});

/* عند الحفظ: احسب ثمن الباك = (prix unitaire) × (Nombre de pièces) */
add_action('woocommerce_save_product_variation', function($variation_id, $i){
  $variation = wc_get_product($variation_id);
  if( ! $variation ) return;

  // Prix unitaire من المنتج الأب
  $parent = wc_get_product( $variation->get_parent_id() );
  $unit   = (float) ($parent ? $parent->get_meta('mpc_unit_price', true) : 0);

  // جِب عدد القطع من أي مفتاح ممكن (custom/global)
  $pcs = 0;
  $candidates = ['attribute_pieces','attribute_pa_pieces','attribute_pack','attribute_pa_pack'];
  foreach($candidates as $k){
    if(isset($_POST[$k][$i]) && $_POST[$k][$i] !== ''){
      $val = sanitize_text_field($_POST[$k][$i]);
      if(preg_match('/\d+/', $val, $m)){ $pcs = (int)$m[0]; break; }
    }
  }

  // إذا عرّفنا unit و pcs نحسب ثمن الباك ونحفظو
  if($unit > 0 && $pcs > 0){
    $pack = $unit * $pcs;
    update_post_meta($variation_id, '_regular_price', $pack);
    update_post_meta($variation_id, '_price', $pack);
    update_post_meta($variation_id, 'mpc_pieces_in_pack', $pcs); // للحاجة فالعرض
  }
}, 10, 2);

/* عرض "≈ prix/pc" ملي تختار variation */
add_filter('woocommerce_available_variation', function($data,$product,$variation){
  $pcs  = (int) get_post_meta($variation->get_id(),'mpc_pieces_in_pack',true);
  $parent = wc_get_product($variation->get_parent_id());
  $unit = (float) ($parent ? $parent->get_meta('mpc_unit_price', true) : 0);
  if($pcs && $unit){ $data['mpc_pcs']=$pcs; $data['mpc_unit']=$unit; }
  return $data;
},10,3);

add_action('woocommerce_single_product_summary', function(){
  echo '<div id="mpc-unit-info" style="margin-top:6px"></div>'; ?>
  <script>
  jQuery(function($){
    var $f=$('form.variations_form'), $info=$('#mpc-unit-info');
    if(!$f.length) return;
    function show(v){
      if(v && v.mpc_pcs && v.mpc_unit){
        var pack=(v.mpc_pcs * v.mpc_unit).toFixed(2);
        $info.text('≈ ' + v.mpc_unit.toFixed(2) + ' DH / pièce — Pack ' + v.mpc_pcs + ' = ' + pack + ' DH');
      } else { $info.text(''); }
    }
    $f.on('found_variation', function(e,v){ show(v); })
     .on('reset_data', function(){ $info.text(''); });
  });
  </script>
<?php },11);

// يعرض Pièces + ~ السعر/القطعة تحت اسم المنتج فالسلة والـ Checkout
add_filter('woocommerce_get_item_data', function($data,$cart_item){
  $pcs = 0;
  if(!empty($cart_item['variation'])){
    foreach($cart_item['variation'] as $val){
      if(preg_match('/\d+/', $val, $m)){ $pcs = (int)$m[0]; break; }
    }
  }
  if($pcs){
    $pack = wc_get_price_to_display($cart_item['data']);
    $unit = $pcs ? $pack / $pcs : 0;
    $data[] = ['name' => 'Pièces', 'value' => $pcs.' — ~ '.wc_price($unit).' / pièce'];
  }
  return $data;
},10,2);


// Bloc تحت الثمن + JS يحسب prix/pc من ثمن الڤارياسيون وعدد القطع المختارة
add_action('woocommerce_single_product_summary', function () {
  if (!is_product()) return;
  echo '<div id="mpc-unit-price" data-symbol="' . esc_attr( get_woocommerce_currency_symbol() ) . '" style="margin-top:6px"></div>';
  ?>
  <script>
    jQuery(function($){
      var $form = $('form.variations_form');
      var $out  = $('#mpc-unit-price');
      if(!$form.length || !$out.length) return;

      function getPiecesFromSelects() {
        var pcs = 0;
        $form.find('select[name^="attribute_"]').each(function(){
          var name = this.name.toLowerCase();
          if(name.indexOf('piece') !== -1 || name.indexOf('pack') !== -1){
            var txt = $(this).find('option:selected').text();
            var m = txt.match(/(\d+)/);
            if(m){ pcs = parseInt(m[1],10); return false; }
          }
        });
        return pcs;
      }

      function showUnit(v){
        var symbol = $out.data('symbol') || '';
        var price  = v && typeof v.display_price !== 'undefined' ? parseFloat(v.display_price) : NaN;
        var pcs    = getPiecesFromSelects(); // 1,3,10,20...
        if(!isNaN(price) && pcs > 0){
          var unit  = (price / pcs).toFixed(2);
          $out.text('Prix unitaire ≈ ' + unit + ' ' + symbol + ' / pièce');
        } else {
          $out.text('');
        }
      }

      $form.on('found_variation', function(e, v){ showUnit(v); });
      $form.on('reset_data change', function(){ $out.text(''); });
    });
  </script>
  <?php
}, 11);
/* ===== Paclean – styliser les swatches du plugin (boutons lisibles) ===== */
.variations .variable-items-wrapper{display:flex;flex-wrap:wrap;gap:10px}

/* bouton par défaut (non sélectionné) */
.variable-items-wrapper .button-variable-item{
  border:2px solid #1C4478 !important;
  background:#fff !important;
  color:#1C4478 !important;
  border-radius:999px !important;            /* pill */
  min-width:48px !important;
  height:40px !important;
  line-height:38px !important;               /* centrage vertical */
  padding:0 14px !important;
  font-weight:700 !important;
  box-shadow:0 1px 2px rgba(0,0,0,.05) !important;
}

/* forcer la couleur du texte intérieur */
.variable-items-wrapper .button-variable-item .variable-item-span{
  color:inherit !important; opacity:1 !important;
}

/* hover + sélection */
.variable-items-wrapper .button-variable-item:hover,
.variable-items-wrapper .button-variable-item.selected{
  background:#1C4478 !important;
  color:#fff !important;
  border-color:#1C4478 !important;
  box-shadow:0 6px 18px rgba(28,68,120,.22) !important;
}

/* état désactivé */
.variable-items-wrapper .variable-item.disabled{
  opacity:.45 !important; cursor:not-allowed !important;
}

@media (max-width:480px){
  .variable-items-wrapper .button-variable-item{
    min-width:40px !important; height:36px !important; line-height:34px !important; font-size:13px !important;
  }
}

.ib-qty-notice{
  background:#fff7d6;
  border:1px solid #f0d98a;
  border-radius:8px;
  padding:8px 12px;
  font-size:14px;
  line-height:1.4;
  font-weight:600;
  display:inline-block;
  margin:6px 0 10px;
}
.ib-qty-notice--loop{
  font-size:13px;
  margin-top:4px;
}

/* Forcer la barre de recherche à bien s'afficher sur mobile */
.ib-shop-search {
  width: 100%;
  margin: 10px 0;
}

.ib-shop-search .woocommerce-product-search {
  display: flex;
  flex-wrap: nowrap;
  width: 100%;
}

.ib-shop-search .search-field {
  flex: 1;
  min-width: 0;
  padding: 10px;
  font-size: 16px;
}

.ib-shop-search button {
  padding: 10px 14px;
  font-size: 16px;
  white-space: nowrap;
}

/* Ajustement mobile */
@media (max-width: 768px) {
  .ib-shop-search .woocommerce-product-search {
    flex-direction: column;
    gap: 8px;
  }
  .ib-shop-search button {
    width: 100%;
  }
}
.ib-shop-search { margin: 12px 0 18px; }
.ib-shop-search .woocommerce-product-search {
  display: flex; align-items: center; gap: 10px;
}
.ib-shop-search .search-field {
  flex: 1; min-width: 0; padding: 10px 12px;
  border: 1px solid #ddd; border-radius: 10px; font-size: 16px;
}
.ib-shop-search .button {
  padding: 10px 14px; border-radius: 10px; font-size: 16px;
}

/* Mobile */
@media (max-width: 768px){
  .ib-shop-search .woocommerce-product-search { flex-direction: column; }
  .ib-shop-search .button { width: 100%; }
}


