var stars = 1;
var appliedpromo = false;
var adr = "";
var frais ="";
var type="";


$("#btn-cmnt").click(function (e) {
    //alert('rgrgrtgrt');
    //alert(stars);
    $.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
e.preventDefault();

$.ajax({
    url:"/comment/add",
    method:'POST',
    data:{
        'produit':document.getElementsByClassName('id_att')[0].id,
        'comment':$('#comment').val(),
        'stars':stars
    },

    success:function(data){
        
        var st = JSON.parse(JSON.stringify(data));
        console.log(st);
        var html=st.clientdetails.name;
    
        var html = '<div class="uk-card uk-card-small uk-card-body uk-border-rounded uk-background-muted uk-margin-top">'+
        '<div class="uk-flex-between" uk-grid>'+
            '<div>'+
                '<div>'+st.clientdetails.name+'<span></span>'+'  '+st.created_at+'</div>';
            
                
            html+='</div>'+
            '<div>'+
                '<div class="uk-text-secondary">';

            for(i=0;i<stars;i++)
                html +='<span uk-icon="icon: star"></span>'
                
                    
                '</div>'+
            '</div>'+
        '</div>'+
    '</div>';
    










        
        $("#comments").append(html);
        //$('.uk-text-small #comments').html('');
        //$('.uk-text-small #comments').append(html);
        $('#aviscount').html('');
        //$('#aviscount').append('(Avis '+parseInt(@json(count($product->thoughts))+1)+')');
        $('.avnumber').html('');
        //$('.avnumber').append(parseInt(@json(count($product->));
        //@json($product->thoughts)=parseInt(@json($product->thoughts))++
    },

    error: function(jqXHR, textStatus, errorThrown){
        //window.location="http://localhost:8000/login"    
   }         
});


});


function checkout(){
    //alert(adr);
    //adr = document.querySelector('input[name="radio"]:checked').value;
    //alert(adr);
    //alert('hereeee');
    //alert(adr);
    //alert(adr=="");
    //adr = document.querySelector('input[name="radio"]:checked').value;
    //alert(adr);
    //alert($('#'+adr).data('frais'));
    
    
    
    if(adr=="" && type=="domicile") {
        Swal.fire({
            title: 'Veuillez selectionner une adresse',
            icon: 'error',
            confirmButtonText: 'OK'
        })
        return ; 
    
    }else{
        if(type=="domicile")
        adr = document.querySelector('input[name="radio"]:checked').value;
        //alert(adr);
        else adr = null;
    
    $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        //e.preventDefault();
        $.ajax({
        type: 'POST', 
        url: '/commande/add',
        dataType: 'json',
        
        data:{
            'adr':adr,
            'total': parseFloat($('#totalPF').html()),

            },
        success: function () {
            //alert('errerer');
            window.location.href="https://autosupply.orcloudproject.com/mescommandes";  
                
            
        },error:function(){ 
             //console.log("error"); 
            window.location.href="https://autosupply.orcloudproject.com/mescommandes";                  
        }
    });
    }
    
}

function showadr(){
    //adr = document.querySelector('input[name="radio"]:checked').value;
    
    
    /*
    if(@json($free)==true) {
     $('#charges').html('');
     $('#charges1').html('');
     $('#charges1').append(0);
     $('#charges').append(0);
     all=parseInt(@json($total));
             
     $('#sum').html('');
     $('#sum2').html('');
     $('#sum').append(all);
     $('#sum2').append(all);
    */
   
    //}else {
    /*
    $.ajax({
         type: 'GET', 
         url: '/tarif/'+adr,
         dataType: 'json',
         success: function (data) {
             $('#charges').html('');
             $('#charges1').html('');
             var st = JSON.parse(JSON.stringify(data)); 
             
             $('#charges1').append(st[0].prix);
             $('#charges').append(st[0].prix);
             
             all =parseInt(@json($total))+parseInt(st[0].prix);
             $('#sum').html('');
             $('#sum2').html('');
             $('#sum').append(all);
             $('#sum2').append(all);
             $('#modal-center').removeClass('uk-open').hide();
             $('#modal-center').toggle();
    
         },error:function(data){ 
              console.log(data);
         }
    });
    }
    */


     
 
 }


