<?php $this->view("includes/Inc_pagehead"); ?>
<!-- Page Styles Goes Here-->

<?php $this->view("includes/Inc_navigation"); ?>
<div class="m-grid__item m-grid__item--fluid m-wrapper">
  <!-- BEGIN: Subheader -->
  <div class="m-subheader ">
    <div class="d-flex align-items-center">
      <div class="mr-auto">
        <h3 class="m-subheader__title m-subheader__title--separator">
          Sales Targets
        </h3>
        <ul class="m-subheader__breadcrumbs m-nav m-nav--inline">
          <li class="m-nav__item m-nav__item--home">
            <a href="#" class="m-nav__link m-nav__link--icon">
              <i class="m-nav__link-icon la la-home"></i>
            </a>
          </li>
          <li class="m-nav__separator">
            -
          </li>
          <li class="m-nav__item">
            <a href="<?php echo $this->session->userdata("dashboard_link") ?>" class="m-nav__link">
              <span class="m-nav__link-text">
                Home
              </span>
            </a>
          </li>
          <li class="m-nav__separator">
            -
          </li>
          <li class="m-nav__item">
            <a href="<?php echo base_url() . 'sales_targets' ?>" class="m-nav__link">
              <span class="m-nav__link-text">
                Sales Targets
              </span>
            </a>
          </li>


        </ul>
      </div>
      <div>

      </div>
    </div>
  </div>
  <!-- END: Subheader -->
  <div class="m-content">
    <div class="m-portlet m-portlet--mobile m-portlet--info m-portlet--head-solid-bg m-portlet--bordered m-portlet--rounded">
      <div class="m-portlet__head">
        <div class="m-portlet__head-caption">
          <div class="m-portlet__head-title">
            <h3 class="m-portlet__head-text">
              List of Sales Targets
            </h3>
          </div>
        </div>
        <div class="m-portlet__head-tools">

          <?php if ($this->session->userdata('user_role') != 'auditor') { ?>
            <button data-toggle="modal" data-target="#sales_target_add_modal" class="btn btn-focus m-btn m-btn--custom m-btn--icon m-btn--air m-btn--pill">
              <span>
                <i class="la la-plus"></i>
                <span>
                  Create New Sales Targets
                </span>
              </span>
            </button>
          <?php } ?>

        </div>
      </div>
      <div class="m-portlet__body">

        <div class="m-form m-form--label-align-right m--margin-bottom-10">
          <div class="row">
            <div class="col-xl-12 order-2 order-xl-1">
              <div class="form-group m-form__group row ">
                <div class="col-lg-4">
                  <div class="form-group m-form__group">
                    <label>
                      Sales Staff
                    </label>
                    <div class="m-select2 m-select2--air m-select2--pill">
                      <select width="100%" required class="form-control m-select2 table_filter " id="sales_staff_filter">
                        <option disabled="" selected="" value="all">All</option>
                        <?php
                        foreach ($sales_staffs as $key => $value) {
                          echo '<option value="' . $value->user_id . '">' . $value->user_alias . '</option>';
                        }
                        ?>
                      </select>
                    </div>
                    <span class="m-form__help"></span>
                  </div>
                </div>

                <div class="col-lg-4">
                  <div class="form-group m-form__group">
                    <label>
                      Target Type
                    </label>
                    <div class="m-select2 m-select2--air m-select2--pill">
                      <select width="100%" required class="form-control m-select2 table_filter " id="target_type_filter">
                        <option disabled="" selected="" value="all">All</option>
                        <option value="product">Product</option>
                        <option value="service">Service</option>
                      </select>
                    </div>
                    <span class="m-form__help"></span>
                  </div>
                </div>

                <div class="col-lg-2">
                  <div class="form-group m-form__group">
                    <label>
                      Target Month
                    </label>
                    <input readonly placeholder="Month" type="text" value="<?= date('F Y') ?>" id="month_filter" class="form-control table_filter m-input m-input--air m-input--pill" aria-describedby="basic-addon1">
                    <span class="m-form__help"></span>
                  </div>

                </div>
              </div>
            </div>
          </div>
        </div>

        <table width="100%" class="table m-table nowrap table-header-fixed table-striped table-bordered table-hover table-header-fixed" id="sales_targets_view_table">
          <thead>
            <tr class="">
              <th>Sl No</th>
              <th>ID</th>
              <th>Sales Staff</th>
              <th>Month</th>
              <th>Type</th>
              <th>Details</th>
              <th>Creation</th>
              <th>Actions</th>
              <th>staff userid</th>
              <th>Details</th>
            </tr>
          </thead>
          <tbody>
          </tbody>
        </table>

      </div>
    </div>
  </div>
