<link rel="stylesheet" href="/admin/assets/libs/select2/select2.css" />
<link rel="stylesheet" href="/admin/assets/css/pages/providers.css?v=2.8.2">
<% const isArabic = typeof lang === 'undefined' || lang !== 'en'; %>
<!-- start content -->
<section id="multiple-column-form" class="kt-provider-form-page">
  <header class="kt-provider-form-hero">
    <div class="kt-provider-form-hero__identity">
      <span class="kt-provider-form-hero__icon" aria-hidden="true"><i class="ti ti-building-store"></i></span>
      <div>
        <span class="kt-provider-form-hero__eyebrow"><%= isArabic ? 'إدارة مقدمي الخدمات' : 'Provider management' %></span>
        <h1><%= isArabic ? 'إضافة مقدم خدمة' : 'Add provider' %></h1>
        <p><%= isArabic ? 'أنشئ ملف الهوية والتشغيل والبيانات المالية في مساحة منظمة وآمنة.' : 'Create identity, operations, and financial details in one secure workspace.' %></p>
      </div>
    </div>
    <a class="kt-provider-form-hero__back" href="<%= referer %>"><i class="ti ti-arrow-right"></i><span><%= i18n.__('common.referer') %></span></a>
  </header>
  <div class="row match-height">
    <div class="col-12">
      <div class="card kt-provider-form-card">

        <div class="card-content">
          <div class="card-body kt-provider-form-card__body">
            <div class="kt-provider-form-card__header">
              <span aria-hidden="true"><i class="ti ti-id-badge-2"></i></span>
              <div><h2><%= isArabic ? 'بيانات مقدم الخدمة' : 'Provider details' %></h2><p><%= isArabic ? 'الحقول المطلوبة موضحة، ويمكن استكمال بيانات الخدمات حسب القسم.' : 'Required fields are marked; service details depend on the selected department.' %></p></div>
            </div>
            <form method="POST" id="createProvider" action="/dashboard/providers/create"
              class="needs-validation store form-horizontal kt-provider-form" novalidate enctype="multipart/form-data">

              <%- include('../../components/input.ejs', inputAttrs={ type: "hidden" , name:"_csrf", value:csrfToken,
                classes: "" , ids:"" }) %>

                <div class="form-body kt-provider-form__body">
                  <div class="row kt-provider-form__grid">

                    <%- include('../../components/image.ejs', { required: 'required' ,
                      url: '' , id: 'avatar' ,
                      name: 'avatar' , imgClass: 'd-block uploadedAvatar medium-img rounded' , invalidFeedback
                      :i18n.__('common.pleaseEnterImage'), layout: 1 }) %>


                      <%- include('../../components/input.ejs', inputAttrs={ type: "text" , name:'name', required:true,
                        placeholder:i18n.__('common.{{field}}Placeholder',{field:i18n.__('common.name')}),
                        label:i18n.__('common.name'),
                        invalidMsg:i18n.__('common.{{field}}Required',{field:i18n.__('common.name')}) ,
                        classes:["form-control"], ids:"", oninput:"validateInput(this)" }) %>


                        <%- include('../../components/input.ejs', inputAttrs={ type: "text" , name:'phone',
                          required:true, label:i18n.__('common.phone'), invalidMsg:i18n.__('infoSite.phoneRequired'),
                          placeholder:i18n.__('common.{{field}}Placeholder',{field:i18n.__('common.phone')}),
                          classes:["form-control"], ids:"", minlength:"10", maxlength:'10',
                          oninput: "this.value = this.value.replace(/[^0-9]/g, ''); validateInput(this)" }) %>



                          <%- include('../../components/input.ejs', inputAttrs={ type: "text" , name:'nationalId',
                            required:true, label:i18n.__('auth.nationalId'),
                            invalidMsg:i18n.__('common.{{field}}Required',{field:i18n.__('auth.nationalId')}) ,
                            placeholder:i18n.__('common.{{field}}Placeholder',{field:i18n.__('auth.nationalId')}),
                            classes:["form-control"], ids:"", minlength:"10", maxlength:'10',
                            oninput: "this.value = this.value.replace(/[^0-9]/g, ''); validateInput(this)" }) %>


                            <%- include('../../components/input.ejs', inputAttrs={ type: "text" , name:'bankName',
                              required:true, label:i18n.__('common.bankName'),
                              invalidMsg:i18n.__('common.{{field}}Required',{field:i18n.__('common.bankName')}) ,
                              placeholder:i18n.__('common.{{field}}Placeholder',{field:i18n.__('common.bankName')}),
                              classes:["form-control"], ids:"", oninput:"validateInput(this)" }) %>


                              <%- include('../../components/input.ejs', inputAttrs={ type: "text" , name:'iban',
                                required:true,
                                invalidMsg:i18n.__('auth.invalidIban') ,
                                placeholder:"SA0380000000608010167519",
                                label:i18n.__('common.ibanNumber'), classes:["form-control"], ids:"",
                                minlength:"24", maxlength:"24",
                                helperText:i18n.__('auth.ibanHelper'),
                                oninput:"this.value = this.value.toUpperCase().replace(/[^A-Z0-9]/g, ''); validateInput(this)" }) %>


                                <%- include('../../components/input.ejs', inputAttrs={ type: "text" ,
                                  name:'accountName', required:true, label:i18n.__('common.accountName'),
                                  invalidMsg:i18n.__('common.{{field}}Required',{field:i18n.__('common.accountName')}) ,
                                  placeholder:i18n.__('common.{{field}}Placeholder',{field:i18n.__('common.accountName')}),
                                  classes:["form-control"], ids:"", oninput:"validateInput(this)" }) %>

                                  <%- include('../../components/input.ejs', inputAttrs={ type: "text" ,
                                    name:'accountNumber', required:true,
                                    invalidMsg:i18n.__('auth.accountNumberMinimum')
                                    ,
                                    placeholder:i18n.__('common.{{field}}Placeholder',{field:i18n.__('common.accountNumber')}),
                                    label:i18n.__('common.accountNumber'), classes:["form-control"], ids:"",
                                    minlength:"10", maxlength:'24',
                                    helperText:i18n.__('auth.accountNumberHelper'),
                                    inputmode:"numeric",
                                    oninput: "this.value = this.value.replace(/[^0-9]/g, ''); validateInput(this)" }) %>




                                    <!-- <div class="row"> -->
                                      <!-- Department -->
                                      <div class="col-md-6 kt-provider-form__field">
                                        <label for="department">
                                          <%= i18n.__('auth.department') %>
                                        </label>
                                        <div class="controls">
                                          <select class="form-control select2" name="department" required>
                                            <option disabled selected value="">
                                              <%= i18n.__('providers.selectDepartement') %>
                                            </option>
                                            <% departments.forEach(department=> { %>
                                              <option value="<%= department._id %>" id="<%= department.slug %>">
                                                <%= department.name[lang] %>
                                              </option>
                                              <% }) %>
                                          </select>
                                          <div class="invalid-feedback">
                                            <%= i18n.__('providers.selectDepartement') %>
                                          </div>
                                        </div>
                                      </div>

                                      <div class="col-md-6 kt-provider-form__field" id="commercial-container"
                                        style="display:none;">
                                        <label for="commercialRegistrationNumber">
                                          <%= i18n.__('auth.commercialRegistrationNumber') %>
                                        </label>
                                        <input type="text" name="commercialRegistrationNumber" class="form-control"
                                          placeholder="<%= i18n.__('common.{{field}}Placeholder', {field: i18n.__('auth.commercialRegistrationNumber')}) %>"
                                          minlength="10" maxlength="10"
                                          oninput="this.value = this.value.replace(/[^0-9]/g, ''); validateInput(this)">
                                        <div class="invalid-feedback">
                                          <%= i18n.__('auth.commercialRegistrationNumber') %>
                                        </div>
                                      </div>


                                    <div class="col-md-6" id="services-container" style="display:none;">
                                      <div class="form-group">
                                        <label for="services">
                                          <%= i18n.__('common.services') %>
                                        </label>
                                        <div class="controls">
                                          <select class="form-control select2" name="services" id="services" multiple
                                            data-placeholder="<%= i18n.__('providers.selectServices') %>">
                                          </select>
                                          <div class="invalid-feedback">
                                            <%= i18n.__('providers.selectServices') %>
                                          </div>
                                        </div>
                                      </div>
                                    </div>

                                    <!-- Container for dynamic prices -->
                                    <div class="row" id="service-prices-container" style="display:none;"></div>



                                    <div class="col-12">
                                      <div class="form-group">
                                        <label for="first-name-column">
                                          <%= i18n.__('common.location') %>
                                        </label>
                                        <div class="controls">

                                          <%- include('../../components/input.ejs', inputAttrs={ type: "hidden" ,
                                            name:"latitude", value:"",classes: "" , ids:["latitude"]}) %>

                                            <%- include('../../components/input.ejs', inputAttrs={type: "hidden"
                                              ,name:"longitude",value:"",classes: "" ,ids:["longitude"]}) %>

                                              <%- include('../../components/input.ejs', inputAttrs={type: "hidden"
                                                ,name:"description",value:"",classes: "" ,ids:["address"]}) %>

                                                <%- include('../../components/input.ejs', inputAttrs={type: "hidden"
                                                  ,name:"showSearch",value:"true",classes: "" ,ids:["showSearch"]}) %>
                                                  <%- include('../../components/input.ejs', inputAttrs={type: "text"
                                                    ,placeholder:i18n.__('common.selectLocation'),classes:
                                                    ["mapControls"],ids:["searchTextField"]}) %>

                                                    <div id="map" class="map-register" style="height: 400px"></div>
                                        </div>
                                      </div>
                                    </div>


                                    <div class="col-12 kt-provider-form__commands">
                                      <button type="submit"
                                        class="btn btn-primary waves-effect waves-light submit_button">
                                        <%= i18n.__('common.add') %>
                                      </button>
                                      <a class="btn btn-label-secondary waves-effect" href="<%=referer%>">
                                        <%= i18n.__('common.referer') %>
                                      </a>
                                    </div>

                  </div>
                </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>