function check(){
       
    var promo = $('#promocode').val();
    if(promo==""){

        if(appliedpromo) {
            all=parseFloat($('#total2').html()) + parseFloat($('#frais_Liv').html());
            $('#totalPF').html(all);  
            $('#totalPF').append(' DZD');  
            $('#applypromo').removeAttr('disabled');
            appliedpromo=false;

        }
    } 
}
$('#applypromo').click(function(e){
    
    var promo = $('#promocode').val();
    //if(promo==""){
      // return  $('#total').html(all);  
         
    var x = $('#frais_Liv').html();
    //}else 
    if(x==0) {
        $('#result').html('veuillez selectionner une adresse');
        return;

    }
    if(appliedpromo==true) {
        $('#result').html('un code promo a deja été appliqué');
        return; 
    }

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    //e.preventDefault();
    $.ajax({
    method: 'POST', 
    url: '/verify',

    
    data:{
        'promo':promo,
        'total':parseFloat($('#totalPF').html())

        },
    success: function (data) {
        if(data=='non applicable') 
            $('#result').html('code non valide');
        else {
            all = parseFloat($('#totalPF').html());
            appliedpromo=true;
           all = Math.round( parseFloat(all) - ((parseFloat(data) * parseFloat(all)  ) / 100));
        
           $('#result').html('');
           //$('#sum').html(all);
           $('#totalPF').html(all);  
           $('#totalPF').append(" DZD");  
           $('#applypromo').attr('disabled','disabled')
         
        }
           

   },
   error:function(){

   }

});
});
   
$('#adr').on('change',function(){
    adr = document.querySelector('input[name="radio"]:checked');
    type = document.querySelector('input[name="radio2"]:checked').value;
    if(type=="domicile"){
        $('#totalPF').html(0);
        if(adr!=null) {
        
                frais  =  parseFloat($('#'+adr).data('frais'));
                $('#frais_Liv').html(frais);
                var x  = parseFloat($("#total2").html()) + frais;
                alert(x);
                $('#totalPF').html(x);
            }else adr ="";
        }else {
                $('#frais_Liv').html(0);
                var x  = parseFloat($("#total2").html());
                $('#totalPF').html(x);
            }
    
    
});

$(".btn-inc").click(function (e) {
    var value = $(this).parent().find('#number').attr('value');
    //alert(value);
    var limit = $(this).parent().find('#limit').attr('value');
    //alert(limit);
    var prix = parseFloat($(this).parent().closest('li').find('.price').find('#prix').html());
    //alert(prix);

    var total = parseFloat($('#total').html());
    total = total - (prix*value);
    
    value = isNaN(value) ? 0 : value;
            value++;
    
    total = total+(prix*value);

    if(limit >= value ) {
        $(this).parent().find('#number').attr('value',value);
        $(this).parent().find('#number').html('');
        //alert(prix*value);
        $(this).parent().closest('li').find('.stotal').html(prix*value);
        //$(this).closest('.stotal').html('deded');    
        $('#total').html(total);
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        
        
        $.ajax({
            url:"/panier/updateqte",
            method:'POST',
            data:{
                'id':$(this).attr('id'),
                'qte':value
            },
                     
        });
    }   
        


});


$(".btn-dec").click(function (e) {
    var value = $(this).parent().find('#number').attr('value');
    var limit = $(this).parent().find('#limit').attr('value');
    
    var prix = parseFloat($(this).parent().closest('li').find('.price').find('#prix').html());
    //alert(prix);

    var total = parseFloat($('#total').html());
    total = total - (prix*value);
    
    
    value = isNaN(value) ? 0 : value;
            value--;
    total = total+(prix*value);
       
    if(value >=1 ) {
        $(this).parent().find('#number').attr('value',value);
    
        $(this).parent().closest('li').find('.stotal').html(prix*value);
        //$(this).closest('.stotal').html('deded');    
        $('#total').html(total);
        
        
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        
        
        $.ajax({
            url:"/panier/updateqte",
            method:'POST',
            data:{
                'id':$(this).attr('id'),
                'qte':value
            },
                     
        });
    }   
        


});

