<?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">
          Add Subcontract Work
        </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 base_url().'dashboard'?>" 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().'subcontracts/add' ?>" class="m-nav__link">
              <span class="m-nav__link-text">
                Add Subcontract Work
              </span>
            </a>
          </li>


        </ul>
      </div>
      <div>

      </div>
    </div>
  </div>
  <!-- END: Subheader -->
  <div class="m-content">
    <!--begin::Portlet-->
    <div class="m-portlet">
      <div class="m-portlet__head">
        <div class="m-portlet__head-caption">
          <div class="m-portlet__head-title">
            <h3 class="m-portlet__head-text">
              Add New Subcontract Work
            </h3>
          </div>
        </div>
      </div>
      <!--begin::Form-->
      <form autocomplete="off" id="form_subcontract_add" data-form-type="subcontract_create" method="post" action="<?php echo base_url().'subcontracts/create'?>" enctype="multipart/form-data" class="m-form m-form--fit m-form--state m-form--label-align-right ">
        <div class="m-portlet__body" style="padding-top: 0px">
          <div class="m-form__content">
            <div class="m-alert m-alert--icon alert alert-warning m--hide" role="alert" id="form_work_msg">
              <div class="m-alert__icon">
                <i class="la la-warning"></i>
              </div>
              <div class="m-alert__text">
                Oh snap! Change a few things up and try submitting again.
              </div>
              <div class="m-alert__close">
                <button type="button" class="close" data-close="alert" aria-label="Close"></button>
              </div>
            </div>
          </div>
          <div style="background: white;border: 4px solid #f7f7fa;padding: 30px;margin: 20px;padding-bottom: 0px">
            <div class="m-section">
              <h3 class="m-section__heading">Contract Details</h3>
              <div class="row">
                <div class="col-lg-4">
                  <div class="form-group m-form__group" >
                    <label for="user_name">
                      Work
                    </label>
                    <div class="m-select2 m-select2--air m-select2--pill">
                      <select required style="width: 100%" class="form-control m-select2 form_subcontract_add_select" id="work_add"  name="work_id" data-placeholder="Select Work">
                        <option selected disabled>Select Work</option>
                        <?php
                        foreach($work_contracts as $row): ?>
                        <option data-work-status="<?php echo $row->work_status?>" value="<?php echo $row->work_id?>"><?php echo $row->work_name?></option>
                        <?php
                      endforeach;
                      ?>
                    </select>
                  </div>
                  <span class="m-form__help"></span>
                </div>
              </div>
              <div class="col-lg-4">
                <div class="form-group m-form__group" >
                  <label for="user_name">
                    Subcontract Work Name
                  </label>
                  <div class="input-group m-input-group m-input-group--pill m-input-group--air">
                    <div class="input-group-prepend">
                      <span class="input-group-text" id="basic-addon1">
                        <i class="fa fa-building"></i>
                      </span>
                    </div>
                    <input required type="text" name="sub_work_name"  class="form-control form_subcontract_add_fields m-input" placeholder="Subcontract Work Name" aria-describedby="basic-addon1">
                  </div>
                  <span class="m-form__help"></span>
                </div>
              </div>
              <div class="col-lg-4">
                <div class="form-group m-form__group">
                  <label>
                    Contrator
                  </label>
                  <div class="input-group m-input-group  m-input-group--pill  m-input-group--air">
                    <div class="input-group-prepend">
                      <a href="#contractor_add_modal"   data-toggle="modal" data-target="#contractor_add_modal" class="btn btn-focus">
                        <i class="fa fa-plus-circle"></i>
                      </a>
                    </div>
                    <select style="width:85%" class="form-control m-select2 m-select2-general" required id="contractor" name="contractor">

                    </select>
                  </div>
                  <span class="m-form__help"></span>
                </div>
              </div>
            </div>
            <div class="row">
              <div class="col-lg-4">
                <div class="m-form__group form-group" >
                  <label class="col-form-label">Contract Type</label>
                  <div class="col-12">
                    <div class="m-radio-inline">
                      <label class="m-radio m-radio--solid m-radio--state-brand">
                        <input required type="radio" name="contract_type" class="form_subcontract_add_fields" checked value="fixed_rate"> Fixed Rate
                        <span></span>
                      </label>
                      <label class="m-radio m-radio--solid m-radio--state-success">
                        <input type="radio" name="contract_type" class="form_subcontract_add_fields" value="unit_rate"> Unit Based Rate
                        <span></span>
                      </label>
                    </div>
                    <span class="m-form__help"></span>
                  </div>
                </div>
              </div>
              <div class="col-lg-4">
                <div class="form-group m-form__group" >
                  <label for="user_name">
                    Reference No
                  </label>
                  <div class="input-group m-input-group m-input-group--pill m-input-group--air">
                    <div class="input-group-prepend">
                      <span class="input-group-text" id="basic-addon1">
                        <i class="fa fa-edit"></i>
                      </span>
                    </div>
                    <input  type="text" name="reference_no"  class="form-control form_subcontract_add_fields m-input" placeholder="Reference No" aria-describedby="basic-addon1">
                  </div>
                  <span class="m-form__help"></span>
                </div>
              </div>
              <div class="col-lg-4">
                <div class="form-group m-form__group" >
                  <label for="user_name">
                    Date
                  </label>
                  <div class="input-group m-input-group m-input-group--pill m-input-group--air">
                    <div class="input-group-prepend">
                      <span class="input-group-text" id="basic-addon1">
                        <i class="fa fa-edit"></i>
                      </span>
                    </div>
                    <input data-date-format="dd-mm-yyyy"  type="text" id="date" name="date"  class="form-control form_subcontract_add_fields m-input" placeholder="Date" aria-describedby="basic-addon1">
                  </div>
                  <span class="m-form__help"></span>
                </div>
              </div>
              <div class="col-lg-12">
                <div class="form-group m-form__group" >
                  <label for="user_name">
                    Work Description
                  </label>
                  <textarea type="text" name="description" id="subcontract_description"  class="form-control m-input form_subcontract_add_fields" placeholder="Work Description" aria-describedby="basic-addon1"></textarea>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div style="background: white;border: 4px solid #f7f7fa;padding: 30px;margin: 20px;padding-bottom: 0px">
          <div class="m-section">
            <div class="row">
              <div class="col-lg-6">
                <h3 class="m-section__heading">Work Details</h3>
              </div>
              <div class="col-lg-6" >
                <a href="#" style="margin-right: 5px;margin-bottom: 20px;float: right" data-toggle="modal" data-target="#work_type_add_modal" class="btn btn-sm btn-info m-btn m-btn--custom m-btn--icon m-btn--air m-btn--pill">
                  <span>
                    <i class="la la-plus"></i>
                    <span>
                      Add Work Type
                    </span>
                  </span>
                </a>
                <a href="#" style="margin-right: 5px;float: right" data-toggle="modal" data-target="#unit_add_modal" class="btn btn-sm btn-focus m-btn m-btn--custom m-btn--icon m-btn--air m-btn--pill">
                  <span>
                    <i class="la la-plus"></i>
                    <span>
                      Add Measure Unit
                    </span>
                  </span>
                </a>
              </div>
            </div>
            <table style="width: 100%;max-width: 100%"  id="table_work" class="table order-list table-striped table-bordered table-advance table-hover" style="display: none">
              <thead>
                <tr>
                  <th style="width:6%">Sl No</th>
                  <th style="width:18%">Work Type</th>
                  <th style="width:12%" class="unit_rate_element">Measure Unit</th>
                  <th style="width:12%" class="unit_rate_element">Rate per Unit</th>
                  <th style="width:12%" class="unit_rate_element">Total Qty</th>
                  <th style="width:8%" class="unit_rate_element">Tax %</th>
                  <th style="width:13%">Total Amt</th>
                  <th style="width:20%">Remarks</th>
                  <th style="width:5%"></th>
                </tr>
              </thead>
              <tbody id="table_work_body">
                <tr data-row-no="0" class="row_0">
                  <td><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input style="padding: 10px" readonly type="text" class="form-control m-input" name="work[sl_no][0]" value="1"/></div></div></td>
                  <td><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class="m-select2 m-select2--air m-select2--pill">
                    <select required style="width: 100%" class="form-control m-select2  work_type" name="work[work_type][0]" id="work_type_1"></select></div></div></td>
                    <td class="unit_rate_element"><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class="m-select2 m-select2--air m-select2--pill">
                      <select style="width: 100%" class="form-control m-select2  measure_unit unit_rate_fields" name="work[unit][0]" id="unit_1"></select></div></div></td>
                      <td class="unit_rate_element"><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text"  class="form-control m-input unit_rate_fields numeric_fields unit_rate" value="0" data-sl-no="1" name="work[unit_rate][0]" id="unit_rate_1"/></div></div></td>
                      <td class="unit_rate_element"><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text"  class="form-control m-input unit_rate_fields numeric_fields" value="0" data-sl-no="1" name="work[quantity][0]" id="quantity_1"/></div></div></td>
                      <td class="unit_rate_element"><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text"  class="form-control m-input unit_rate_fields numeric_fields" value="0" data-sl-no="1" name="work[tax_percentage][0]" id="tax_percentage_1"/></div></div></td>
                      <td><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text" required class="form-control m-input est_amount numeric_fields" value="0" name="work[est_amount][0]" id="est_amount_1"/></div></div></td>
                      <td><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text"  class="form-control m-input" name="work[remarks][0]" id="remarks_1"/></div></div></td>
                      <td></td>
                    </tr>
                    <tr data-row-no="0" class="row_0">
                      <td></td>
                      <td colspan="7">
                        <div class="form-group m-form__group" >
                          <textarea type="text" name="work[work_description][0]" id="work_description_1"  class="form-control m-input m-input--pill m-input--air" placeholder="Work Description" aria-describedby="basic-addon1"></textarea>
                        </div>
                      </div>
                    </td>
                  </tr>
                </tbody>
                <tfoot>
                  <tr>
                    <td colspan="8"  style="text-align: left;border-bottom: 1px solid #e7ecf1;">
                      <button type="button"  class="btn btn-block " id="addrow"><i class="fa fa-plus-square"></i> Add New Work</a>
                      </td>
                    </tr>
                    <tr>
                    </tr>
                  </tfoot>
                </table>
                <input type="hidden" value="1" id="current_row_count" name="current_row_count" >
              </div>
            </div>
            <div  style="background: white;border: 4px solid #f7f7fa;padding: 30px;margin: 20px;padding-bottom: 0px;">
              <div class="m-section">
                <h3 class="m-section__heading">Summary</h3>
                <div class="row">
                  <div class="col-lg-6">
                    <div class="form-group m-form__group" >
                      <label for="user_name">
                        Total No. of Works
                      </label>
                      <div class="input-group m-input-group m-input-group--pill m-input-group--air">
                        <div class="input-group-prepend">
                          <span class="input-group-text" id="basic-addon1">
                            <i class="la la-edit"></i>
                          </span>
                        </div>
                        <input value="0" readonly type="text" name="total_works" id="total_works"  class="form-control form_subcontract_add_fields m-input" aria-describedby="basic-addon1">
                      </div>
                      <span class="m-form__help"></span>
                    </div>
                  </div>
                  <div class="col-lg-6">
                    <div class="form-group m-form__group" >
                      <label for="user_name">
                        Total Estimated Amount
                      </label>
                      <div class="input-group m-input-group m-input-group--pill m-input-group--air">
                        <div class="input-group-prepend">
                          <span class="input-group-text" id="basic-addon1">
                            <?php echo $this->config->item('Currency_currency_format'); ?>
                          </span>
                        </div>
                        <input value="0" readonly type="text" name="total_est_amount" id="total_est_amount"  class="form_subcontract_add_fields form-control m-input op_fields"  aria-describedby="basic-addon1">
                      </div>
                      <span class="m-form__help"></span>
                    </div>
                  </div>
                </div>
                <div class="row">
                  <div class="col-lg-4">
                    <div class="form-group m-form__group" >
                      <label for="user_name">
                        Retention %
                      </label>
                      <div class="input-group m-input-group m-input-group--pill m-input-group--air">
                        <div class="input-group-prepend">
                          <span class="input-group-text" id="basic-addon1">
                            <?php echo $this->config->item('Currency_currency_format'); ?>
                          </span>
                        </div>
                        <input value="0" type="text" name="retention_percent" id="retention_percent"  class="form_subcontract_add_fields form-control m-input op_fields"  aria-describedby="basic-addon1">
                      </div>
                      <span class="m-form__help"></span>
                    </div>
                  </div>
                  <div class="col-lg-4">
                    <div class="form-group m-form__group" >
                      <label for="user_name">
                        Retention Amount
                      </label>
                      <div class="input-group m-input-group m-input-group--pill m-input-group--air">
                        <div class="input-group-prepend">
                          <span class="input-group-text" id="basic-addon1">
                            <?php echo $this->config->item('Currency_currency_format'); ?>
                          </span>
                        </div>
                        <input value="0" readonly type="text" name="retention_amount" id="retention_amount"  class="form_subcontract_add_fields form-control m-input "  aria-describedby="basic-addon1">
                      </div>
                      <span class="m-form__help"></span>
                    </div>
                  </div>
                  <div class="col-lg-4">
                    <div class="form-group m-form__group" >
                      <label for="user_name">
                        Total Payable Amount
                      </label>
                      <div class="input-group m-input-group m-input-group--pill m-input-group--air">
                        <div class="input-group-prepend">
                          <span class="input-group-text" id="basic-addon1">
                            <?php echo $this->config->item('Currency_currency_format'); ?>
                          </span>
                        </div>
                        <input value="0" readonly type="text" name="payable_amount" id="payable_amount"  class="form_subcontract_add_fields form-control m-input "  aria-describedby="basic-addon1">
                      </div>
                      <span class="m-form__help"></span>
                    </div>
                  </div>
                </div>
                <div class="row">
                  <div class="col-lg-4">
                    <div class="form-group m-form__group" >
                      <label for="user_name">
                        Opening Balance Paid (Already Paid Before A/C Creation)
                      </label>
                      <div class="input-group m-input-group m-input-group--pill m-input-group--air">
                        <div class="input-group-prepend">
                          <span class="input-group-text" id="basic-addon1">
                            <?php echo $this->config->item('Currency_currency_format'); ?>
                          </span>
                        </div>
                        <input value="0" type="text" name="opening_balance" id="opening_balance"  class="form_subcontract_add_fields form-control m-input op_fields"  aria-describedby="basic-addon1">
                      </div>
                      <span class="m-form__help"></span>
                    </div>
                  </div>
                  <div class="col-lg-4">
                    <div class="form-group m-form__group" >
                      <label for="user_name">
                        Balance Payable Amount
                      </label>
                      <div class="input-group m-input-group m-input-group--pill m-input-group--air">
                        <div class="input-group-prepend">
                          <span class="input-group-text" id="basic-addon1">
                            <?php echo $this->config->item('Currency_currency_format'); ?>
                          </span>
                        </div>
                        <input value="0" readonly type="text" name="balance_payable_amount" id="balance_payable_amount"  class="form_subcontract_add_fields form-control m-input "  aria-describedby="basic-addon1">
                      </div>
                      <span class="m-form__help"></span>
                    </div>
                  </div>
                  <div class="col-lg-4">
                    <?php if ($this->config->item('Data_billing_addresses') == 1){?>
                      <div class="form-group m-form__group" >
                        <label for="user_name">
                          Select Billing Address
                        </label>
                        <div class="m-select2 m-select2--air m-select2--pill">
                          <select required style="width: 100%" class="form-control m-select2 form_subcontract_add_select" id="billing_address_id_add"  name="billing_address_id" data-placeholder="Select Billing Address">
                            <option selected disabled>Select Billing Address</option>
                            <?php
                            foreach($billing_address as $row): ?>
                            <option data-address="<?php echo $row->billing_address?>" value="<?php echo $row->id?>"><?php echo $row->title?></option>
                            <?php
                          endforeach;
                          ?>
                        </select>
                      </div>
                    </div>
                  <?php } ?>
                  <div class="form-group m-form__group" >
                    <label for="user_name">
                      Billing Address
                    </label>
                    <div class="m-input-icon m-input-icon--right">
                      <?php
                      $company_address = '';
                      if ($this->config->item('Data_billing_addresses') != 1){
                        $company_address .= $this->config->item('company_name')."<br/>";
                        $company_address .= $this->config->item('company_address');
                        $company_address = preg_replace('#(<br */?>\s*)+#i', '<br />',$company_address);
                        $company_address = str_replace('<br />','&#13;&#10;',$company_address);
                        $company_address = str_replace('<br/>','&#13;&#10;',$company_address);
                        $company_address = str_replace('<br>','&#13;&#10;',$company_address);
                      }
                      ?>
                      <textarea style="" rows="4" id="billing_address" name="billing_address" class="form-control m-input m-input--pill m-input--air"><?php echo $company_address ?></textarea>
                    </div>
                    <span class="m-form__help"></span>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="m-portlet ">
            <div class="m-portlet__head">
              <div class="m-portlet__head-caption">
                <div class="m-portlet__head-title">
                  <h4 class="m-portlet__head-text">Terms and Conditions</h4>
                </div>
              </div>
            </div>
            <div class="m-portlet__body">

              <div class="row">
                <div class="col-lg-12">
                  <table style="width: 100%;max-width: 100%"  id="table_terms" class="table m-table m-table--head-bg-success order-list table-striped table-bordered table-advance table-hover">
                    <thead>
                      <tr>
                        <th style="width:5%">Sl No</th>
                        <th style="width:20%">Title</th>
                        <th style="width:30%">Description</th>
                        <th style="width:6%">&nbsp;</th>
                      </tr>
                    </thead>
                    <tbody id="table_body_terms">
                      <?php
                      $i=0;
                      ?>

                    </tbody>
                    <tfoot>
                      <tr>
                        <td colspan="10"  style="text-align: left;border-bottom: 1px solid #e7ecf1;">
                          <button type="button"  class="btn btn-block " id="addrow_terms"><i class="fa fa-plus-square"></i> Add new Terms and Condition</button>
                        </td>
                      </tr>
                    </tfoot>
                  </table>
                  <input type="hidden" value="<?php echo $i ?>" id="current_row_count_terms_and_conditions" name="current_row_count" >
                  <input type="hidden" value="<?php echo $i ?>" id="actual_row_count_terms_and_conditions" name="actual_row_count" >
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="m-portlet__foot m-portlet__foot--fit">
          <div class="m-form__actions m-form__actions">
            <div class="row">
              <div class="col-lg-9 ml-lg-auto">
                <button type="submit" class="btn btn-brand form_submit_btn">
                  Submit
                </button>
                <button type="reset" class="btn btn-secondary">
                  Cancel
                </button>
              </div>
            </div>
          </div>
        </div>
      </form>
      <!--end::Form-->

    </div>
  </div>
  <?php $this->view("modules/include_modals/modal_unit_add");?>
  <?php $this->view("modules/include_modals/modal_work_type_add");?>

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

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