</div>
</div>
<!-- end:: Body -->
<!-- begin::Footer -->

<?php $this->view("modules/include_modals/modal_sales_targets"); ?>


<?php $this->view("includes/Inc_footer"); ?>
<!-- end::Footer -->
</div>
<!-- end:: Page -->

<?php $this->view("includes/Inc_sidebar"); ?>
<?php $this->view("includes/Inc_scripts"); ?>
<!--begin::Page Snippets -->

<script>
  $("#sales_targets_menu").addClass('m-menu__item--active m-menu__item--open');
  // $("#sales_quo_menu_2").addClass('m-menu__item--active');
</script>
<script>
  // month datepicker month select
  $('#month,#month_filter,#month_edit').datepicker({
    format: "MM yyyy",
    viewMode: "months",
    minViewMode: "months"
  });

  // sales_staff select2
  $("#sales_staff,#sales_staff_filter,#sales_staff_edit").select2({
    placeholder: "Select Sales Staff",
  });

  // target_type_filter
  $("#target_type_filter").select2({
    placeholder: "Select Target Type",
  });

  // sales_targets_add_add_row on click add row
  $("#sales_targets_add_add_row").click(function() {
    var row_count = $("#sales_targets_add_table tbody tr").length;
    var row_html = ' <tr> <td> <div class="form-group m-form__group"> <input required type="text" name="items[target_amount][]" class="form-control m-input m-input--air m-input--pill" placeholder="Target Amount"> <span class="m-form__help"></span> </div> </td> <td> <div class="form-group m-form__group"> <input required type="text" name="items[incentive_percent][]" class="form-control m-input m-input--air m-input--pill" placeholder="Incentive %"> <span class="m-form__help"></span> </div> </td> <td> <a style="margin-left: 5px;margin-right: 5px" id="sales_targets_add_remove_btn" class="btn btn-danger text-white m-btn m-btn--icon m-btn--icon-only m-btn--pill m-btn--air"> <i class="la la-trash"></i> </a></a> </td> </tr>';
    $("#sales_targets_add_table tbody").append(row_html);
  });

  $("#sales_targets_edit_add_row").click(function() {
    var row_count = $("#sales_targets_edit_table tbody tr").length;
    var row_html = ' <tr> <td> <div class="form-group m-form__group"> <input required type="text" name="items[target_amount][]" class="form-control m-input m-input--air m-input--pill" placeholder="Target Amount"> <span class="m-form__help"></span> </div> </td> <td> <div class="form-group m-form__group"> <input required type="text" name="items[incentive_percent][]" class="form-control m-input m-input--air m-input--pill" placeholder="Incentive %"> <span class="m-form__help"></span> </div> </td> <td> <a style="margin-left: 5px;margin-right: 5px" id="sales_targets_edit_remove_btn" class="btn btn-danger text-white m-btn m-btn--icon m-btn--icon-only m-btn--pill m-btn--air"> <i class="la la-trash"></i> </a></a> </td> </tr>';
    $("#sales_targets_edit_table tbody").append(row_html);
  });

  // sales_targets_add_remove_row on click remove row
  $(document).on("click", "#sales_targets_add_remove_btn", function() {
    $(this).parent().parent().remove();
  });


  $(document).on("click", "#sales_targets_edit_remove_btn", function() {
    var no = $(this).closest('tr').children('td');
    var id = $(no).find('input[type="hidden"]').val();
    var ids = $("#sales_target_delete_ids").val();
    if (ids != "") {
      ids = ids + ',' + id;
    } else {
      ids = id;
    }
    console.log(ids);
    $("#sales_target_delete_ids").val(ids);
    $(this).parent().parent().remove();
  });



  $('body').on('click', '#sales_target_delete_btn', function() {
    var no = $(this).closest('tr').children('td');
    $('#sales_target_id_delete').val(no.eq(1).text());
  });

  $('body').on('click', '#sales_target_edit_btn', function() {
    var no = $(this).closest('tr').children('td');
    console.log(no);
    $('#sales_target_id_edit').val(no.eq(1).text());
    $('#sales_staff_edit').val(no.eq(8).text()).trigger('change');
    $('#month_edit').val(no.eq(3).text());
    $('[type=radio][name=sales_target_type_edit][value=' + no.eq(4).text().toLowerCase() + ']').prop('checked', true);
    var details = JSON.parse(no.eq(9).text());
    $("#sales_targets_edit_table tbody").html('');
    $i = 0;
    $.each(details, function(index, value) {
      var row_count = $("#sales_targets_edit_table tbody tr").length;
      var row_html = ' <tr> <td> <div class="form-group m-form__group"><input required type="hidden" name="items[id][]" value="' + value.id + '" > <input required type="text" name="items[target_amount][' + $i + ']" class="form-control m-input m-input--air m-input--pill" placeholder="Target Amount" value="' + value.target_amount + '"> <span class="m-form__help"></span> </div> </td> <td> <div class="form-group m-form__group"> <input required type="text" name="items[incentive_percent][]" class="form-control m-input m-input--air m-input--pill" placeholder="Incentive %" value="' + value.incentive_percent + '"> <span class="m-form__help"></span> </div> </td> <td> <a style="margin-left: 5px;margin-right: 5px" id="sales_targets_edit_remove_btn" class="btn btn-danger text-white m-btn m-btn--icon m-btn--icon-only m-btn--pill m-btn--air"> <i class="la la-trash"></i> </a>  </td> </tr>';
      $("#sales_targets_edit_table tbody").append(row_html);
      $i++;
    });
  });

  var Datatable_sales_targets_view_table = function() {

      function get_sales_staff() {
        return $("#sales_staff_filter :selected").val();
      }

      function get_target_type() {
        return $("#target_type_filter :selected").val();
      }

      function get_month() {
        return $("#month_filter").val();
      }


      var t = function() {
        var sales_targets_view_table = $('#sales_targets_view_table').DataTable({
          "ajax": {
            url: "<?php echo base_url() . 'sales_targets/select_sales_targets' ?>", // json datasource
            type: "post", // type of method  , by default would be get
            data: function(d) {
              d.staff = get_sales_staff();
              d.target_type = get_target_type();
              d.month = get_month();
            }
          },
          "bProcessing": true,
          "deferRender": true,
          "bDeferRender": true,
          "scrollX": true,
          buttons: [{
              extend: 'print',
              className: 'btn dark btn-outline',
              title: 'Sales Targets'
            },
            {
              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
          ],
          "columnDefs": [{
              "targets": [1, 8, 9],
              className: "hidden"
            },
            {
              // render: function (data, type, full, meta) {
              //   return "<div class='text-wrap width-300'>" + data + "</div>";
              // },
              // targets: 5
            }
          ],
          'order': false
        });
        $(".table_filter").on("change", function() {
          sales_targets_view_table.ajax.reload();
        });

      };
      return {
        init: function() {
          t()
        }
      }
    }
    ();
  jQuery(document).ready(function() {
    Datatable_sales_targets_view_table.init();
    $(".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: {
          "amount": {
            required: !0,
            number: !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('');
              $('#sales_targets_view_table').dataTable().fnDestroy();
              Datatable_sales_targets_view_table.init();
            } 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");
          }
        })
      )
    });
  });
</script>
