/* ------------------
	JS - localStorage
--------------------*/
if (!localStorage.user) {
  window.location.href = 'login.html';
}

$(document).ready(function() {
  userDisplay();
  basketDisplay();
  cartDisplay();
});

function cartCheckout() {

  var totalHT = 0;
  var tva2 = 0;
  var tva7 = 0;
  var totalTTC = 0;
  var user = JSON.parse(localStorage.getItem('user'));
  if (localStorage.basket) {
    var basket = JSON.parse(localStorage.getItem('basket'));
  } else {
    var basket = [];
  }
  if (basket.length != 0) {
    $(basket).each(function(index) {;
      totalHT += this.price * this.quantity;
	if (this.vatCode == "2"){
		tva2 += (this.price * this.quantity * 2.5) / 100;
	} else if (this.vatCode == "1"){
		tva7 += (this.price * this.quantity * 7.7) / 100;
	}
    })
    totalTTC = totalHT + tva2 + tva7;	
    $.ajax({
      url: '../../../bubble/api/order/add',
      type: 'POST',
      dataType: "json",
      contentType: "application/json; charset=utf-8",
      data: JSON.stringify({
        "basket": basket,
        "companyName": user.companyName,
        "street": user.street,
        "postalCode": user.postalCode,
        "city": user.city,
        "total": parseFloat(totalTTC).toFixed(2)
      }),
      success: function(response) {
        if (response.notice) {
		  $('#orderId').html(response.orderId);
		  invoicExport();  
        }
      }
    })
  } else {
    alert('panier vide');
  }
}