<?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>
$("#subcontract_menu").addClass('m-menu__item--active m-menu__item--open');
$("#subcontract_menu_1").addClass('m-menu__item--active');
</script>
<script>
$("#m_aside_left_minimize_toggle").addClass("m-brand__toggler--active");
$("#body").addClass("m-brand--minimize m-aside-left--minimize");
$("#contractor").select2({
  placeholder: "Select Contractor",
  dropdownParent: $("#form_subcontract_add")
})
$("#billing_address_id_add").select2({
  placeholder: "Select Address",
  dropdownParent: $("#form_subcontract_add")
})

$('body').on('change', '#billing_address_id_add', function() {
  var address = $('#billing_address_id_add :selected').data('address');
  $("#billing_address").val(address);
})
$("#subcontract_description").summernote({height:300});

$("#date").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_id')>2 && $this->config->item('User_calendar_date_restriction_enabled')==1){ ?>
    startDate: '<?php echo $this->config->item('User_calendar_date_restriction_start_days');?>d'
    <?php } ?>
  });
  select_contractors();
  function select_contractors(){
    $('#contractor').html('');
    $("#contractor").append("<option disabled selected >Select contractor</option>");
    $.post("<?php echo base_url() ?>Subcontracts/select_contractors_list",{},function(data) {
      var obj = $.parseJSON(data);
      var i=0;
      if(obj.count>0) {
        while (i < obj.id.length) {
          $("#contractor").append("<option value=" + obj.id[i] + ">" + obj.name[i] + "</option>");
          i++;
        }
      }
    })
  }

  $('body').on('change keyup', '.op_fields', function() {
    calculate_total();
  })
  function calculate_total(){
    var total_est_amount = parseFloat($("#total_est_amount").val());
    var retention_percent = parseFloat($("#retention_percent").val());
    var retention_amount = total_est_amount*retention_percent/100;
    $("#retention_amount").val(retention_amount.toFixed(2));
    var opening_balance = parseFloat($("#opening_balance").val());
    var payable = total_est_amount - retention_amount;
    $("#payable_amount").val(payable.toFixed(2));
    if($("#payable_amount").val()=='NaN')
    {
      $("#payable_amount").val('0');
    }
    var balance_payable = payable-opening_balance;
    $("#balance_payable_amount").val(balance_payable.toFixed(2));
  }

  $("#work_add").select2({
    placeholder: "Select Work",
    dropdownParent: $("#form_subcontract_add"),
    templateResult: format_project_dropdown
  })
  var selected_work = "<?php echo $work_id?>";
  if(selected_work!=''){
    $("#work_add").val(selected_work).trigger('change');
  }
  function select_work_type(select_id){
    $(select_id).each(function (index, value) {
      var id = $(this).attr('id');
      var selected_option = $('#'+id+' :selected').val();
      $("#"+id).html('');
      $("#"+id).append("<option disabled selected >Select Work Type</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) {
            $("#"+id).append("<option value=" + obj.id[i] + ">" + obj.name[i] + "</option>");
            i++;
          }
        }
        if(selected_option!=''){
          $("#"+id).val(selected_option).trigger('change');
        }
      })
    });
    $(".work_type").select2({
      placeholder: "Select Work Type",
      dropdownParent: $("#form_subcontract_add")
    })
  }
  select_work_type(".work_type");

  function select_measure_unit(select_id){
    $(select_id).each(function (index, value) {
      var id = $(this).attr('id');
      var selected_option = $('#'+id+' :selected').val();
      $("#"+id).html('');
      $("#"+id).append("<option disabled selected >Select Unit</option>");
      $.post("<?php echo base_url() ?>units/select",{},function(data) {
        var obj = $.parseJSON(data);
        var i=0;
        if(obj.count>0) {
          while (i < obj.id.length) {
            $("#"+id).append("<option value=" + obj.id[i] + ">" + obj.name[i] + "</option>");
            i++;
          }
        }
        if(selected_option!=''){
          $("#"+id).val(selected_option).trigger('change');
        }
      })
    });
    $(".measure_unit").select2({
      placeholder: "Select Unit",
      dropdownParent: $("#form_subcontract_add")
    })
  }
  select_work_type(".work_type");
  contract_type();
  select_measure_unit(".measure_unit");
  calculate_summary();

  function contract_type(){
    var contract_type = $("input[type=radio][name=contract_type]:checked").val();
    if (contract_type == 'fixed_rate') {
      $(".unit_rate_element").hide();
      $(".unit_rate_fields").removeAttr('required',true);
      $(".est_amount").removeAttr('readonly',true);
    }else if (contract_type == 'unit_rate') {
      $(".unit_rate_element").show();
      $(".unit_rate_fields").attr('required',true);
      $(".est_amount").attr('readonly',true);

      $(".numeric_fields").each(function () {
        $(this).rules('add', {
          number: !0
        });
      });

      $(".unit_rate").each(function () {
        var sl_no = $(this).attr('data-sl-no');
        var rate = parseFloat($("#unit_rate_"+sl_no).val());
        var qty = parseFloat($("#quantity_"+sl_no).val());
        var tax_percent = parseFloat($("#tax_percentage_"+sl_no).val());
        var total = rate*qty;
        var tax_amount = parseFloat(total*tax_percent/100);
        var sub_total = total+tax_amount;
        $("#est_amount_"+sl_no).val(sub_total);
        calculate_summary()
      });
    }
  }
  $('input[type=radio][name=contract_type]').change(function() {
    contract_type();
  });
  $('body').on('change keyup', '.unit_rate_fields', function() {
    var sl_no = $(this).attr('data-sl-no');
    var rate = parseFloat($("#unit_rate_"+sl_no).val());
    var qty = parseFloat($("#quantity_"+sl_no).val());
    var tax_percent = parseFloat($("#tax_percentage_"+sl_no).val());
    var total = rate*qty;
    var tax_amount = parseFloat(total*tax_percent/100);
    var sub_total = total+tax_amount;
    $("#est_amount_"+sl_no).val(sub_total);
    calculate_summary()
  });
  $('body').on('change keyup', '.est_amount', function() {
    calculate_summary()
  });

  function calculate_summary(){
    var total_works = total_est_amount = 0;
    $(".est_amount").each(function(){
      total_est_amount += +$(this).val();
    });

    $("#total_est_amount").val(total_est_amount);
    $("#total_works").val($("#current_row_count").val());
    calculate_total();
  }
  </script>
  <script>

  $("#addrow_terms").on("click", function () {
    var i = parseInt($('#current_row_count_terms_and_conditions').val());
    var new_i = i + 1;
    var new_row = '<tr class="row_'+i+'">';
    new_row += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input style="padding: 10px" readonly type="text" class="form-control m-input item_slno" data-sl-no="'+new_i+'" name="terms[sl_no]['+i+']" value="'+new_i+'"/></div></div></td>';
    new_row += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text" class="form-control m-input" name="terms[title]['+i+']" id="title_'+new_i+'"/></div></div></td>';

    new_row += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><textarea rows="2" class="form-control m-input m-input--pill m-input--air" name="terms[description]['+i+']" id="description_'+new_i+'"/></textarea></div></td><td>';

    new_row += '<a href="javascript:" data-row-sl-no="'+i+'" class="ibtnDel_terms btn btn-danger btn-icon-only" ><i class="fa fa-trash"></i></td></tr>';

    $('#table_body_terms').append(new_row);
    $('#current_row_count_terms_and_conditions').val(new_i);
  });

  $("#table_body_terms").on("click", ".ibtnDel_terms", function (event) {
    var sl_no = $(this).attr("data-sl-no");

    var counter = parseInt($("#current_row_count_terms_and_conditions").val());
    $(this).closest("tr").remove();
    counter -= 1;
    $("#current_row_count_terms_and_conditions").val(counter);

  });
  //  User Add / Edit Form Validation
  var FormControls=function() {

    add=function() {
      $("#form_subcontract_add").validate( {
        rules: {
          email: {
            email: !0
          },
          client_contact: {
            number: !0,
            required: !0
          },
          budget_amt: {
            number: !0,
            required: !0
          }
        },
        invalidHandler:function(e, r) {
          var i=$("#form_work_msg");
          i.removeClass("m--hide").show(), mUtil.scrollTo(i, -200)
        }
        , submitHandler:function(e) {
          mApp.blockPage({
            overlayColor: "#000000",
            type: "loader",
            state: "primary",
            message: "Processing...Please Wait"
          }), setTimeout(function() {}, 3e3);
          this.submit();
        }
      }
    );
    $('.m-select2,.m-select2-multiple',  $("#form_work")).change(function () {
      $("#form_work").validate().element($(this)); //revalidate the chosen dropdown value and show error or success message for the input
      $(this).select2("close");
    });
  };
  return {
    init:function() {
      add();
    }
  }
}

