$(document).ready(function(){
    //console.log('foo bar');
    var d = new Date();
    var month = d.getMonth()+1;
    var day = d.getDate();
    var currentDate = d.getFullYear() + '/' + ((''+month).length<2 ? '0' : '') + month + '/' + ((''+day).length<2 ? '0' : '') + day;
    /*
    $('.progressIndicatorCheckbox').change(function() {
        console.log('food inside');
        if(this.checked) {
            var returnVal = confirm("Are you sure?");
            $(this).prop("checked", returnVal);
        }
        $('#textbox1').val(this.checked);
    });
    */
    function matchCustom(params, data) {
      // If there are no search terms, return all of the data
        if ($.trim(params.term) === '') {
          return data;
        }

        // Do not display the item if there is no 'text' property
        if (typeof data.text === 'undefined') {
          return null;
        }

        // `params.term` should be the term that is used for searching
        // `data.text` is the text that is displayed for the data object
        if (data.text.indexOf(params.term) > -1) {
          var modifiedData = $.extend({}, data, true);
          modifiedData.text += ' (matched)';

          // You can return modified objects from here
          // This includes matching the `children` how you want in nested data sets
          return modifiedData;
        }

        // Return `null` if the term should not be displayed
        return null;
    }
    $('#shortCodeCountry').select2({
      matcher: matchCustom
    });
    $('.progressIndicatorCheckbox').on('change', function() {
        // From the other examples
      // console.log('finker');
        if (!this.checked) {
            var sure = confirm("Are you sure?");
            this.checked = !sure;
            $('#textbox1').val(sure.toString());
        }
    });
    $("select#shortCodeCountry").change(function(){
      var shortCodeCountry = $(this).val();
      var theToken = "{{ csrf_token }}";
          $.ajax({
            type: "POST",
            url: base_url + '/mnos/getCountryNetworks',
            headers: {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            data: {"country" : shortCodeCountry },
            cache: false,
            beforeSend: function () {
              console.log('loader here');
             //show a loader here
             //$('#district').html('<img src="../../img/loading.gif" alt="" width="24" height="24">');
            },
            success: function(data) {
              console.log(data.mnos);
              // var jason = JSON.parse(data);
              if (data.code === 1) {
                var actionPoint = $('#networks').empty();
                console.log(actionPoint);
                $.each(data.mnos, function(key, value) {
                  console.log(id);
                  console.log(row);
                   //$('#networks').append($("<option />").val(row.id).text(row.name));
                });
              }
              else {
                console.log(data);
                $.alert(data.msg);
              }
            },
            fail : function(errordata){
             console.log(errordata);å
           }
          });
    });
    
    $('select').select2();
    $('#myDatepicker2').datetimepicker({
        format: 'YYYY-MM-DD',
        maxDate: currentDate
    });
    $('#launchDate').datetimepicker({
        format: 'YYYY-MM-DD'
    });

    $('#invoiceDateSupport').datetimepicker({
        format: 'YYYY-MM-DD'
    });
    $('#expiryDate').datetimepicker({
      format: 'YYYY-MM-DD'
  });
    $('#createNotesBtn').click(function(evt){
      evt.preventDefault();
      $('#newNotesForm').modal('show');
    });
    $('#progressIndicatorBtn').click(function(evt){
      // console.log('foo bars');
      evt.preventDefault();
      $('#progressIndicatorDetailsModal').modal('show');
    });

    $('#createSmsShortCodeBtn').click(function(evt){
      evt.preventDefault();
      $('#shortCodeType').val('sms');
      $('#newShortCodeFormModal').modal('show');
    });
    $('#createUssdShortCodeBtn').click(function(evt){
      evt.preventDefault();
      $('#shortCodeType').val('ussd');
      $('#newShortCodeFormModal').modal('show');
    });

    $('#createVoiceShortCodeBtn').click(function(evt){
      evt.preventDefault();
      $('#shortCodeType').val('voice');
      $('#newShortCodeFormModal').modal('show');
    });
    $('#createSenderIdBtn').click(function(evt){
      evt.preventDefault();
      $('#newSenderIdFormModal').modal('show');
    });

    $('#createPaymentBtn').click(function(evt){
      evt.preventDefault();
      $('#financePaymentsForm').modal('show');
    });
    $('#addSupportFeesInfoBtn').click(function(evt){
      evt.preventDefault();
      $('#supportFeesFormModal').modal('show');
    });
    $('.paymentEntryEditBtn').click(function(tve){
      tve.preventDefault();
      //var theIDD = $("input[name=payment_entry_id]").val();
      var theIDD = $(this).siblings('.paymentEntryRowId').val();

      $.ajax({
        type: "GET",
        url: base_url + '/clients/get_payment/' + theIDD,
        processData: false,
        contentType: false,
        async: false,
        success: function (data){
          console.log(data);
          if (data.code === 1) {
            // console.log(theIDD);
            $('#paymentIdEdit').val(theIDD);
            $('#financeServicesEdit').val(data.services_arr).change();
            $('#invoiceNumberEdit').val(data.result.invoice_number);
            $('#invoiceAmountEdit').val(data.result.invoice_amount);
            $('#invoiceDateEdit').val(data.result.invoice_date);
            $('#financeShortCodeEdit').val(data.result.short_code);
            $('#invoiceStatusEdit').val(data.result.invoice_status).change();
            $('#remarksEdit').val(data.result.remarks);
            $('#financePaymentsEditForm').modal('show');
          }
          else if (data.code > 1) {
            $.alert({
                title: 'Alert!',
                content: data.msg,
            });
          }
          else {
            $.alert({
                title: 'Alert!',
                content: 'Your request could not be handled. Try again !',
            });

          }
        }
    });

    });


    $('.shortCodeEditBtn').click(function(tve){
      tve.preventDefault();
      var theIDD = $(this).siblings('.shortCodeEntryRowId').val();
      $.ajax({
        type: "GET",
        url: base_url + '/clients/get_shortcode/' + theIDD,
        processData: false,
        contentType: false,
        async: false,
        success: function (data){
          if (data.code === 1) {
            console.log(theIDD);
            console.log(data);
            $('#shortCodeIDEdit').val(theIDD);
            $('#nameEdit').val(data.result.name);
            $('#shortCodeClientIdEdit').val(data.result.client_id);
            $('#shortCodeTypeEdit').val(data.result.code_type);
            $('#shortCodeEdit').val(data.result.shortcode);
            $('#tollFreeEdit').val(data.result.toll_free).change();
            $('#monthlyFeeEdit').val(data.result.monthly_fee);
            $('#launchDateEdit').val(data.result.launch_date);
            $('#expiryDateEdit').val(data.result.expiry_date);
            $('#codeStatusEdit').val(data.result.status).change();
            $('#network').val(data.result.network).change();
            $('#remarksEdit').val(data.result.remarks);
            $('#shortCodeEditModal').modal('show');
          }
          else if (data.code > 1) {
            $.alert({
                title: 'Alert!',
                content: data.msg,
            });
          }
          else {
            $.alert({
                title: 'Alert!',
                content: 'Your request could not be handled. Try again !',
            });

          }
        }
    });

    });



    $('.notesEditBtn').click(function(tve){
      tve.preventDefault();
      //var theIDD = $("input[name=payment_entry_id]").val();
      var theIDD = $(this).siblings('.notesRowId').val();
      // console.log(theIDD);

      $.ajax({
        type: "GET",
        url: base_url + '/clients/get_note/' + theIDD,
        processData: false,
        contentType: false,
        async: false,
        success: function (data){
          if (data.code === 1) {
            // console.log(theIDD);
            $('#noteIdEdit').val(theIDD);
            $('#notesServicesEdit').val(data.services_arr).change();
            $('#notesBodyEdit').val(data.result.notes_body);
            $('#invoiceStatusEdit').val(data.result.invoice_status).change();
            $('#remarksEdit').val(data.result.remarks);
            $('#editNotesFormModal').modal('show');
          }
          else if (data.code > 1) {
            $.alert({
                title: 'Alert!',
                content: data.msg,
            });
          }
          else {
            $.alert({
                title: 'Alert!',
                content: 'Your request could not be handled. Try again !',
            });

          }
        }
    });



    });

    $('#newNotesFormForm').submit(function(evt){
    evt.preventDefault();
    var formData = new FormData($(this)[0]);
    $.ajax({
        type: "POST",
        url: base_url + '/clients/notes_store',
        data : formData,
        processData: false,
        contentType: false,
        async: false,
        success: function (data){
          if (data.code === 1) {
            $("#newNotesFormForm")[0].reset();
            $.alert({
                title: 'Alert!',
                content: 'Notes added successfully',
            });
            setTimeout(function(){
              location.reload();
            }, 8000);
          }
          else if (data.code > 5) {
            $.alert({
                title: 'Alert!',
                content: data.msg,
            });
          }
          else {
            $.alert({
                title: 'Alert!',
                content: 'Your request could not be handled. Try again !',
            });

          }
        }
    });
    });

    $('#financeForm').submit(function(evt){
      evt.preventDefault();
      var formData = new FormData($(this)[0]);
      $.ajax({
          type: "POST",
          url: base_url + '/clients/finance_store',
          data : formData,
          processData: false,
          contentType: false,
          async: false,
          success: function (data){
            if (data.code === 1) {
              $("#financeForm")[0].reset();
              $.alert({
                  title: 'Alert!',
                  content: 'Payment Details added successfully',
              });
              setTimeout(function(){
                location.reload();
              }, 8000);
            }
            else if (data.code > 1) {
              $.alert({
                  title: 'Alert!',
                  content: data.msg,
              });
            }
            else {
              $.alert({
                  title: 'Alert!',
                  content: 'Your request could not be handled. Try again !',
              });

            }
          },
          error: function(error){
            //console.log(error);
            //console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
            var output = $.parseJSON(error.responseText);
              // console.log(output.errors);
              $('#financeNotifyArea').removeClass('hidden');
              $('#financeNotifyArea').addClass('alert alert-danger');
              $.each(output.errors, function (key, value) {
                // console.log(value[0]);
                $('#financeNotifyArea').text(value[0]);
              });
          }
      });
    });

    $('#supportFeesEntryForm').submit(function(evt){
      evt.preventDefault();
      var formData = new FormData($(this)[0]);
      $.ajax({
          type: "POST",
          url: base_url + '/clients/support_fees_store',
          data : formData,
          processData: false,
          contentType: false,
          async: false,
          success: function (data){
            if (data.code === 1) {
              $("#financeForm")[0].reset();
              $.alert({
                  title: 'Alert!',
                  content: 'Support Fees Details added successfully',
              });
              setTimeout(function(){
                location.reload();
              }, 8000);
            }
            else if (data.code > 5) {
              $.alert({
                  title: 'Alert!',
                  content: data.msg,
              });
            }
            else {
              $.alert({
                  title: 'Alert!',
                  content: 'Your request could not be handled. Try again !',
              });

            }
          },
          error: function(error){
            //console.log(error);
            //console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
            var output = $.parseJSON(error.responseText);
              // console.log(output.errors);
              $('#financeNotifyArea').removeClass('hidden');
              $('#financeNotifyArea').addClass('alert alert-danger');
              $.each(output.errors, function (key, value) {
                // console.log(value[0]);
                $('#financeNotifyArea').text(value[0]);
              });
          }
      });
    });

    /*
    $('#financeServicesStore').change(function(evtt){
      let currentServices = $('#financeServicesStore').val();
      $.each(currentServices, function (key, value) {
        // console.log(value);
        let short_code_services = ["USSD", "SMS Application", "IVR"];
        let checkArray = $.inArray(value, short_code_services) > -1;
        // console.log(checkArray);
        if (checkArray == true) {
          $('#ShortCodeFormGrp').removeClass('hidden');
        }
        else{
          $('#ShortCodeFormGrp').addClass('hidden');
        }
      });
    });
    */

    $('#financeEditForm').submit(function(evt){
      evt.preventDefault();
      var formData = new FormData($(this)[0]);
      $.ajax({
          type: "POST",
          url: base_url + '/clients/finance_update',
          data : formData,
          processData: false,
          contentType: false,
          async: false,
          success: function (data){
            if (data.code === 1) {
              $.alert({
                  title: 'Alert!',
                  content: 'Payment Details successfully updated',
              });
              setTimeout(function(){
                location.reload();
              }, 8000);
            }
            else if (data.code > 1) {
              $.alert({
                  title: 'Alert!',
                  content: data.msg,
              });
            }
            else {
              $.alert({
                  title: 'Alert!',
                  content: 'Your request could not be handled. Try again !',
              });

            }
          }
      });
    });

    $('#shortCodeEditForm').submit(function(evt){
      evt.preventDefault();
      var formData = new FormData($(this)[0]);
      $.ajax({
          type: "POST",
          url: base_url + '/clients/shortcode_update',
          data : formData,
          processData: false,
          contentType: false,
          async: false,
          success: function (data){
            if (data.code === 1) {
              $.alert({
                  title: 'Alert!',
                  content: 'Short Code Details successfully updated',
              });
              setTimeout(function(){
                location.reload();
              }, 8000);
            }
            else if (data.code > 1) {
              $.alert({
                  title: 'Alert!',
                  content: data.msg,
              });
            }
            else {
              $.alert({
                  title: 'Alert!',
                  content: 'Your request could not be handled. Try again !',
              });

            }
          }
      });
    });

    $('#editNotesForm').submit(function(evt){
      evt.preventDefault();
      // console.log($(this).length);
      var formData = new FormData($(this)[0]);
      $.ajax({
          type: "POST",
          url: base_url + '/clients/notes_update',
          data : formData,
          processData: false,
          contentType: false,
          async: false,
          success: function (data){
            if (data.code === 1) {
              $.alert({
                  title: 'Alert!',
                  content: 'Notes Details successfully updated',
              });
              setTimeout(function(){
                location.reload();
              }, 8000);
            }
            else if (data.code > 1) {
              $.alert({
                  title: 'Alert!',
                  content: data.msg,
              });
            }
            else {
              $.alert({
                  title: 'Alert!',
                  content: 'Your request could not be handled. Try again !',
              });

            }
          }
      });
    });

    $('#shortCodeForm').submit(function(evt){
      evt.preventDefault();
      var formData = new FormData($(this)[0]);
      $.ajax({
          type: "POST",
          url: base_url + '/clients/shortcode_store',
          data : formData,
          processData: false,
          contentType: false,
          async: false,
          success: function (data){
            if (data.code === 1) {
              $.alert({
                  title: 'Alert!',
                  content: 'Short code details successfully saved',
              });
              setTimeout(function(){
                location.reload();
              }, 8000);
            }
            else if (data.code > 1) {
              $.alert({
                  title: 'Alert!',
                  content: data.msg,
              });
            }
            else {
              $.alert({
                  title: 'Alert!',
                  content: 'Your request could not be handled. Try again !',
              });

            }
          },
          error: function (data) {
              var output = $.parseJSON(data.responseText);
              // console.log(output.errors);
              $('#notifyArea').removeClass('hidden');
              $.each(output.errors, function (key, value) {
                // console.log(value[0]);
                $('#notifyArea').text(value[0]);
              });
          },
          fail : function(errordata){
            // console.log(errordata);
          }
      });
    });

    $('#newSenderIdForm').submit(function(evt){
      evt.preventDefault();
      var formData = new FormData($(this)[0]);
      $.ajax({
          type: "POST",
          url: base_url + '/senderids/direct_store',
          data : formData,
          processData: false,
          contentType: false,
          async: false,
          success: function (data){
            if (data.code === 1) {
              $.alert({
                  title: 'Alert!',
                  content: 'Sender ID successfully saved',
              });
              setTimeout(function(){
                location.reload();
              }, 8000);
            }
            else if (data.code > 1) {
              $.alert({
                  title: 'Alert!',
                  content: data.msg,
              });
            }
            else {
              $.alert({
                  title: 'Alert!',
                  content: 'Your request could not be handled. Try again !',
              });

            }
          },
          error: function (data) {
              var output = $.parseJSON(data.responseText);
              console.log(output.errors);
              $('#senderIdnotifyArea').removeClass('hidden');
              $.each(output.errors, function (key, value) {
                console.log(value[0]);
                $('#senderIdnotifyArea').text(value[0]);
              });
          },
          fail : function(errordata){
            console.log(errordata);
          }
      });
    });
  });