<!-- end content -->

<%- include('./includes.ejs') %>



  <script>

    $('form').on('submit', function (e) {
      const fileInput = $('input[type="file"]');
      const file = fileInput[0].files[0];
      const feedback = fileInput.closest('.image_groub').find('.invalid-feedback');

      if (!file) {
        fileInput.addClass('is-invalid');
        feedback.text("<%= i18n.__('common.pleaseEnterImage') %>").addClass('d-block');
        e.preventDefault();
      }
    });

    window.onload = (event) => {
      getLocation();
    };

    $(document).ready(function () {

      const $commercial = $('input[name="commercialRegistrationNumber"]');
      const $servicesSelect = $('#services');
      const $priceContainer = $('#service-prices-container');

      $('select[name="department"]').on('change', function () {
        const selectedOption = $(this).find('option:selected');
        const selectedSlug = selectedOption.attr('id');
        const selectedId = $(this).val();


        if (selectedSlug === 'advanced-wash' || selectedSlug === 'fixed-laundries') {

          $servicesSelect.attr('required', true);
          $commercial.attr('required', true);

          $('#services-container').show();
          $('#commercial-container').show();
          $priceContainer.show().empty();

          $.ajax({
            url: `/dashboard/providers/services?department=${selectedId}`,
            type: 'GET',
            success: function (data) {
              $servicesSelect.empty();

              $servicesSelect.append('<option disabled>' + '<%= i18n.__("providers.selectServices") %>' + '</option>');
              data.data.forEach(sub => {
                $servicesSelect.append(`<option value="${sub.id}">${sub.name}</option>`);
              });

              $servicesSelect.trigger('change');
            },
            error: function () {}
          });
        } else {
          $('#services-container, #commercial-container, #service-prices-container').hide();
          $servicesSelect.empty();
          $priceContainer.empty();

          $servicesSelect.removeAttr('required');
          $commercial.removeAttr('required');
        }
      });



      $servicesSelect.on('change', function () {
        const selectedServices = $(this).val() || [];
        const selectedOptions = $(this).find('option:selected');

        const existingInputs = {};
        $priceContainer.find('input').each(function () {
          const nameMatch = $(this).attr('name').match(/servicePrices\[(.+)\]/);
          if (nameMatch) {
            existingInputs[nameMatch[1]] = $(this).val();
          }
        });

        $priceContainer.empty();

        selectedOptions.each(function () {
          const serviceId = $(this).val();
          const serviceName = $(this).text();
          const defaultPrice = $(this).data('price') || '';
          const savedValue = existingInputs[serviceId] || defaultPrice;

          $priceContainer.append(`
      <div class="form-group col-md-6">
        <label><%= i18n.__('providers.price') %> (${serviceName})</label>
        <input
          type="number"
          step="0.01"
          min="0.01"
          class="form-control"
          name="servicePrices[${serviceId}]"
          required
          value="${savedValue}"
          placeholder="<%= i18n.__('providers.price') %>"
          oninvalid="this.setCustomValidity('<%= i18n.__('services.priceMustGreaterThan') %>')"
          oninput="this.setCustomValidity('')"
        >
        <div class="invalid-feedback"><%= i18n.__('services.priceMustGreaterThan') %></div>
      </div>
    `);
        });
      });
    });

  </script>