function cartDisplay() {
  if (localStorage.basket) {
    var basket = JSON.parse(localStorage.getItem('basket'));
  } else {
    var basket = [];
  }
  var user = JSON.parse(localStorage.getItem('user'));
  var totalHT = 0;
  var tva2 = 0;
  var base2 = 0;
  var tva7 = 0;
  var base7 = 0;
  var totalTTC = 0;
  var totalTVA = 0;
  var items = "";
  var items2 = "";
  var items3 = "";
  $(basket).each(function(index) {
    items += '<div class="cart-item">' + '<div class="cart-item-product">' + '<div class="item-preview">' + '<a>' + '<figure class="product-preview-image small liquid">' + '<img src="images/items/image' + this.productId + '_s.jpg" alt="">' + '</figure>' + '</a>' + '<p class="text-header small">' + this.designation + '</p>' + '<p class="description">' + this.variante + '</p>' + '</div>' + '</div>' + '<div class="cart-item-category">' + '<input type="number" min="1" data-index="' + index + '" value="' + this.quantity + '">' + '</div>' + '<div class="cart-item-price">' + '<p class="price">' + parseFloat(this.price * this.quantity).toFixed(2) + '<span> CHF</span></p>' + '</div>' + '<div class="cart-item-actions">' + '<a href="javascript:basketDeleteItem(' + this.productId + ');" class="button dark-light rmv">' + '<svg class="svg-plus">' + '<use xlink:href="#svg-plus"></use>' + '</svg>' + '</a>' + '</div>' + '</div>';
    totalHT += this.price * this.quantity;
	if (this.vatCode == "2"){
		tva = 2.5;
		base2 += this.price * this.quantity;
	} else if (this.vatCode == "1"){
		tva = 7.7;
		base7 += this.price * this.quantity;
	}
	if(index >= 38 /*19*/) {
	items2 += '<tr>' + '<td class="desc">' + this.designation + ' - ' + this.variante + ' </td>' + '<td class="unit">' + parseFloat(this.price).toFixed(2) + '</td>' + '<td class="qty">' + this.quantity + '</td>' + '<td class="total">' + parseFloat(this.price * this.quantity).toFixed(2) + '</td>' + '<td class="tva">' + tva + '%</td>' + '</tr>';
	} else  {
	items3 += '<tr>' + '<td class="desc">' + this.designation + ' - ' + this.variante + ' </td>' + '<td class="unit">' + parseFloat(this.price).toFixed(2) + '</td>' + '<td class="qty">' + this.quantity + '</td>' + '<td class="total">' + parseFloat(this.price * this.quantity).toFixed(2) + '</td>' + '<td class="tva">' + tva + '%</td>' + '</tr>';
	}
  });
  tva2 = (base2 * 2.5) / 100;
  tva7 = (base7 * 7.7) / 100;
  totalTTC = totalHT + tva2 + tva7;
  totalTVA = tva2 + tva7;
  totalFrancs = NumberToLetter(Math.floor(totalTTC));
  totalCentimes = NumberToLetter(parseInt(totalTTC.toFixed(2).toString().split(".")[1]));
  var content = '<div class="cart">' + '<div class="cart-header">' + '<div class="cart-header-product">' + '<p class="text-header small">Produit</p>' + '</div>' + '<div class="cart-header-category">' + '<p class="text-header small">Quantité</p>' + '</div>' + '<div class="cart-header-price">' + '<p class="text-header small">Prix</p>' + '</div>' + '<div class="cart-header-actions">' + '<p class="text-header small"></p>' + '</div>' + '</div>' + items + '<div class="cart-total">' + '<p class="price medium">' + parseFloat(totalHT).toFixed(2) + '<span> CHF</span></p>' + '<p class="text-header total">Total HT</p>' + '</div>' + '<div class="cart-total">' + '<p class="price medium">' + parseFloat(tva2).toFixed(2) + '<span> CHF</span></p>' + '<p class="text-header total">TVA 2.5% </p>' + '</div>' + '<div class="cart-total">' + '<p class="price medium">' + parseFloat(tva7).toFixed(2) + '<span> CHF</span></p>' + '<p class="text-header total">TVA 7.7% </p>' + '</div>' + '<div class="cart-total">' + '<p class="price medium">' + parseFloat(totalTTC).toFixed(2) + '<span> CHF</span></p>' + '<p class="text-header total">Total TTC</p>' + '</div>' + '<div class="cart-actions">' + '<a href="javascript:cartCheckout();" class="button mid primary">Valider</a>' + '<a href="products.html" class="button mid dark-light spaced">Retour</a>' + '</div>' + '</div>';
  $('.jq-cart-content').html(content);
  var date = new Date();
  var day = date.getDate();
  if (day < 10) {
    day = "0" + day;
  }
  var month = date.getMonth() + 1;
  if (month < 10) {
    month = "0" + month;
  }
  var year = date.getFullYear();
  var invoice = '<header class="clearfix">'
    +'<div id="project">'
      +'Le Palmier s&agrave;rl' 
	  + '<br>Route de Peney 51' 
	  + '<br>1214 Vernier' 
	  + '<br>TVA: CHE-485.765.573'
	  + '<br>contact@lepalmier-distribution.ch'
	  + '<br>+41 77 996 51 81'
   +'</div>'
    +'<div id="slogan" class="clearfix">'
      +'Osez l&apos;originalit&eacute;'
    +'</div>'
    +'<div class="clearfix"></div>'
    +'<div id="contact">'
    +'</div>'
    +'<div id="company">'
      + user.companyName
      +'<br>' +user.street
      +'<br>'+user.postalCode+' '+user.city
    +'</div>'
    +'<div class="clearfix"></div>'
    +'<div id="facture">'
      +'Facture proforma n&ordm; '
    +'</div>'
    +'<div id="date">'
      +'Date: '+day+'.'+month+'.'+year 
    +'</div>'
  +'</header>'
  +'<main>'
    +'<table id="order">'
      +'<thead>'
        +'<tr>'
          +'<th class="desc">D&eacute;signation</th>'
          +'<th class="unit">Prix unit.</th>'
          +'<th class="qty">Qt&eacute;</th>'
          +'<th class="total">Montant</th>'
          +'<th class="tva">TVA</th>'
        +'</tr>'
      +'</thead>'
      +'<tbody>'
        + items3
    +'</tbody>'
    +'<table id="order">'
      +'<tbody>'
        + items2
    +'</tbody>'
  +'</table>'
  +'<div class="clearfix"></div>'
  +'<div id="tva">'
    +'<span>D&eacute;tail TVA:</span>'
    +'<table>'
      +'<thead>'
        +'<tr>'
          +'<th>Base</th>'
          +'<th>Taux</th>'
          +'<th>TVA</th>'
        +'</tr>'
      +'</thead>'
      +'<tbody>'
        +'<tr>'
          +'<td>'+parseFloat(base7).toFixed(2)+'</td>'
          +'<td>7.7%</td>'
          +'<td>'+parseFloat(tva7).toFixed(2)+'</td>'
        +'</tr>'
        +'<tr>'
          +'<td>'+parseFloat(base2).toFixed(2)+'</td>'
          +'<td>2.5%</td>'
          +'<td>'+parseFloat(tva2).toFixed(2)+'</td>'
        +'</tr>'
      +'</tbody>'
    +'</table>'
  +'</div>'
  +'<div id="montant">'
    +'<table>'
      +'<tbody>'
        +'<tr>'
          +'<td class="first">Total net</td>'
          +'<td class="last">'+parseFloat(totalHT).toFixed(2)+'</td>'
        +'</tr>'
        +'<tr>'
          +'<td class="first">TVA</td>'
          +'<td  class="last">'+parseFloat(totalTVA).toFixed(2)+'</td>'
        +'</tr>'
        +'<tr>'
          +'<td class="first">Montant total TTC</td>'
          +'<td  class="last">'+parseFloat(totalTTC).toFixed(2)+'</td>'
        +'</tr>'
      +'</tbody>'
    +'</table>'
    +'<span>'+totalFrancs+' francs et '+totalCentimes+' centimes</span>'
  +'</div>'
  +'<div class="clearfix"></div>'
  +'<div id="notices">'
      +'Compte POSTFINANCE IBAN CH59 0900 0000 1451 3853 5<br>Avec nos meilleurs remerciements pour votre commande.'
    +'<br>contact@lepalmier-distribution.ch'
  +'</div>'
+'</main>';

  $('#invoice').html(invoice);
  $('input').on("change", function() {
    var index = $(this).data("index");
	var quantity = $(this).val();
	var basketStorage = JSON.parse(localStorage.getItem('basket'));
	basketStorage[index].quantity = quantity;
	localStorage.setItem('basket', JSON.stringify(basketStorage));
    basketDisplay();
	cartDisplay();
  });
}