function incrementValue(){
          var value = parseInt(document.getElementById('number').value, 10);
          var limit = parseInt(document.getElementById('limit').value, 10);
          value = isNaN(value) ? 0 : value;
          value++;
          //alert(limit);
          if(limit >= value ) document.getElementById('number').value = value; 
          else {
               $('.limithidden').show();
               $('#btn-save').attr('disabled','disabled');

          }
      }
      
      
      
    
      
      function setbackground(el){
         if(el.style.color=="orange"){
              el.style.color="black" ;
               stars --; 
         }
          else{ el.style.color="orange"; stars++}
      }
      $( "#number" ).change(function() {
      var max = parseInt(document.getElementById('limit').value,10);
      var min = 1;
      if ($(this).val() > max)
      {
          $(this).val(max);
      }
      else if ($(this).val() < min)
      {
          $(this).val(min);
      } 
      
      });
      
      $("#btn-wish,#btn-wish2").click(function (e) {
          
        // add to whishlist 
          $color = $('.heart').attr('value');
          if($color=='on') $url="/wishlist/remove";
          else $url="/wishlist/add";
         
           $.ajaxSetup({
          headers: {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
           });
          e.preventDefault();
      
          $.ajax({
              url:$url,
              method:'POST',
              data:{
                  'produit':document.getElementsByClassName('id_att')[0].id,
              },
      
          success:function(){
              if($color!='on'){
              $('.heart').css('background-color','orange');
              $('.heart').attr('value','on');}
              else {
              $('.heart').css('background-color','white');
              $('.heart').attr('value','off');}
          },

          error: function(jqXHR, textStatus, errorThrown){
           //   window.location="http://localhost:8000/login"    
          }         
          });
          
  });

  $("#btn-wishremove").click(function (e) {
      
          $.ajaxSetup({
          headers: {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
      });
      e.preventDefault();
      
      $.ajax({
          url:"/wishlist/remove",
          method:'POST',
          data:{
              'produit':document.getElementsByClassName('id_att')[0].id,
          },
          success:function(){
              $(".heart").css("background-color" ,"white");
              $('.heart').attr('id','btn-wish')
          },
          error: function(jqXHR, textStatus, errorThrown){
              window.location.href="http://localhost:8000/login"    
         }         
      });
     
  
  });



          
  function showlim(){
      
          $('.lim').show();
      }
     
     

      function decrementValue()
      {
          var value = parseInt(document.getElementById('number').value, 10);
          var limit = parseInt(document.getElementById('limit').value, 10);
          value = isNaN(value) ? 0 : value;
          value--;
          if($('.limithidden').display!='hidden' && value<=limit )  {$('.limithidden').hide(); 
          $("#btn-save").removeAttr('disabled');
          }
          if(value >= 1)
          document.getElementById('number').value = value; 
      }

     
     $("#btn-save").click(function (e) {
         
      $.ajaxSetup({
          headers: {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
      });
      e.preventDefault();
      
      $.ajax({
          url:"/panier/add",
          method:'POST',
          data:{
              'produit':document.getElementsByClassName('id_att')[0].id,
              'qte': document.getElementById('number').value,
          },
      
          success:function(response){
            var st = JSON.parse(JSON.stringify(response));
              if(st.produitdetails==undefined) {
                  
                  
                  st.produitdetails= st['produit'];
                  
                  //st.produitdetails.product_name = st['produit'].product_name;
                  //st.produitdetails.promo = st['produit'].promo;
                  st.quantite = st['qte'];
                  //st.produitdetails.prix = st['prix'];

              }
              console.log(st.produitdetails.name);
              console.log(st.produitdetails);
              //alert(st.produitdetails.name);

              //alert(st['produit'].product_name);
            var html = '<li>'+
                '<div class="uk-flex">'+
                    '<div class="uk-border-rounded uk-background-muted" style="width: 50px; height: 50px">'+
                    '<img src="https://autosupply.orcloudproject.com/assets/images/products/'+st.produitdetails.image+'" alt="" srcset="">'+
                    
                    
                    '</div>'+
                    '<div class="uk-width-expand uk-flex uk-flex-between uk-flex-middle uk-margin-small-left">'
                        +'<div>'+
                            '<div class="uk-text-bold uk-text-primary">'+st.produitdetails.name+'</div>'
                            +'<div class="uk-text-small uk-text-bold uk-text-secondary">'+st.produitdetails.prix+' DZD </div>'
                        +'</div>'
                        +'<div>'
                            +'<div class="uk-text-warning">&times;'+st.qte+'</div>'+
                        '</div>'+
                    '</div>'+
                '</div>'+
            '</li>'
                  
            var x = $('#count').html();
              
              var n = parseInt(x)+1;
              $('#count').html('');
              $('#count').append(n);
          
              $('.panier').append(html); //// For Append
              $("#btn-save").hide()
              
              $("#btn-save2").show();   //// For replace with previous one
              
              
               },
              
              
           error: function(response){
            //console.log(jqXHR.responseText);
            //alert(response); 
            //alert('efffzfz');
            //window.location.href="/login"
                
        }         
      });
  
     
});

$('#btn-save2').click(function(e){
    window.location='/panier'
});
$("#save-now").click(function (e) {
    
    var produit = document.getElementsByClassName('id_att')[0].innerHTML;
    qte= document.getElementById('number').value,
    taille=$('#colors').find(":selected").attr('id'),
    taille_nocolor=$('#tailles').find(":selected").attr('id'),
     
    $('#form').submit(function(eventObj) {
        $(this).append('<input type="hidden" name="produit" value="'+produit+'" /> ');
        $(this).append('<input type="hidden" name="qte" value="'+qte+'" /> ');
        $(this).append('<input type="hidden" name="taille" value="'+taille+'" /> ');
        $(this).append('<input type="hidden" name="taille_nocolor" value="'+taille_nocolor+'" /> ');
        return true;
    });
    
    /*
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    e.preventDefault();
    
    $.ajax({
        url:"/acheter",
        method:'POST',
        data:{
            'produit':document.getElementsByClassName('id_att')[0].id,
            'qte': document.getElementById('number').value,
            'taille':$('#colors').find(":selected").attr('id'),
            'taille_nocolor':$('#tailles').find(":selected").attr('id'),
            

        },
    
        success:function(res){
            window.location=res.url;
            //alert(st['produit'].product_name);
        
             },
            
         error: function(jqXHR, textStatus, errorThrown){
           // window.location="/login";
                
      }         
    });
    */

   
});
     