<script>
<?php if ($page_name == 'subcontracts_view') { ?>
  $("#table_filter_work").select2({
    placeholder: "Select  Material",
    templateResult: format_project_dropdown
  })
  $("#table_filter_work_type").select2({
    placeholder: "Select  Work Type"
  })
  $("#table_filter_contractor").select2({
    placeholder: "Select Contractor"
  })
  <?php } ?>

  function select_work_type(select_id) {
    $('#' + select_id).html('');
    $("#" + select_id).append("<option value='all' selected >All Work Types</option>");
    $.post("<?php echo base_url() ?>work_types/select", {}, function(data) {
      var obj = $.parseJSON(data);
      var i = 0;
      if (obj.count > 0) {
        while (i < obj.id.length) {
          $("#" + select_id).append("<option value=" + obj.id[i] + ">" + obj.name[i] + "</option>");
          i++;
        }
      }
    })
  }
  select_work_type("table_filter_work_type");

  $('body').on('click', '#btn_approve_subcontract', function() {
    var no = $(this).closest('tr').children('td');
    $('#subcontract_id_appoval').val(no.eq(26).text());
    $("input[name=subcontract_approval_status][value=" + $(this).data('approval-status') + "]").prop('checked', true);
  })
  $('body').on('click', '#subcontract_delete_btn', function() {
    var no = $(this).closest('tr').children('td');
    $('#delete_contract_id').val(no.eq(26).text());
  })
  $('body').on('click', '#btn_print_subcontract', function() {
    var id = $(this).data('contract-id');
    window.open('<?php echo base_url() . 'subcontracts/print/' ?>' + id, 'newwindow', 'width=1200,height=700');
    return false
  });
  $('input[type=radio][name=subcontract_data_type]').change(function() {
    if (this.value == 'bill') {
      $(".subcontract_bill_fields_div").show();
      $(".subcontract_bill_add_required_fields").attr('required', true);
      $("#subcontract_bill_gross_amount_add").attr('min', 0);
      $("#subcontract_bill_paid_amount_add").attr('min', 0);
    } else {
      $(".subcontract_bill_fields_div").hide();
      $(".subcontract_bill_add_required_fields").removeAttr('required', true);
      $("#subcontract_bill_gross_amount_add").attr('min', 0);
      $("#subcontract_bill_paid_amount_add").attr('min', 0);
    }
  });

  $("#subcontract_bill_tax_percent_add").select2({
    placeholder: "Select Tax %",
    dropdownParent: $("#form_subcontract_bill_add")
  })
  $("#subcontract_bill_debit_acc_add").select2({
    placeholder: "Select Debit Account",
    dropdownParent: $("#form_subcontract_bill_add")
  })
  $("#subcontract_bill_payment_mode_add").select2({
    placeholder: "Select Debit Account",
    dropdownParent: $("#form_subcontract_bill_add")
  })
  $("#subcontract_bill_paid_date_add,#subcontract_bill_paid_date_edit,#subcontract_bill_reference_date_add,subcontract_bill_reference_date_edit,#subcontract_bill_date_add").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 } ?>
    })

    $("#subcontract_bill_debit_acc_edit").select2({
      placeholder: "Select Debit Account",
      dropdownParent: $("#form_subcontract_bill_edit")
    })
    $("#subcontract_bill_payment_mode_edit").select2({
      placeholder: "Select Debit Account",
      dropdownParent: $("#form_subcontract_bill_edit")
    })
    $("#subcontract_bill_tax_percent_edit").select2({
      placeholder: "Select Tax %",
      dropdownParent: $("#form_subcontract_bill_edit")
    })

    function calculate_subcontract_bill_balance(form_type = '') {
      if (form_type == 'edit') {
        var payable_amount = ($("#subcontract_bill_payable_amount_edit").val() == '') ? 0 : parseFloat($("#subcontract_bill_payable_amount_edit").val());
        var paid_amount = ($("#subcontract_bill_total_paid_edit").val() == '') ? 0 : parseFloat($("#subcontract_bill_total_paid_edit").val());
        $("#subcontract_bill_total_balance_edit").val(payable_amount - paid_amount);
      } else {
        var payable_amount = ($("#subcontract_bill_payable_amount_add").val() == '') ? 0 : parseFloat($("#subcontract_bill_payable_amount_add").val());
        var paid_amount = ($("#subcontract_bill_paid_amount_add").val() == '') ? 0 : parseFloat($("#subcontract_bill_paid_amount_add").val());
        $("#subcontract_bill_balance_amount_add").val(payable_amount - paid_amount);
      }
    }
    $('body').on('change keyup', '#subcontract_bill_paid_amount_add', function() {
      var value = $(this).val();
      if (value == "" || value == null) {
        // $(this).val(0)
      }
      if ($(this).val() > 0) {
        $(".subcontract_bill_paid_amount_req_fields").attr('required', true);
      } else {
        $(".subcontract_bill_paid_amount_req_fields").removeAttr('required', true);
      }
      calculate_subcontract_bill_balance('add');
    })
    $('body').on('change keyup', '.form_subcontract_bill_amount_fields_add', function() {
      var value = $(this).val();
      if (value == "" || value == null) {
        $(this).val(0);
      }
      var bill_gross_amount = parseFloat($('#subcontract_bill_gross_amount_add').val());
      var tax_percent = parseFloat($('#subcontract_bill_tax_percent_add :selected').val());
      var bill_tax_amount = parseFloat(bill_gross_amount * tax_percent / 100);
      $('#subcontract_bill_tax_amount_add').val(bill_tax_amount.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2') ?>));
      var bill_tds_amount = parseFloat($('#subcontract_bill_tds_amount_add').val());
      var payable_amount = bill_gross_amount + bill_tax_amount - bill_tds_amount;
      $('#subcontract_bill_payable_amount_add').val(payable_amount.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2') ?>));
      $("#subcontract_bill_paid_amount_add").val($('#subcontract_bill_payable_amount_add').val());
      $("#subcontract_bill_paid_amount_add").attr('max', $('#subcontract_bill_payable_amount_add').val());
      if ($("#subcontract_bill_paid_amount_add").val() > 0) {
        $(".subcontract_bill_paid_amount_req_fields").attr('required', true);
      } else {
        $(".subcontract_bill_paid_amount_req_fields").removeAttr('required', true);
      }
      calculate_subcontract_bill_balance('add');
    })
    $('body').on('change keyup', '#subcontract_bill_date_add', function() {
      $("#subcontract_bill_paid_date_add").datepicker("setDate", $(this).val());
    })
    // $('body').on('click', '#btn_add_subcontract_bill', function() {
    //   var no = $(this).closest('tr').children('td');
    //   $('#subcontract_id_bill_add').val(no.eq(20).text());
    //   $('#contract_id_bill_add').val(no.eq(1).text());
    //   $('#subcontract_bill_project_add').val(no.eq(2).text());
    //   $('#subwork_name_bill_add').val(no.eq(5).text());
    //   $('#subwork_type_bill_add').html(no.eq(3).html());
    //   $('#subcontract_bill_consignee_add').val(no.eq(6).text());
    //   $('#subcontract_bill_description_add').val(no.eq(7).text());
    // })

    $('body').on('change keyup', '.form_subcontract_bill_amount_fields_edit', function() {
      var value = $(this).val();
      if (value == "" || value == null) {
        $(this).val(0);
      }
      var bill_gross_amount = parseFloat($('#subcontract_bill_gross_amount_edit').val());
      var tax_percent = parseFloat($('#subcontract_bill_tax_percent_edit :selected').val());
      var bill_tax_amount = parseFloat(bill_gross_amount * tax_percent / 100);
      $('#subcontract_bill_tax_amount_edit').val(bill_tax_amount.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2') ?>));
      var bill_tds_amount = parseFloat($('#subcontract_bill_tds_amount_edit').val());
      var payable_amount = bill_gross_amount + bill_tax_amount - bill_tds_amount;
      $('#subcontract_bill_payable_amount_edit').val(payable_amount.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2') ?>));

      calculate_subcontract_bill_balance('edit');
    })
    $('body').on('click', '#subcontract_bill_edit_btn', function() {
      var no = $(this).closest('tr').children('td');
      var bill_type = $(this).attr('data-bill-type');
      var bill_id_column_no = $(this).attr('data-bill-id-column');
      var bill_id = no.eq(bill_id_column_no).text();
      $.post("<?php echo base_url() ?>bills/get_details", {
        bill_id: bill_id,
        bill_type: bill_type
      }, function(data) {
        var obj = $.parseJSON(data);
        if (obj.count == 1) {
          $('#subcontract_id_bill_edit').val("#" + obj.contract_id);
          $('#subcontract_bill_project_edit').val(obj.project_name);
          $('#subwork_name_bill_edit').val(obj.subwork_name);
          $('#subwork_type_bill_edit').html(obj.subwork_types);
          $('#subcontract_id_bill_edit').val(no.eq(24).text());
          $('#bill_id_edit').val(no.eq(23).text());
          $('#subcontract_bill_consignee_edit').val(no.eq(8).text());
          $('#subcontract_bill_description_edit').val(no.eq(16).text());
          $('#subcontract_bill_no_edit').val(no.eq(7).text());
          $('#subcontract_bill_date_edit').val(no.eq(2).text());
          $('#subcontract_bill_gross_amount_edit').val(no.eq(9).text());
          $('#subcontract_bill_tax_amount_edit').val(no.eq(10).text());
          $('#subcontract_bill_tds_amount_edit').val(no.eq(11).text());
          $('#subcontract_bill_payable_amount_edit').val(no.eq(12).text());
          $('#subcontract_bill_total_paid_edit').val(no.eq(13).text());
          $('#subcontract_bill_total_balance_edit').val(no.eq(14).text());
          $('#subcontract_bill_remarks_edit').val(no.eq(19).text());
          $('#subcontract_labours_no_edit').val(no.eq(18).text());
          $('#subcontract_bill_tax_percent_edit').val(no.eq(26).text()).trigger('change');

        }
      })
      // $('#subcontract_id_bill_add').val(no.eq(20).text());
      // $('#contract_id_bill_add').val(no.eq(1).text());
      // $('#subcontract_bill_project_add').val(no.eq(2).text());
      // $('#subwork_name_bill_add').val(no.eq(5).text());
      // $('#subwork_type_bill_add').html(no.eq(3).html());
      // $('#subcontract_bill_consignee_add').val(no.eq(6).text());
      // $('#subcontract_bill_description_add').val(no.eq(7).text());
    })
      var subcontracts_view_table=function() {
        <?php if ($page_name == 'subcontracts_view') { ?>

          function GetSearchStatus() {
            return $('#table_filter_status').val();
          }

          function GetSearchWork() {
            return $('#table_filter_work').val();
          }
          function GetSearchContractor() {
            return $('#table_filter_contractor').val();
          }
          function GetSearchWorktype() {
            return $('#table_filter_work_type').val();
          }

          function get_branch_id() {
            return $('#company_branch :selected').val();
          }
          <?php } ?>
          <?php if ($page_name == 'user_profile') { ?>

            function GetStartDate() {
              return $('#table_filter_start_date').val();
            }

            function GetEndDate() {
              return $('#table_filter_end_date').val();
            }
            <?php } ?>
              $('#subcontracts_view_table').dataTable().fnDestroy();
              var subcontracts_view_table = $('#subcontracts_view_table').DataTable({
                "ajax": {
                  url: "<?php echo base_url() . 'subcontracts/select_subcontracts' ?>", // json datasource
                  type: "post", // type of method  , by default would be get
                  data: function(d) {
                    <?php if ($page_name == 'subcontracts_view') { ?>
                      d.work = GetSearchWork();
                      d.contractor = GetSearchContractor();
                      d.work_type = GetSearchWorktype();
                      <?php if (!empty($this->config->item('company_branches'))) { ?>
                        d.branch_id = get_branch_id();
                        <?php } ?>
                        <?php } ?>
                        <?php if ($page_name == 'work_profile' || $page_name == 'work_summary') { ?>
                          d.work = "<?php echo $work_data->work_id ?>";
                          <?php } ?>
                          <?php if($page_name=='work_profile_master' || $page_name=='work_summary_master'){?>
                            d.work_ids = "<?php echo implode(',',$sub_project_ids)?>";
                            <?php } ?>
                          <?php if ($page_name == 'work_summary') { ?>
                            d.start_date = GetStartDate();
                            d.end_date = GetEndDate();
                            <?php } ?>
                            <?php if ($page_name == 'reports_activity') { ?>
                              d.date = GetSearchDate();
                              d.work = GetSearchWork();
                              <?php } ?>
                              <?php if ($page_name == 'user_profile') { ?>
                                d.user_id = "<?php echo $user_data->user_id ?>";
                                d.start_date = GetStartDate();
                                d.end_date = GetEndDate();
                                <?php } ?>
                                <?php if ($page_name == 'stage_profile' || $page_name == 'stage_summary') { ?>
                                  d.stage_id = "<?php echo $stage_data->stage_id ?>";
                                  <?php } ?>
                                }
                              },
                              "bProcessing": true,
                              "deferRender": true,
                              "bDeferRender": true,
                              <?php if ($page_name == 'work_summary') { ?> "scrollX": false,
                              bFilter: false,
                              "bLengthChange": false,
                              "bPaginate": false,
                              "bInfo": false,
                              buttons: [{
                                extend: 'colvis',
                                className: 'btn dark btn-outline',
                                text: 'Columns'
                              }],
                              "dom": "<'row' <'col-md-12'B>><'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'
                                },
                                title: 'Subcontracts',
                                <?php if($this->config->item('company_letter_head')!=''){ ?>
                                  customize: function ( win ) {
                                    $(win.document.body).prepend(
                                      '<img src="<?php echo base_url().'uploads/company/'.$this->config->item('company_letter_head')?>" style="top:0; left:0;width:100%;" />'
                                    );
                                  }
                                  <?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": [8,13,24, 25, 26 <?php if ($page_name == 'work_profile') {
                                  echo ",3";
                                } ?><?php if ($page_name == 'work_summary') {
                                  echo ",2,3,8,10,21,22,23";
                                } ?><?php if ($page_name == 'reports_activity') {
                                  echo ",23";
                                } ?>
                                <?php if (empty($this->config->item('company_branches'))) { echo ",1"; }?>
                                <?php if ($this->session->userdata('user_role') == 'auditor' && $this->session->userdata('user_data_permission')['adding'] != 1) {
                                  echo ",23";
                                } ?>],
                                className: "hidden"
                              },
                              {
                                render: function(data, type, full, meta) {
                                  return "<div class='text-wrap width-400'>" + data + "</div>";
                                },
                                targets: 8
                              }
                            ]
                          });

                          // $(".table_filter").on("change", function() {
                          //   subcontracts_view_table.ajax.reload();
                          // });
                          $(".hide_column").hide();
                          }
                          <?php if ($page_name == 'subcontracts_view') { ?>
                            $('body').on('click', '#btn_go', function() {
                              $("#subcontracts_view_table").show();
                              subcontracts_view_table();
                            })
                            <?php }else{?>
                              $("#subcontracts_view_table").show();
                              subcontracts_view_table();
                              <?php } ?>

                              <?php if ($page_name == 'subcontracts_view') { ?>
                                $(".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: {
                                      paid_date: {
                                        required: !0
                                      },
                                      paid_amount: {
                                        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,
                                    success: function(e, t, r, s) {
                                      var modal_id = l.attr('data-modal-id');
                                      var form_type = l.attr('data-form-type');
                                      $("#" + form_id + "_msg").addClass("m--hide");
                                      // Block UI
                                      mApp.blockPage({
                                        overlayColor: "#000000",
                                        type: "loader",
                                        state: "success",
                                        message: "Please wait..."
                                      }), setTimeout(function() {
                                        mApp.unblockPage()
                                      }, 2e3);
                                      var obj = $.parseJSON(e);
                                      if (obj.status == 1) {
                                        a.removeClass("m-loader m-loader--right m-loader--light").attr("disabled", !1);
                                        toastr[obj.flashdata_type](obj.flashdata_msg, obj.flashdata_title);
                                        $("#" + modal_id).modal('toggle');
                                        $("." + form_id + "_fields").val('');
                                        $("." + form_id + "_select").val('').trigger("change");
                                        // subcontracts_view_table.ajax.reload();
                                        subcontracts_view_table();
                                      } 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");
                                    }
                                  })
                                )
                              });
                              <?php } ?>
                              </script>