();
jQuery(document).ready(function() {
  FormControls.init();

  $(".form_submit_btn").click(function (e) {
    $(".numeric_fields").each(function () {
      $(this).rules('add', {
        number: !0
      });
    });
    e.preventDefault();
    var a = $(this),
    l = $(this).closest("form"),
    action = l.attr('action');
    var form_id = l.attr('id');
    l.validate({
      rules: {
        op_balance: {
          number: !0
        }
      }, invalidHandler: function (e, r) {
        var i = $("#" + form_id + "_msg");
        i.removeClass("m--hide").show(), mUtil.scrollTo(i, -200)
      }, submitHandler: function (e) {
      }
    }),
    $(".numeric_fields").each(function () {
      $(this).rules('add', {
        number: !0
      });
    }),
    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);
          $("#"+modal_id).modal('toggle');
          $("."+form_id+"_fields").val('');
          $("."+form_id+"_select").val('').trigger("change");
          toastr[obj.flashdata_type](obj.flashdata_msg, obj.flashdata_title);
          select_work_type(".work_type");
          select_contractors();
          select_measure_unit(".measure_unit");
          if(form_type=="subcontract_create"){
            swal({
              width: 500,
              title: obj.flashdata_title,
              text: obj.flashdata_msg,
              type: obj.flashdata_type,
              showCancelButton: !0,
              confirmButtonText: "Go to Project Profile",
              cancelButtonText: "Add New Subcontract",
              confirmButtonColor: '#3085d6',
              cancelButtonColor: '#d33',
              reverseButtons: !0,
              closeOnClickOutside: false,
              allowOutsideClick: false,
              html: "<br>" +
              '<a href="<?php echo base_url()?>subcontracts"  class="SwalBtn1  btn btn-outline-info customSwalBtn">' + 'View All Subcontracts' + '</button>'+
              '<a href="<?php echo base_url()?>subcontracts/profile/'+obj.contract_id+'"  class="SwalBtn1  btn btn-outline-info customSwalBtn">' + 'Go to Subcontract Profile' + '</button>'
            }).then(function(e) {
              e.value ? window.location.replace("<?php echo base_url()?>work/profile/" + obj.work_id) : "cancel" === e.dismiss && location.reload()
            })
          }

        } 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>
<script>
$(document).ready(function () {
  $("#addrow").on("click", function () {
    var counter = parseInt($("#current_row_count").val());
    var cols = "";
    cols += '<tr data-row-no="'+(counter)+'" class="row_'+(counter)+'">';
    cols += '<td><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input style="padding: 10px" readonly type="text" class="form-control m-input" name="work[sl_no]['+(counter)+']" value="' + (counter+1) + '"/></div></div></td>';
    cols += '<td><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class="m-select2 m-select2--air m-select2--pill">'+
    '<select required style="width: 100%" class="form-control m-select2  work_type" name="work[work_type]['+(counter)+']" id="work_type_' + (counter+1) + '"></select></div></div></td>';
    cols += '<td class="unit_rate_element"><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class="m-select2 m-select2--air m-select2--pill">'+
    '<select style="width: 100%" class="form-control m-select2  measure_unit unit_rate_fields" name="work[unit]['+(counter)+']" id="unit_' + (counter+1) + '"></select></div></div></td>';
    cols += '<td class="unit_rate_element"><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text"  class="form-control m-input unit_rate_fields numeric_fields unit_rate" value="0" data-sl-no="' + (counter+1) + '" name="work[unit_rate]['+(counter)+']" id="unit_rate_' + (counter+1) + '"/></div></div></td>';
    cols += '<td class="unit_rate_element"><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text"  class="form-control m-input unit_rate_fields numeric_fields" value="0" data-sl-no="' + (counter+1) + '" name="work[quantity]['+(counter)+']" id="quantity_' + (counter+1) + '"/></div></div></td>';
    cols += '<td class="unit_rate_element"><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text"  class="form-control m-input unit_rate_fields numeric_fields" value="0" data-sl-no="' + (counter+1) + '" name="work[tax_percentage]['+(counter)+']" id="tax_percentage_' + (counter+1) + '"/></div></div></td>';
    cols += '<td><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text" required class="form-control m-input est_amount numeric_fields" value="0" name="work[est_amount]['+(counter)+']" id="est_amount_' + (counter+1) + '"/></div></div></td>';
    cols += '<td><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text"  class="form-control m-input" name="work[remarks]['+(counter)+']" id="remarks_' + (counter+1) + '"/></div></div></td>';
    cols += '<td><a href="javascript:" data-row-sl-no='+counter+' class="ibtnDel btn btn-danger btn-icon-only" ><i class="fa fa-trash"></i></td>';
    cols += '</tr>';
    cols += '<tr data-row-no="'+(counter)+'" class="row_'+(counter)+'">';
    cols += '<td></td>';
    cols += '<td colspan="7">';
    cols += '<div class="form-group m-form__group" >';
    cols += '<textarea type="text" name="work[work_description]['+(counter)+']" id="work_description_' + (counter+1) + '"  class="form-control m-input m-input--pill m-input--air" placeholder="Work Description" aria-describedby="basic-addon1"></textarea>';
    cols += '</div>';
    cols += '</div>';
    cols += '</td>';
    cols += '</tr>';
    $("#table_work_body").append(cols);
    counter++;
    $("#current_row_count").val(counter);
    select_work_type(".work_type");
    select_measure_unit(".measure_unit");
    contract_type();
    calculate_summary();

  });
  $("#table_work_body").on("click", ".ibtnDel", function (event) {
    var row_sl_no = $(this).data('row-sl-no');
    var counter = parseInt($("#current_row_count").val());
    $('.row_'+row_sl_no).remove();
    counter -= 1;
    $("#current_row_count").val(counter);
  });
})
</script>
