//JS file for the Administrator's simple Tasks.


/** =================================================================
 * For all Products
 ========================================================================*/
 var save_method;
 const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];
 function dateToYMD(date) {
  var d = date.getDate();
  //var m = date.getMonth() + 1; //Month from 0 to 11
  var m = monthNames[date.getMonth()];
  var y = date.getFullYear();
  //return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
  return '<span class="text-muted"><small>' + (d <= 9 ? '0' + d : d) + '/' + m + '/'+ y + '</small></span>';
}

/**================= Show Product Details =============*/
function show_product(id)
{
  //$("#showProductModal").modal('show');
    var form =  $('#discount-form')[0].reset();
    $.ajax({
        url:  base_url + '/administrator/products/show/details/'+ id,
        type: "GET",
        dataType: "JSON",
        success: function(data)
        {
            $('[name="id"]').val(data.id);
            $('[name="name"]').val(data.name);
            $('[name = "price"]').val(data.price);
            $('[name = "discount_price"]').val(data.discount_price);
            $('[name = "category"]').val(data.category);
            $('[name = "quantity"]').val(data.quantity);
            $('[name = "brand_name"]').val(data.category);
            $('[name = "supplier_name"]').val(data.supplier_name);
            $('[name = "units"]').val(data.unit+' ('+data.symbol+')');

            //striped text for excerpt and description
            $('#brieftxt').html(excerpt);
            $('[name = "description"]').html(description);

            //Get Main photo
            if(data.photo !== null){
              $("#preview-image").html("<img src="+data.photo+" class='img-fluid'>");
            }

            //Pick product attributes and thier items.
            $.ajax({
              url:  base_url + '/administrator/products/attributes/list/'+ id,
              type: "GET",
              dataType: "JSON",
              success: function(data)
              {
                  var attributes = '';
                  for (var i = 0; i < data.length; i++) {
                    attributes += data[i].attribute_name + ':' + data[i].item_name + ' , ';
                  }
                  // remove the last comma and space from the string
                  attributes = attributes.slice(0, -2);
                  $('[name="attributes"]').val(attributes);
              }
            });

            //Get product Images for Gallery
            $.ajax({
              url: base_url + '/administrator/products/images/list/' + id,
              type: 'GET',
              dataType: 'JSON',
              success: function(data) {
                var gallery = '';
                for (var i = 0; i < data.length; i++) {
                  gallery += '<img src="' + data[i].photo + '" class="gallery-image" width="80px" data-index="' + i + '">';
                }
                // display gallery
                $("#gallery").html(gallery);
            
                // add click event listener to gallery images
                $('.gallery-image').click(function() {
                  var index = $(this).data('index');
                  var photo = data[index].photo;
                  $("#show-gallery").html("<img src='" + photo + "' class='img-fluid'>");
                });
              }
            });

            //load modal
            start_load()
            $("#showProductModal").modal('show');
            $(".modal-title").text("Product Details!");
            $(".stbtn").text("Update");
            setTimeout(function(){
              end_load();
          },500)
        }

  });
}
/**========= Product Status change ===========*/
$(document).on("change","#cstatus",function(e){
  var status = $(this).val();
  var id = $(this).data('id');
  if(status == 1){
      status = 0;
  }else{
      status = 1;
  }
  $.ajax({
      url : base_url+'/administrator/products/status/'+id,
      type : "POST",
      data : {status:status,id:id},
      success : function(data){
          if(data.success == true)
          {
              if(status == 1){
                  toastr.success("Product Status activated successfully");
              }else{
                  toastr.warning("Product Status deactivated");
              }
              location.href = base_url+"/administrator/products";
          }
      }
  });
});
//Update Stock
function update_stock(id)
  {
      var form =  $('#stock-form')[0].reset();
      $.ajax({
          url:  base_url + '/administrator/products/stock/edit/'+ id,
          type: "GET",
          dataType: "JSON",
          success: function(data)
          {
              $('[name="id"]').val(data.id);
              $('[name="product_id"]').val(data.product_id);
              $('[name="name"]').val(data.name);
              $('[name = "quantity"]').val(data.quantity);
              $('[name="status"]').val(data.status);
              
              //load modal
              start_load()
              $("#stockModal").modal('show');
              $(".modal-title").text("update Stock!");
              $(".stbtn").text("Update Stock");
              setTimeout(function(){
                end_load();
            },500)
          }
  
      });
   }


  function save_stock()
  { 
      var form =  $('#stock-form')[0];
      $.ajax({
          type: "post",
          url: base_url + '/administrator/products/stock/update',
          dataType: "JSON",
          data: new FormData(form),
          processData: false,
          contentType: false,
          headers: {'X-Requested-With': 'XMLHttpRequest'},
          success: function(data)
          {
            if(data.success == true){
                start_load()
                  toastr.success(data.msg);
                  setTimeout(function(){
                    end_load()
                    location.href = base_url+"/administrator/products";
                },500);
              }else{
                  toastr.error(data.msg);
              }
          }
      });
 }
 //Add Discount Price or Sale Price
 function product_discount(id)
  {
    
      var form =  $('#discount-form')[0].reset();
      $.ajax({
          url:  base_url + '/administrator/products/discount/edit/'+ id,
          type: "GET",
          dataType: "JSON",
          success: function(data)
          {
              $('[name="id"]').val(data.id);
              $('[name="name"]').val(data.name);
              $('[name = "price"]').val(data.price);
              
              //load modal
              start_load()
              $("#discountModal").modal('show');
              $(".modal-title").text("Add Discount Price!");
              $(".stbtn").text("Update Price");
              setTimeout(function(){
                end_load();
            },500)
          }
  
      });
   }
