<script>
$("#table_filter_work").select2({
  placeholder: "Select  Work",
  templateResult: format_project_dropdown
});
$("#table_filter_contractor").select2({
  placeholder: "Select Contractor"
});
$("#payment_schedule_work_add").select2({
  placeholder: "Select Work",
  dropdownParent: $("#form_payment_schedule_add"),
  templateResult: format_project_dropdown
})
$("#payment_schedule_work_edit").select2({
  placeholder: "Select Work",
  dropdownParent: $("#form_payment_schedule_edit"),
  templateResult: format_project_dropdown
})
$("#payment_scheduled_date_add,#payment_scheduled_date_edit").datepicker({
  todayHighlight: !0,
  orientation: "bottom left",
  templates: {
    leftArrow: '<i class="la la-angle-left"></i>',
    rightArrow: '<i class="la la-angle-right"></i>'
  },
  // endDate: '+0d',
  <?php if ($this->session->userdata('user_role') != 'admin' && $this->config->item('User_calendar_date_restriction_enabled') == 1) { ?>
    startDate: '<?php echo $this->config->item('User_calendar_date_restriction_start_days'); ?>d'
    <?php } ?>
  })
  $("#table_filter_payment_schedule_start_date,#table_filter_payment_schedule_end_date").datepicker({
    todayHighlight: !0,
    orientation: "bottom left",
    templates: {
      leftArrow: '<i class="la la-angle-left"></i>',
      rightArrow: '<i class="la la-angle-right"></i>'
    }
  })
  // $('#payment_scheduled_date_add').select2();

  <?php if ($page_name == 'client_payments_schedule') { ?>
    // Only for Client Payment View PAge
    $("#table_filter_work").select2({
      placeholder: "Select  Work",
      templateResult: format_project_dropdown
    })
    $("#table_filter_clients").select2({
      placeholder: "Select  Client"
    })

    $("#client_payment_work_edit").select2({
      placeholder: "Select Work",
      dropdownParent: $("#form_client_payment_schedule_edit"),
      templateResult: format_project_dropdown
    })

    $('body').on('change', '#payment_schedule_work_add', function() {
      var work_id = $('#payment_schedule_work_add :selected').val();
      $("#reference_id_add_client_payment").val(work_id);
      $("#reference_type_add_client_payment").val('work');
      $.post("<?php echo base_url() ?>work/select_details", {
        work_id: work_id
      }, function(data) {
        var obj = $.parseJSON(data);
        var i = 0;
        if (obj.count == 1) {
          $("#client_payment_client_name_add").val(obj.data['client_name']);
          $("#client_payment_client_id_add").val(obj.data['client_id']);
        }
      })
    })
    $('body').on('change', '#client_payment_work_edit', function() {
      var work_id = $('#client_payment_work_edit :selected').val();
      $("#reference_id_edit_client_payment").val(work_id);
      $("#reference_type_edit_client_payment").val('project');
      $.post("<?php echo base_url() ?>work/select_details", {
        work_id: work_id
      }, function(data) {
        var obj = $.parseJSON(data);
        var i = 0;
        if (obj.count == 1) {
          $("#client_payment_client_name_edit").val(obj.data['client_name']);
          $("#client_payment_client_id_edit").val(obj.data['client_id']);
        }
      })
    })

    $('body').on('click', '#btn_delete_payment_schedule', function() {
      var no = $(this).closest('tr').children('td');
      $('#schedule_id_delete').val(no.eq(12).text());

    })

    $('body').on('click', '#payment_schedule_edit_btn', function() {
      var no = $(this).closest('tr').children('td');

      $('#client_payment_work_edit').val(no.eq(13).text()).trigger('change');
      $('#scheduled_amount').val(no.eq(7).text());
      $("#payment_scheduled_date_edit").datepicker("setDate", no.eq(6).text());
      $('#stage_no').val(no.eq(4).text());
      $('#stage_name').val(no.eq(5).text());
      $('#remarks').val(no.eq(8).text());
      $('#schedule_id_edit').val(no.eq(12).text());
    })

    <?php } ?>


    <?php if ($page_name == 'subcontract_payments_schedule') { ?>

      $("#payment_schedule_subcontract_add").select2({
        placeholder: "Select Subcontract",
        dropdownParent: $("#form_payment_schedule_add")
      })

      $("#payment_schedule_subcontract_edit").select2({
        placeholder: "Select Subcontract",
        dropdownParent: $("#form_payment_schedule_edit")
      })

      $('body').on('change', '#payment_schedule_work_add', function() {
        var work_id = $('#payment_schedule_work_add :selected').val();
        // $("#reference_id_add_client_payment").val(work_id);
        $("#reference_type_add_subcontract_payment").val('subcontract');
        $.post("<?php echo base_url() ?>subcontracts/select_subcontracts", {
          work: work_id,
          list_type: 'select2_options'
        }, function(data) {
          var obj = $.parseJSON(data);
          var i = 0;
          if (obj.length > 0) {
            $("#payment_schedule_subcontract_add option").remove();
            var opt = '<option selected disabled>Select Subcontract</option>';
            $("#payment_schedule_subcontract_add").append(opt);
            $.each(obj, function(index, value) {
              var opt = '<option value=' + value.contract_id + '>' + value.sub_work_name + ' [ ' + value.contractor + ' ]' + '</option>';
              $("#payment_schedule_subcontract_add").append(opt);
            });
          } else {
            $("#payment_schedule_subcontract_add option").remove();
            var opt = '<option selected disabled>Select Subcontract</option>';
            $("#payment_schedule_subcontract_add").append(opt);
          }
          $("#payment_schedule_subcontract_add option:selected").val();
        })
      })


      $('body').on('change', '#payment_schedule_work_edit', function(e, e_data) {
        var work_id = $('#payment_schedule_work_edit :selected').val();
        // $("#reference_id_add_client_payment").val(work_id);
        $("#reference_type_edit_subcontract_payment").val('subcontract');
        $.post("<?php echo base_url() ?>subcontracts/select_subcontracts", {
          work: work_id,
          list_type: 'select2_options'
        }, function(data) {
          var obj = $.parseJSON(data);
          var i = 0;
          if (obj.length > 0) {
            $("#payment_schedule_subcontract_edit option").remove();
            var opt = '<option selected disabled>Select Subcontract</option>';
            $("#payment_schedule_subcontract_edit").append(opt);
            $.each(obj, function(index, value) {
              var opt = '<option value=' + value.contract_id + '>' + value.sub_work_name + ' [ ' + value.contractor + ' ]' + '</option>';
              $("#payment_schedule_subcontract_edit").append(opt);
            });
          } else {
            $("#payment_schedule_subcontract_edit option").remove();
            var opt = '<option selected disabled>Select Subcontract</option>';
            $("#payment_schedule_subcontract_edit").append(opt);
          }
          if (e_data != null) {
            $('#payment_schedule_subcontract_edit').val(e_data.selected_subcontract).trigger('change');
          }
        })
      })


      $('body').on('click', '#btn_delete_payment_schedule', function() {
        var no = $(this).closest('tr').children('td');
        $('#schedule_id_delete').val(no.eq(13).text());

      })

      $('body').on('click', '#payment_schedule_edit_btn', function() {
        var no = $(this).closest('tr').children('td');

        $('#payment_schedule_work_edit').val(no.eq(14).text()).trigger('change', [{
          selected_subcontract: no.eq(15).text()
        }]);
        $('#scheduled_amount_edit').val(no.eq(8).text());
        $("#payment_scheduled_date_edit").datepicker("setDate", no.eq(7).text());
        $('#stage_no_edit').val(no.eq(5).text());
        $('#stage_name_edit').val(no.eq(6).text());
        $('#tr_remarks_edit').val(no.eq(9).text());
        $('#schedule_id_edit').val(no.eq(13).text());
      })

      <?php } ?>


      function GetSearchStartDate() {
        return $('#table_filter_payment_schedule_start_date').val();
      }

      function GetSearchEndDate() {
        return $('#table_filter_payment_schedule_end_date').val();
      }

      function GetSearchWork() {
        return $('#table_filter_work').val();
      }

      function get_branch_id() {
        return $('#company_branch :selected').val();
      }

      <?php if ($page_name == 'client_payments_schedule') { ?>

        function GetSearchClient() {
          return $('#table_filter_clients').val();
        }
        <?php } ?>
        <?php if ($page_name == 'subcontract_payments_schedule') { ?>

          function GetSearchContractor() {
            return $('#table_filter_contractor').val();
          }
          <?php } ?>

          var payment_schedule_view_table = $('#payments_schedule_view_table').DataTable({
            "ajax": {
              url: "<?php echo base_url() . 'payment_schedule/select_schedule_payments' ?>", // json datasource
              type: "post", // type of method  , by default would be get
              data: function(d) {
                <?php if ($page_name == 'client_payments_schedule') { ?>
                  d.start_date = GetSearchStartDate();
                  d.end_date = GetSearchEndDate();
                  d.clients = GetSearchClient();
                  d.reference = GetSearchWork();
                  d.type = 'client_payment';

                  <?php if (!empty($this->config->item('company_branches'))) { ?>
                    d.branch_id = get_branch_id();
                    <?php } ?>

                    <?php } elseif ($page_name == 'subcontract_payments_schedule') { ?>
                      d.start_date = GetSearchStartDate();
                      d.end_date = GetSearchEndDate();
                      d.reference = GetSearchWork();
                      d.contractor = GetSearchContractor();
                      d.type = 'subcontract_payment';

                      <?php if (!empty($this->config->item('company_branches'))) { ?>
                        d.branch_id = get_branch_id();
                        <?php } ?>

                        <?php } elseif ($page_name == 'work_profile' || $page_name == 'projects_profile' || $page_name == 'work_summary') { ?>
                          d.work = "<?php echo $work_data->work_id ?>";
                          <?php } ?>
                          <?php if ($page_name == 'reports_activity') { ?>
                            d.date = GetSearchDate();
                            d.work = GetSearchWork();
                            <?php } ?>
                          }
                        },
                        "bProcessing": true,
                        "deferRender": true,
                        "bDeferRender": true,
                        <?php if ($page_name == 'work_summary') { ?> "scrollX": false,
                        bFilter: false,
                        "bLengthChange": false,
                        "bPaginate": false,
                        "bInfo": false,
                        "dom": "<'row' <'col-md-12'>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", // horizobtal scrollable datatable
                        <?php } else { ?> "scrollX": true,
                        buttons: [{
                          extend: 'print',
                          className: 'btn dark btn-outline',
                          exportOptions: {
                            columns: ':visible'
                          },
                          <?php if ($page_name == 'client_payments_schedule') { ?>
                            title: 'Client Payment Schedule'
                            <?php } elseif ($page_name == 'subcontract_payments_schedule') { ?>
                              title: 'Subcontract Payment Schedule'
                              <?php } ?>
                            },
                            {
                              extend: 'csv',
                              className: 'btn purple btn-outline '
                            },
                            {
                              extend: 'colvis',
                              className: 'btn dark btn-outline',
                              text: 'Columns'
                            }
                          ],
                          dom: "<'row'<'col-sm-6 text-left'B><'col-sm-6 text-right'f>>\n\t\t\t<'row'<'col-sm-12'tr>>\n\t\t\t<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7 dataTables_pager'lp>>", // horizobtal scrollable datatable
                          "lengthMenu": [
                            [25, 50, 100, -1],
                            [25, 50, 100, "All"] // change per page values here
                          ],
                          <?php } ?> 'order': false,
                          "columnDefs": [{
                            "targets": [1, 13 <?php if ($page_name == 'client_payments_schedule') {
                              echo ',12';
                            } ?><?php if ($page_name == 'subcontract_payments_schedule') {
                              echo ',14,15';
                            } ?><?php if ($page_name == 'work_profile' || $page_name == 'projects_profile') {
                              echo ",4,5";
                            } ?><?php if ($page_name == 'work_summary') {
                              echo ",2,4,5,11,12";
                            } ?><?php if ($page_name == 'reports_activity') {
                              echo ",12";
                            } ?><?php if ($this->session->userdata('user_role') == 'auditor') {
                              echo ",11";
                            } ?>],
                            className: "hidden"
                          }]
                        });
                        $(".table_filter").on("change", function() {
                          payment_schedule_view_table.ajax.reload();
                        });
                        $(".hide_column").hide();

                        <?php if ($page_name == 'client_payments_schedule' || $page_name == 'subcontract_payments_schedule') { ?>
                          // Date Range Picker
                          <?php if ($selected_start_date != '') { ?>
                            var start = moment("<?php echo date('F d, Y', strtotime("01-" . $selected_start_date)) ?>");
                            <?php } else { ?>
                              var start = moment();
                              <?php } ?>

                              <?php if ($selected_end_date != '') { ?>
                                var end = moment("<?php echo date('F t, Y', strtotime("01-" . $selected_end_date)) ?>");
                                <?php } else { ?>
                                  var end = moment();
                                  <?php } ?>

                                  function cb(start, end) {
                                    $('#table_filter_date_range').val(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
                                    payment_schedule_view_table.ajax.reload();
                                  }

                                  $('#table_filter_date_range').daterangepicker({
                                    buttonClasses: "m-btn btn",
                                    applyClass: "btn-primary",
                                    cancelClass: "btn-secondary",
                                    startDate: start,
                                    endDate: end,
                                    locale: {
                                      format: 'MMMM D, YYYY'
                                    },
                                    ranges: {
                                      'Today': [moment(), moment()],
                                      'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                                      'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                                      'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                                      'This Month': [moment().startOf('month'), moment().endOf('month')],
                                      'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
                                      'All time': [moment('1970-01-01'), moment().add(9999, 'days')],
                                    }
                                  }, cb);

                                  cb(start, end);

                                  $(".form_submit_btn").click(function(e) {
                                    e.preventDefault();
                                    var a = $(this),
                                    l = $(this).closest("form"),
                                    action = l.attr('action');
                                    var form_id = l.attr('id');
                                    l.validate({
                                      rules: {
                                        scheduled_amount: {
                                          number: !0,
                                          required: !0
                                        },
                                        stage_no: {
                                          number: !0,
                                          required: !0
                                        }
                                      },
                                      invalidHandler: function(e, r) {
                                        var i = $("#" + form_id + "_msg");
                                        i.removeClass("m--hide").show(), mUtil.scrollTo(i, -200)
                                      },
                                      submitHandler: function(e) {}
                                    }), l.valid() && (a.addClass("m-loader m-loader--right m-loader--light").attr("disabled", !0),
                                    l.ajaxSubmit({
                                      url: action,
                                      beforeSend: function() {
                                        // Handle the beforeSend event
                                        // Block UI
                                        mApp.blockPage({
                                          overlayColor: "#000000",
                                          type: "loader",
                                          state: "success",
                                          message: "Please wait..."
                                        });

                                        mApp.block(".modal-content", {
                                          overlayColor: "#000000",
                                          type: "loader",
                                          state: "success",
                                          message: "Please wait..."
                                        });
                                      },

                                      success: function(e, t, r, s) {
                                        // UnBlock UI

                                        var modal_id = l.attr('data-modal-id');
                                        var form_type = l.attr('data-form-type');
                                        $("#" + form_id + "_msg").addClass("m--hide");

                                        var obj = $.parseJSON(e);
                                        if (obj.status == 1) {
                                          a.removeClass("m-loader m-loader--right m-loader--light").attr("disabled", !1);
                                          $("#" + modal_id).modal('toggle');
                                          $("." + form_id + "_fields").val('');
                                          $("." + form_id + "_select").val('').trigger("change");
                                          payment_schedule_view_table.ajax.reload();
                                          toastr[obj.flashdata_type](obj.flashdata_msg, obj.flashdata_title);
                                        } else {
                                          a.removeClass("m-loader m-loader--right m-loader--light").attr("disabled", !1);
                                          toastr[obj.flashdata_type](obj.flashdata_msg, obj.flashdata_title);
                                        }
                                        if (obj == null) {
                                          setTimeout(function() {
                                            a.removeClass("m-loader m-loader--right m-loader--light").attr("disabled", !1);
                                            toastr["warning"]("Your Attempt is Timed Out. Please Try Again.", "Timed Out");
                                          }, 2e4)
                                        }
                                      },
                                      error: function() {
                                        a.removeClass("m-loader m-loader--right m-loader--light").attr("disabled", !1);
                                        toastr["error"]("Sorry. There Has Been Some Error Occurred. Please Try Again.", "Error");
                                      },
                                      ajaxComplete: function() {
                                        mApp.unblockPage();
                                        mApp.unblock(".modal-content");
                                      },
                                      complete: function() {
                                        mApp.unblockPage();
                                        mApp.unblock(".modal-content");
                                      },
                                    })
                                  )
                                });


                                <?php } ?>
                              </script>