function invoicExport() {
	if ($("#order:nth-child(2) tbody tr").length == 0) {
		$("#order:nth-child(2)").hide();
		$("#invoice").css("height", "29.7cm");
	} else {
		$("#order:nth-child(2)").show();
		$("#order:nth-child(2)").css("margin-top", "6cm");
		$("#invoice").css("height", "59.4cm");
	} 
	$('.section-wrap').hide();
	window.print();

//$('#invoice').printThis();
	setTimeout(function(){window.location.href = 'checkout.html'; }, 1000);	

		

/* var pdf = new jsPDF('p', 'mm', 'a4');
  var options = {
       pagesplit: true
  };
  $('#invoice').show();
  if ($("#order:nth-child(2) tbody tr").length == 0) {
	   $("#order:nth-child(2)").hide();
	  $("#invoice").css("height", "22.2cm");

	} else {
			   $("#order:nth-child(2)").show();

		 $("#order:nth-child(2)").css("margin-top", "6cm");
		$("#invoice").css("height", "44.4cm");

	} 
	  pdf.addHTML($('#invoice').first(), options, function() {
   $.when(pdf.save("Facture.pdf")).done(function() {
      $('#invoice').hide();
setTimeout(function(){window.location.href = 'checkout.html'; }, 600);	
});
  });*/
}

function basketDisplay() {
  if (localStorage.basket) {
    var basket = JSON.parse(localStorage.getItem('basket'));
  } else {
    var basket = [];
  }
  var total = 0;
  var items = "";
  $('.jq-basket-count').html(basket.length);
  $(basket).each(function(index) {
    items += '<li class="dropdown-item">' + '<a class="link-to"></a>' + '<figure class="product-preview-image tiny">' + '<img src="images/items/image' + this.productId + '_s.jpg" alt="">' + '</figure>' + '<p class="text-header tiny">' + this.designation + '</p>' + '<p class="category tiny primary">x ' + this.quantity + '</p>' + '<p class="price tiny">' + parseFloat(this.price * this.quantity).toFixed(2) + '<span> CHF</span></p>' + '</li>';
    total += this.price * this.quantity;
  });
  items += '<li class="dropdown-item">' + '<p class="text-header tiny">Total</p>' + '<p class="price">' + parseFloat(total).toFixed(2) + '<span> CHF</span></p>' + '<a href="cart.html" class="button primary">Aller au panier</a>' + '</li>';
  $('.jq-basket-content').html(items);
}