//Save Discount Price or Sale Price
function save_discount()
  { 
      var form =  $('#discount-form')[0];
      $.ajax({
          type: "post",
          url: base_url + '/administrator/products/discount/update',
          dataType: "JSON",
          data: new FormData(form),
          processData: false,
          contentType: false,
          headers: {'X-Requested-With': 'XMLHttpRequest'},
          success: function(data)
          {
            if(data.success == true){
                start_load()
                  toastr.success(data.msg);
                  setTimeout(function(){
                    end_load()
                    location.href = base_url+"/administrator/products";
                },500);
              }else{
                  toastr.error(data.msg);
              }
          }
      });
 }
//Delete Gallery image in Edit Product Area
function image_gallery_delete(id)
{
  var confirmation = confirm('Are you sure you want to delete Gallery Image ?');
  if (confirmation) {
      window.location.href = base_url + '/administrator/products/gallery/delete/' + id;
  }
}
//Delete Product
function delete_product(id, name)
{
  var confirmation = confirm('Are you sure you want to delete product ' + name + '?');
  if (confirmation) {
      window.location.href = base_url + '/administrator/products/delete/' + id;
  }
}
//Delete Product - Brand
function delete_brand(id, name)
{
  var confirmation = confirm('Are you sure you want to delete ' + name + '?');
  if (confirmation) {
      window.location.href = base_url + '/administrator/products/brands/delete/' + id;
  }
}

//Delete Product - Supplier
function delete_supplier(id, name)
{
  var confirmation = confirm('Are you sure you want to delete ' + name + '?');
  if (confirmation) {
      window.location.href = base_url + '/administrator/products/suppliers/delete/' + id;
  }
}

//Delete Product - Attribute
function attribute_delete(id, name)
{
  var confirmation = confirm('Are you sure you want to delete ' + name + '?');
  if (confirmation) {
      window.location.href = base_url + '/administrator/products/attributes/delete/' + id;
  }
}

//Delete Product - Attribute ITEM
function delete_attrItem(id, name)
{
  var confirmation = confirm('Are you sure you want to delete ' + name + '?');
  if (confirmation) {
      window.location.href = base_url + '/administrator/products/attribute/item/delete/' + id;
  }
}

//Delet Product Category
 function delete_productCategory(id, name)
{
  var confirmation = confirm('Are you sure you want to delete ' + name + '?');
  if (confirmation) {
      window.location.href = base_url + '/administrator/products/categories/delete/' + id;
  }
}