function basketDeleteItem(productId) {
  var basketStorage = JSON.parse(localStorage.getItem('basket'));
  var basketFilterm = basketStorage.filter(function(n) {
    return n.productId == productId;
  });
  var index = basketStorage.indexOf(basketFilterm[0]);
  basketStorage.splice(index, 1);
  localStorage.setItem('basket', JSON.stringify(basketStorage));
  basketDisplay();
  cartDisplay();
}

function userDisplay() {
  var user = JSON.parse(localStorage.getItem('user'));
  $('.jq-username').html(user.username);
  $('.jq-company-name').html(user.companyName);
}

function logout() {
  localStorage.clear();
  window.location.href = 'login.html';
}

/* ------------------
	PHP - session
--------------------*/
/*
var user;
var basket;
  $.ajax({
    url: '../../../bubble/api/session/user',
    type: 'GET',
    dataType: "json",
    success: function(response) {
      if(response.error) {  
		window.location.href = 'login.html';
	  } else {
		  user = response;
		    userDisplay();

	  }
    }
  })
  $.ajax({
    url: '../../../bubble/api/session/basket',
    type: 'GET',
    dataType: "json",
    success: function(response) {
      if(!response.error) {  
				  basket = response;

	  } else {
    basket = [];
  }
    basketDisplay();
cartDisplay();
    }
  })

function cartCheckout() {
  var totalHT = 0;
  var tva2 = 0;
  var tva7 = 0;
  var totalTTC = 0;
  if (basket.length != 0) {
    $(basket).each(function(index) {;
      totalHT += this.price * this.quantity;
	if (this.vatCode == "2"){
		tva2 += (this.price * this.quantity * 2.5) / 100;
	} else if (this.vatCode == "1"){
		tva7 += (this.price * this.quantity * 7.7) / 100;
	}
    })
    totalTTC = totalHT + tva2 + tva7;	
    $.ajax({
      url: '../../../bubble/api/order/add',
      type: 'POST',
      dataType: "json",
      contentType: "application/json; charset=utf-8",
      data: JSON.stringify({
        "basket": basket,
        "companyName": user.companyName,
        "street": user.street,
        "postalCode": user.postalCode,
        "city": user.city,
        "total": parseFloat(totalTTC).toFixed(2)
      }),
      success: function(response) {
        console.log(response);
        if (response.notice) {
          window.location.href = 'checkout.html';
        }
      }
    })
  } else {
    alert('panier vide');
  }
}

function cartDisplay() {
  var totalHT = 0;
  var tva2 = 0;
  var base2 = 0;
  var tva7 = 0;
  var base7 = 0;
  var totalTTC = 0;
  var items = "";
  $(basket).each(function(index) {
    items += '<div class="cart-item">' + '<div class="cart-item-product">' + '<div class="item-preview">' + '<a>' + '<figure class="product-preview-image small liquid">' + '<img src="images/items/westeros_s.jpg" alt="">' + '</figure>' + '</a>' + '<p class="text-header small">' + this.designation + '</p>' + '<p class="description">' + this.packagingType + '</p>' + '</div>' + '</div>' + '<div class="cart-item-category">' + '<input type="number" min="1" data-index="' + this.productId + '" value="' + this.quantity + '">' + '</div>' + '<div class="cart-item-price">' + '<p class="price"><span>$</span>' + parseFloat(this.price * this.quantity).toFixed(2) + '</p>' + '</div>' + '<div class="cart-item-actions">' + '<a href="javascript:basketDeleteItem(' + this.productId + ');" class="button dark-light rmv">' + '<svg class="svg-plus">' + '<use xlink:href="#svg-plus"></use>' + '</svg>' + '</a>' + '</div>' + '</div>';
    totalHT += this.price * this.quantity;
	if (this.vatCode == "2"){
		base2 += this.price * this.quantity;
	} else if (this.vatCode == "1"){
		base7 += this.price * this.quantity;
	}
  });
  tva2 = (base2 * 2.5) / 100;
  tva7 = (base7 * 7.7) / 100;
  totalTTC = totalHT + tva2 + tva7;
  var content = '<div class="cart">' + '<div class="cart-header">' + '<div class="cart-header-product">' + '<p class="text-header small">Produit</p>' + '</div>' + '<div class="cart-header-category">' + '<p class="text-header small">Quantité</p>' + '</div>' + '<div class="cart-header-price">' + '<p class="text-header small">Prix</p>' + '</div>' + '<div class="cart-header-actions">' + '<p class="text-header small"></p>' + '</div>' + '</div>' + items + '<div class="cart-total">' + '<p class="price medium"><span>$</span>' + parseFloat(totalHT).toFixed(2) + '</p>' + '<p class="text-header total">Total HT</p>' + '</div>' + '<div class="cart-total">' + '<p class="price medium"><span>$</span>' + parseFloat(tva2).toFixed(2) + '</p>' + '<p class="text-header total">TVA 2.5% </p>' + '</div>' + '<div class="cart-total">' + '<p class="price medium"><span>$</span>' + parseFloat(tva7).toFixed(2) + '</p>' + '<p class="text-header total">TVA 7.7% </p>' + '</div>' + '<div class="cart-total">' + '<p class="price medium"><span>$</span>' + parseFloat(totalTTC).toFixed(2) + '</p>' + '<p class="text-header total">Total TTC</p>' + '</div>' + '<div class="cart-actions">' + '<a href="javascript:cartCheckout();" class="button mid primary">Valider</a>' + '<a href="products.html" class="button mid dark-light spaced">Retour</a>' + '</div>' + '</div>';
  $('.jq-cart-content').html(content);
  $('input').on("change", function() {
    var productId = $(this).data("index");
	var quantity = $(this).val();
    $.ajax({
    url: '../../../bubble/api/basket/edit',
    type: 'POST',
    dataType: "json",
      contentType: "application/json; charset=utf-8",
      data: JSON.stringify({
        "productId": productId,
        "quantity": quantity
      }),
    success: function(response) {
		basket = response;
  basketDisplay();
  cartDisplay();
    }
  })
  });
}

function basketDisplay() {
  var total = 0;
  var items = "";
  $('.jq-basket-count').html(basket.length);
  $(basket).each(function(index) {
    items += '<li class="dropdown-item">' + '<a class="link-to"></a>' + '<figure class="product-preview-image tiny">' + '<img src="images/items/image' + this.productId + '_s.jpg" alt="">' + '</figure>' + '<p class="text-header tiny">' + this.designation + '</p>' + '<p class="category tiny primary">x ' + this.quantity + '</p>' + '<p class="price tiny"><span>$</span>' + parseFloat(this.price * this.quantity).toFixed(2) + '</p>' + '</li>';
    total += this.price * this.quantity;
  });
  items += '<li class="dropdown-item">' + '<p class="text-header tiny">Total</p>' + '<p class="price"><span>$</span>' + parseFloat(total).toFixed(2) + '</p>' + '<a href="cart.html" class="button primary">Aller au panier</a>' + '</li>';
  $('.jq-basket-content').html(items);
}

function basketDeleteItem(productId) {
    $.ajax({
    url: '../../../bubble/api/basket/edit',
    type: 'POST',
    dataType: "json",
      contentType: "application/json; charset=utf-8",
      data: JSON.stringify({
        "productId": productId,
        "quantity": 0
      }),
    success: function(response) {
		basket = response;
  basketDisplay();
  cartDisplay();
    }
  })

}

function userDisplay() {
  $('.jq-username').html(user.username);
  $('.jq-company-name').html(user.companyName);
}

function logout() {
  $.ajax({
    url: '../../../bubble/api/session/destroy',
    type: 'GET',
    dataType: "json",
    success: function(response) {
      if(response.notice) {  
		window.location.href = 'login.html';
	  }
    }
  })
}
*/
