{% extends '_base.html' %}
{% load static %}

{% block sidebar %}
    {% include 'sidebars/admin.html' %}
{% endblock sidebar %}

{% block navbar %}
    {% include 'navbars/admin.html' %}
{% endblock navbar %}

{% block title %}مدیریت چاه‌ها{% endblock %}

{% block style %}
<!-- DataTables CSS -->
<link rel="stylesheet" href="{% static 'assets/vendor/libs/datatables-bs5/datatables.bootstrap5.css' %}">
<link rel="stylesheet" href="{% static 'assets/vendor/libs/datatables-responsive-bs5/responsive.bootstrap5.css' %}">
<link rel="stylesheet" href="{% static 'assets/vendor/libs/datatables-buttons-bs5/buttons.bootstrap5.css' %}">

<!-- Persian Date Picker CSS -->
<link rel="stylesheet" href="https://unpkg.com/persian-datepicker@latest/dist/css/persian-datepicker.min.css">
{% endblock %}

{% block content %}
<!-- Include Toasts -->
{% include '_toasts.html' %}

<div class="container-xxl flex-grow-1 container-p-y">
  <div class="row py-3 mb-4 card-header flex-column flex-md-row pb-0">
    <div class="d-md-flex justify-content-between align-items-center dt-layout-start col-md-auto me-auto mt-0">
      <h5 class="card-title mb-0 text-md-start text-center fw-bold">لیست چاه‌ها</h5>
    </div>
    <div class="d-md-flex justify-content-between align-items-center dt-layout-end col-md-auto ms-auto mt-0">
      <div class="dt-buttons btn-group flex-wrap mb-0">
        <div class="btn-group">
          <button class="btn buttons-collection btn-label-primary dropdown-toggle me-4" tabindex="0" aria-controls="DataTables_Table_0" type="button" aria-haspopup="dialog" aria-expanded="false">
            <span>
              <span class="d-flex align-items-center gap-2">
                <i class="icon-base bx bx-export me-sm-1"></i>
                <span class="d-none d-sm-inline-block">خروجی</span>
              </span>
            </span>
          </button>
          <button class="btn btn-primary" onclick="prepareAddForm()">
            <i class="bx bx-plus me-1"></i>
            افزودن چاه جدید
          </button>
        </div>
      </div>
    </div>
  </div>

  <div class="card">
    <div class="card-datatable table-responsive">
      <table class="datatables-basic table border-top" id="wells-table">
        <thead>
          <tr>
            <th>ردیف</th>
            <th>شماره اشتراک آب</th>
            <th>نماینده</th>
            <th>شماره اشتراک برق</th>
            <th>شرکت سازنده کنتور</th>
            <th>مختصات UTM</th>
            <th>نامه نمایندگی</th>
            <th>عملیات</th>
          </tr>
        </thead>
        <tbody>
          {% for well in wells %}
          <tr>
            <td>{{ forloop.counter }}</td>
            <td>
              <div class="d-flex justify-content-start align-items-center well-name">
                <div class="d-flex flex-column">
                  <h6 class="mb-0">{{ well.water_subscription_number }}</h6>
                  {% if well.water_meter_serial_number %}
                    <small class="text-muted">سریال: {{ well.water_meter_serial_number }}</small>
                  {% endif %}
                </div>
              </div>
            </td>
            <td>
              {% if well.representative %}
                <div class="d-flex justify-content-start align-items-center">
                  <div class="avatar-wrapper">
                    <div class="avatar me-2">
                      <span class="avatar-initial rounded-circle bg-label-primary">
                      {% if well.representative.profile.pic and well.representative.profile.pic.url %}
                        <img src="{{ well.representative.profile.pic.url }}" alt="Avatar" class="rounded-circle" style="width: 40px; height: 40px; object-fit: cover;">
                      {% else %}
                        {% if well.representative.first_name and well.representative.last_name %}
                          {{ well.representative.first_name|first|upper }}{{ well.representative.last_name|first|upper }}
                        {% elif well.representative.first_name %}
                          {{ well.representative.first_name|first|upper }}
                        {% elif well.representative.last_name %}
                          {{ well.representative.last_name|first|upper }}
                        {% else %}
                          {{ well.representative.username|first|upper }}
                        {% endif %}
                        {% endif %}
                      </span>
                    </div>
                  </div>
                  <div class="d-flex flex-column">
                    <span class="emp_name text-truncate text-heading">{{ well.representative.get_full_name|default:well.representative.username }}</span>
                    <small class="emp_post text-truncate">{{ well.representative.username }}</small>
                  </div>
                </div>
              {% else %}
                <span class="text-muted">-</span>
              {% endif %}
            </td>
            <td>{{ well.electricity_subscription_number|default:"-" }}</td>
            <td>{{ well.water_meter_manufacturer|default:"-" }}</td>
            <td>
              {% if well.utm_x and well.utm_y and well.utm_zone and well.utm_hemisphere %}
                <div class="d-flex flex-column">
                  <small class="text-muted">X: {{ well.utm_x }}</small>
                  <small class="text-muted">Y: {{ well.utm_y }}</small>
                  <small class="text-muted">زون: {{ well.utm_zone }} {{ well.utm_hemisphere }}</small>
                </div>
              {% else %}
                <span class="text-muted">-</span>
              {% endif %}
            </td>
            <td>
              {% if well.representative_letter_file %}
                <a href="{{ well.representative_letter_file.url }}" target="_blank" class="btn btn-sm btn-outline-primary">
                  <i class="bx bx-file me-1"></i>مشاهده
                </a>
              {% else %}
                <span class="text-muted">-</span>
              {% endif %}
            </td>
            <td>
              <div class="d-inline-block">
                <a href="javascript:;" class="btn btn-icon dropdown-toggle hide-arrow" data-bs-toggle="dropdown">
                  <i class="icon-base bx bx-dots-vertical-rounded"></i>
                </a>
                <ul class="dropdown-menu dropdown-menu-end m-0">
                  <li>
                    <a href="#" class="dropdown-item" data-well-id="{{ well.id }}" onclick="viewWell(this.getAttribute('data-well-id'))">
                      <i class="bx bx-show me-1"></i>مشاهده جزئیات
                    </a>
                  </li>
                  <li>
                    <a href="#" class="dropdown-item" data-well-id="{{ well.id }}" onclick="editWell(this.getAttribute('data-well-id'))">
                      <i class="bx bx-edit me-1"></i>ویرایش
                    </a>
                  </li>
                  <div class="dropdown-divider"></div>
                  <li>
                    <a href="#" class="dropdown-item text-danger" data-well-id="{{ well.id }}" data-well-name="{{ well.water_subscription_number }}" onclick="deleteWell(this.getAttribute('data-well-id'), this.getAttribute('data-well-name'))">
                      <i class="bx bx-trash me-1"></i>حذف
                    </a>
                  </li>
                </ul>
              </div>
              <a href="#" class="btn btn-icon item-edit" data-well-id="{{ well.id }}" onclick="editWell(this.getAttribute('data-well-id'))">
                <i class="icon-base bx bx-edit icon-sm"></i>
              </a>
            </td>
          </tr>
          {% empty %}
          <tr>
            <td class="text-center py-4">
              <div class="text-muted">
                <i class="ti ti-database-off ti-lg mb-2"></i>
                <p>چاهی یافت نشد</p>
              </div>
            </td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>
  </div>
</div>

  <!-- فرم افزودن/ویرایش چاه -->
  <div class="offcanvas offcanvas-end" tabindex="-1" id="add-new-record" aria-labelledby="add-new-record">
    <div class="offcanvas-header border-bottom">
      <h5 id="exampleModalLabel" class="offcanvas-title">افزودن چاه جدید</h5>
      <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
    </div>
    <div class="offcanvas-body flex-grow-1">
      <form class="add-new-record pt-0 row g-3" id="form-add-new-record" method="post" enctype="multipart/form-data">
        {% csrf_token %}
        
        <!-- فیلد مخفی برای ID -->
        <input type="hidden" id="well-id" name="well_id" value="">

        <!-- نماینده -->
        <div class="col-sm-12">
          <label class="form-label fw-bold" for="{{ form.representative.id_for_label }}">{{ form.representative.label }}</label>
          <div class="input-group input-group-merge">
            <span class="input-group-text"><i class="bx bx-user"></i></span>
            {{ form.representative }}
          </div>
          {% if form.representative.errors %}
            <div class="invalid-feedback d-block">{{ form.representative.errors.0 }}</div>
          {% endif %}
        </div>

        <!-- معرفی نامه -->
        <div class="col-sm-6">
          <label class="form-label fw-bold" for="id_reference_letter_number">شماره معرفی نامه</label>
          {{ form.reference_letter_number }}
        </div>

        <div class="col-sm-6">
          <label class="form-label fw-bold" for="id_reference_letter_date">تاریخ معرفی نامه</label>
          <input type="text" class="form-control" id="id_reference_letter_date" name="reference_letter_date" placeholder="انتخاب تاریخ" readonly>
        </div>

        <!-- فایل نامه نمایندگی -->
        <div class="col-sm-12">
          <label class="form-label fw-bold" for="id_representative_letter_file">نامه نمایندگی</label>
          {{ form.representative_letter_file }}
          <!-- نمایش فایل موجود -->
          <div id="current-file-display" style="display: none; margin-top: 10px;">
            <div class="alert alert-info d-flex align-items-center justify-content-between">
              <div class="d-flex align-items-center">
                <i class="bx bx-file me-2"></i>
                <span id="current-file-name" class="text-truncate" style="max-width: 200px;" title=""></span>
              </div>
              <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeCurrentFile()">
                <i class="bx bx-trash me-1"></i>حذف
              </button>
            </div>
          </div>
          <input type="hidden" id="remove-file" name="remove_file" value="false">
        </div>

        <!-- شماره اشتراک آب -->
        <div class="col-sm-12">
          <label class="form-label fw-bold" for="{{ form.water_subscription_number.id_for_label }}">{{ form.water_subscription_number.label }}</label>
          <div class="input-group input-group-merge">
            <span class="input-group-text"><i class="bx bx-droplet"></i></span>
            {{ form.water_subscription_number }}
          </div>
          {% if form.water_subscription_number.errors %}
            <div class="invalid-feedback d-block">{{ form.water_subscription_number.errors.0 }}</div>
          {% endif %}
        </div>

        <!-- شماره اشتراک برق -->
        <div class="col-sm-12">
          <label class="form-label fw-bold" for="{{ form.electricity_subscription_number.id_for_label }}">{{ form.electricity_subscription_number.label }}</label>
          <div class="input-group input-group-merge">
            <span class="input-group-text"><i class='bx bx-bolt-circle'></i></span>
            {{ form.electricity_subscription_number }}
          </div>
          {% if form.electricity_subscription_number.errors %}
            <div class="invalid-feedback d-block">{{ form.electricity_subscription_number.errors.0 }}</div>
          {% endif %}
        </div>

        <!-- سریال کنتور آب -->
        <div class="col-sm-12">
          <label class="form-label fw-bold" for="{{ form.water_meter_serial_number.id_for_label }}">{{ form.water_meter_serial_number.label }}</label>
          <div class="input-group input-group-merge">
            <span class="input-group-text"><i class="bx bx-barcode"></i></span>
            {{ form.water_meter_serial_number }}
          </div>
          {% if form.water_meter_serial_number.errors %}
            <div class="invalid-feedback d-block">{{ form.water_meter_serial_number.errors.0 }}</div>
          {% endif %}
        </div>

        <!-- سریال کنتور قدیمی آب -->
        <div class="col-sm-12">
          <label class="form-label fw-bold" for="{{ form.water_meter_old_serial_number.id_for_label }}">{{ form.water_meter_old_serial_number.label }}</label>
          <div class="input-group input-group-merge">
            <span class="input-group-text"><i class="bx bx-barcode"></i></span>
            {{ form.water_meter_old_serial_number }}
          </div>
          {% if form.water_meter_old_serial_number.errors %}
            <div class="invalid-feedback d-block">{{ form.water_meter_old_serial_number.errors.0 }}</div>
          {% endif %}
        </div>

        <!-- شرکت سازنده کنتور آب با دکمه افزودن -->
        <div class="col-sm-12">
          <label class="form-label fw-bold" for="id_water_meter_manufacturer">شرکت سازنده کنتور آب</label>
          <div class="input-group">
            {{ form.water_meter_manufacturer }}
            <button class="btn btn-outline-primary" type="button" onclick="toggleNewManufacturer()">
              <i class="icon-base bx bx-plus"></i>
            </button>
          </div>
          <!-- فیلد افزودن شرکت جدید -->
          <div id="new-manufacturer-field" style="display: none; margin-top: 10px;">
            {{ form.new_manufacturer }}
          </div>
        </div>

        <!-- مختصات UTM -->
        <div class="col-sm-6">
          <label class="form-label fw-bold" for="id_utm_x">X UTM</label>
          {{ form.utm_x }}
        </div>

        <div class="col-sm-6">
          <label class="form-label fw-bold" for="id_utm_y">Y UTM</label>
          {{ form.utm_y }}
        </div>

        <div class="col-sm-6">
          <label class="form-label fw-bold" for="id_utm_zone">زون UTM</label>
          {{ form.utm_zone }}
        </div>

        <div class="col-sm-6">
          <label class="form-label fw-bold" for="id_utm_hemisphere">نیمکره UTM</label>
          {{ form.utm_hemisphere }}
        </div>

        <!-- قدرت چاه -->
        <div class="col-sm-12">
          <label class="form-label fw-bold" for="id_well_power">قدرت چاه</label>
          {{ form.well_power }}
        </div>

        <!-- دکمه‌های عملیات -->
        <div class="col-sm-12">
          <button type="submit" class="btn btn-primary data-submit me-sm-4 me-1">ذخیره</button>
          <button type="reset" class="btn btn-outline-secondary" data-bs-dismiss="offcanvas">انصراف</button>
        </div>
      </form>
    </div>
  </div>

  <!-- Well Details Modal -->
  <div class="modal fade" id="wellDetailsModal" tabindex="-1" aria-labelledby="wellDetailsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="wellDetailsModalLabel">جزئیات چاه</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <div id="well-details-loading" class="text-center py-4" style="display:none;">
            <div class="spinner-border" role="status"></div>
            <div class="mt-2">در حال بارگذاری...</div>
          </div>

          <div id="well-details-content" style="display:none;">
            <div class="card mb-4">
              <div class="card-body">
                <h6 class="fw-bold mb-3 text-primary">مشخصات چاه</h6>
                <div class="row">
                  <div class="col-md-6">
                    <table class="table table-borderless table-sm mb-0">
                      <tbody>
                        <tr>
                          <td class="text-muted" style="width: 40%;"><i class="bx bx-droplet me-1"></i>شماره اشتراک آب</td>
                          <td><strong id="wd-water-sub">-</strong></td>
                        </tr>
                        <tr>
                          <td class="text-muted"><i class='bx bx-bolt-circle me-1'></i>شماره اشتراک برق</td>
                          <td><strong id="wd-elec-sub">-</strong></td>
                        </tr>
                        <tr>
                          <td class="text-muted"><i class="bx bx-user me-1"></i>نماینده</td>
                          <td><strong id="wd-rep">-</strong></td>
                        </tr>
                        <tr>
                          <td class="text-muted"><i class="bx bx-briefcase me-1"></i>کارگزار</td>
                          <td><strong id="wd-broker">-</strong></td>
                        </tr>
                        <tr>
                          <td class="text-muted"><i class="bx bx-buildings me-1"></i>امور</td>
                          <td><strong id="wd-affairs">-</strong></td>
                        </tr>
                        <tr>
                          <td class="text-muted"><i class="bx bx-map me-1"></i>شهرستان</td>
                          <td><strong id="wd-county">-</strong></td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                  <div class="col-md-6">
                    <table class="table table-borderless table-sm mb-0">
                      <tbody>
                        <tr>
                          <td class="text-muted" style="width: 40%;"><i class="bx bx-barcode me-1"></i>سریال کنتور</td>
                          <td><strong id="wd-meter-serial">-</strong></td>
                        </tr>
                        <tr>
                          <td class="text-muted"><i class="bx bx-barcode me-1"></i>سریال قدیمی</td>
                          <td><strong id="wd-meter-serial-old">-</strong></td>
                        </tr>
                        <tr>
                          <td class="text-muted"><i class="bx bx-factory me-1"></i>شرکت سازنده</td>
                          <td><strong id="wd-meter-maker">-</strong></td>
                        </tr>
                        <tr>
                          <td class="text-muted"><i class="bx bx-tachometer me-1"></i>قدرت چاه</td>
                          <td><strong id="wd-power">-</strong></td>
                        </tr>
                        <tr>
                          <td class="text-muted"><i class="bx bx-current-location me-1"></i>مختصات</td>
                          <td>
                            <div><small class="text-muted">X:</small> <span id="wd-utm-x">-</span></div>
                            <div><small class="text-muted">Y:</small> <span id="wd-utm-y">-</span></div>
                            <div><small class="text-muted">زون:</small> <span id="wd-utm-zone">-</span> <span id="wd-utm-hem">-</span></div>
                            <div id="wd-latlon-row" style="display:none;"><small class="text-muted">Lat/Lon:</small> <span id="wd-latlon">-</span></div>
                          </td>
                        </tr>
                        <tr>
                          <td class="text-muted"><i class="bx bx-file me-1"></i>نامه نمایندگی</td>
                          <td>
                            <a id="wd-letter-link" href="#" target="_blank" class="btn btn-sm btn-outline-primary" style="display:none;"><i class="bx bx-file me-1"></i>مشاهده</a>
                            <span id="wd-letter-missing" class="text-muted">-</span>
                          </td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
            </div>

            <div class="card">
              <div class="card-header d-flex justify-content-between align-items-center">
                <h6 class="mb-0 fw-bold">سوابق درخواست‌ها
                  <span class="badge bg-label-primary" id="wd-req-count">0</span>
                </h6>
               
              </div>
              <div class="card-body p-0">
                <div class="table-responsive">
                  <table class="table table-striped mb-0">
                    <thead>
                      <tr>
                        <th>کد</th>
                        <th>فرآیند</th>
                        <th>مرحله فعلی</th>
                        <th>وضعیت</th>
                        <th>نماینده</th>
                        <th>تاریخ ایجاد</th>
                        <th></th>
                      </tr>
                    </thead>
                    <tbody id="wd-requests-body">
                      <tr><td class="text-center py-3" colspan="7"><span class="text-muted">رکوردی یافت نشد</span></td></tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">بستن</button>
        </div>
      </div>
    </div>
  </div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-labelledby="deleteConfirmModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="deleteConfirmModalLabel">تایید حذف</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <p id="deleteConfirmText">آیا از حذف این چاه اطمینان دارید؟</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">انصراف</button>
        <button type="button" class="btn btn-danger" id="confirmDeleteBtn">حذف</button>
      </div>
    </div>
  </div>
</div>

{% endblock %}

{% block script %}
<!-- DataTables JS -->
<script src="{% static 'assets/vendor/libs/datatables-bs5/datatables-bootstrap5.js' %}"></script>
<!-- Persian DataTable Language -->
<script src="{% static 'assets/js/persian-datatable.js' %}"></script>

<!-- Persian Date Picker JS -->
<script src="https://unpkg.com/persian-date@latest/dist/persian-date.min.js"></script>
<script src="https://unpkg.com/persian-datepicker@latest/dist/js/persian-datepicker.min.js"></script>

<script>
  // متغیرهای جهانی
  let currentWellId = null;
  let isEditMode = false;

  $(document).ready(function() {
    // Initialize DataTable
    $('#wells-table').DataTable({
      pageLength: 10,
      lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "همه"]],
      order: [[0, 'asc']],
      responsive: true,
    });

    // Initialize Persian Date Picker with delay to ensure libraries are loaded
    setTimeout(function() {
      if ($.fn.persianDatepicker) {
        $('#id_reference_letter_date').persianDatepicker({
          format: 'YYYY/MM/DD',
          initialValue: false,
          autoClose: true,
          persianDigit: false,
          observer: true,
          calendar: {
            persian: {
              locale: 'fa',
              leapYearMode: 'astronomical'
            }
          },
          onSelect: function(unix) {
            // تبدیل تاریخ شمسی به میلادی برای ارسال به سرور
            const gregorianDate = new Date(unix);
            const year = gregorianDate.getFullYear();
            const month = String(gregorianDate.getMonth() + 1).padStart(2, '0');
            const day = String(gregorianDate.getDate()).padStart(2, '0');
            const gregorianDateString = `${year}-${month}-${day}`;
            
            // نمایش تاریخ شمسی در فیلد
            if (window.persianDate) {
              const persianDate = new window.persianDate(unix);
              const persianDateString = persianDate.format('YYYY/MM/DD');
              $('#id_reference_letter_date').val(persianDateString);
            } else {
              // اگر persianDate در دسترس نبود، تاریخ میلادی را نمایش بده
              $('#id_reference_letter_date').val(gregorianDateString);
            }
            
            // ذخیره تاریخ میلادی در فیلد مخفی برای ارسال به سرور
            $('#id_reference_letter_date').attr('data-gregorian', gregorianDateString);
          }
        });
      }
    }, 100);

    // Handle form submission
    $('#form-add-new-record').on('submit', function(e) {
      e.preventDefault();
      
      const form = this;
      const formData = new FormData(form);
      const wellId = $('#well-id').val();
      
      // تبدیل تاریخ شمسی به میلادی برای ارسال
      const persianDateValue = $('#id_reference_letter_date').val();
      const gregorianDateValue = $('#id_reference_letter_date').attr('data-gregorian');
      if (persianDateValue && gregorianDateValue) {
        formData.set('reference_letter_date', gregorianDateValue);
      }
      
      // Determine URL based on whether we're editing or adding
      const url = wellId ? '{% url "wells:edit_well_ajax" 0 %}'.replace('0', wellId) : '{% url "wells:add_well_ajax" %}';
      
      // Show loading state
      const submitBtn = $(form).find('button[type="submit"]');
      const originalText = submitBtn.text();
      submitBtn.prop('disabled', true).text('در حال ذخیره...');
      
      $.ajax({
        url: url,
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
          if (response.success) {
            // Show success message
            showToast(response.message, 'success');
            
            // Close offcanvas and reset form
            $('#add-new-record').offcanvas('hide');
            form.reset();
            
            // Reload page to show new well
            setTimeout(function() {
              location.reload();
            }, 1500);
          } else {
            // Show error message
            showToast(response.message, 'danger');
            
            // Show form errors if any
            if (response.errors) {
              Object.keys(response.errors).forEach(function(field) {
                const errorMsg = response.errors[field][0];
                const fieldElement = $('[name="' + field + '"]');
                fieldElement.addClass('is-invalid');
                fieldElement.siblings('.invalid-feedback').remove();
                fieldElement.after('<div class="invalid-feedback d-block">' + errorMsg + '</div>');
              });
            }
          }
        },
        error: function(xhr, status, error) {
          showToast('خطا در ارتباط با سرور', 'danger');
        },
        complete: function() {
          // Reset button state
          submitBtn.prop('disabled', false).text(originalText);
        }
      });
    });

    // Reset form when offcanvas is hidden
    $('#add-new-record').on('hidden.bs.offcanvas', function() {
      const form = $('#form-add-new-record')[0];
      form.reset();
      
      // Reset form for adding new well
    currentWellId = null;
    isEditMode = false;
      $('#well-id').val('');
      $('#exampleModalLabel').text('افزودن چاه جدید');
      $('.data-submit').text('ذخیره');
      
      // Hide new manufacturer field
    document.getElementById('new-manufacturer-field').style.display = 'none';
    document.getElementById('id_new_manufacturer').style.display = 'none';
      
                // Reset file display
      document.getElementById('current-file-display').style.display = 'none';
      document.getElementById('id_representative_letter_file').style.display = 'block';
      document.getElementById('remove-file').value = 'false';
      
                      // Reset date picker
      $('#id_reference_letter_date').val('');
      $('#id_reference_letter_date').removeAttr('data-gregorian');
      
      // Clear validation errors
      $('.is-invalid').removeClass('is-invalid');
      $('.invalid-feedback').remove();
    });

    // Clear validation errors when user starts typing
    $('input, textarea, select').on('input change', function() {
      $(this).removeClass('is-invalid');
      $(this).siblings('.invalid-feedback').remove();
    });

    // مدیریت انتخاب فایل جدید
    $('#id_representative_letter_file').on('change', function() {
      if (this.files && this.files.length > 0) {
        // اگر فایل جدید انتخاب شده، حذف فایل قبلی را لغو کن
        document.getElementById('remove-file').value = 'false';
        // مخفی کردن نمایش فایل موجود
        document.getElementById('current-file-display').style.display = 'none';
      }
    });
  });

  // toggle برای فیلد شرکت سازنده جدید
  function toggleNewManufacturer() {
    const newField = document.getElementById('new-manufacturer-field');
    const newInput = document.getElementById('id_new_manufacturer');
    
    if (newField.style.display === 'none') {
      newField.style.display = 'block';
      newInput.style.display = 'block';
      newInput.focus();
    } else {
      newField.style.display = 'none';
      newInput.style.display = 'none';
      newInput.value = '';
    }
  }

  // Well functions
  function viewWell(id) {
    currentWellId = id;
    const modalEl = document.getElementById('wellDetailsModal');
    const modal = new bootstrap.Modal(modalEl);
    // reset content
    $('#well-details-content').hide();
    $('#well-details-loading').show();
    $('#wd-requests-body').html('<tr><td class="text-center py-3" colspan="7"><span class="text-muted">در حال بارگذاری...</span></td></tr>');
    $('#wd-req-count').text('0');
    $('#wd-letter-link').hide();
    $('#wd-letter-missing').show();
    modal.show();

    // Fetch well details
    $.get('{% url "wells:get_well_details" 0 %}'.replace('0', id))
      .done(function(resp){
        if (!resp.success) { showToast('خطا در دریافت جزئیات چاه', 'danger'); return; }
        const w = resp.well;
        $('#wellDetailsModalLabel').text('جزئیات چاه ' + (w.water_subscription_number || ''));
        $('#wd-water-sub').text(w.water_subscription_number || '-');
        $('#wd-elec-sub').text(w.electricity_subscription_number || '-');
        $('#wd-rep').text((w.representative && (w.representative.full_name || w.representative.username)) || '-');
        $('#wd-broker').text(w.broker || '-');
        $('#wd-affairs').text(w.affairs || '-');
        $('#wd-county').text(w.county || '-');
        $('#wd-meter-serial').text(w.water_meter_serial_number || '-');
        $('#wd-meter-serial-old').text(w.water_meter_old_serial_number || '-');
        $('#wd-meter-maker').text(w.water_meter_manufacturer || '-');
        $('#wd-power').text(w.well_power || '-');
        $('#wd-utm-x').text((w.utm && w.utm.x) || '-');
        $('#wd-utm-y').text((w.utm && w.utm.y) || '-');
        $('#wd-utm-zone').text((w.utm && w.utm.zone) || '-');
        $('#wd-utm-hem').text((w.utm && w.utm.hemisphere) || '-');
        if (w.lat_long && w.lat_long.lat !== undefined) {
          $('#wd-latlon').text(w.lat_long.lat + ', ' + w.lat_long.lon);
          $('#wd-latlon-row').show();
        } else {
          $('#wd-latlon-row').hide();
        }
        if (w.representative_letter_file_url) {
          $('#wd-letter-link').attr('href', w.representative_letter_file_url).show();
          $('#wd-letter-missing').hide();
        }
        $('#wd-req-count').text(resp.total_requests || '0');
        $('#well-details-loading').hide();
        $('#well-details-content').show();
      })
      .fail(function(){ showToast('خطا در ارتباط با سرور', 'danger'); $('#well-details-loading').hide(); });

    // Fetch requests
    $.get('{% url "wells:get_well_requests" 0 %}'.replace('0', id))
      .done(function(resp){
        if (!resp.success) { $('#wd-requests-body').html('<tr><td class="text-center py-3" colspan="7"><span class="text-danger">خطا در بارگذاری سوابق</span></td></tr>'); return; }
        const rows = (resp.requests || []).map(function(r){
          const status = r.status_display || r.status;
          const step = r.current_step || '-';
          const href = r.url || '#';
          const rep = r.representative || '-';
          return '<tr>'+
            '<td>'+ (r.code || '-') +'</td>'+
            '<td>'+ (r.process || '-') +'</td>'+
            '<td>'+ step +'</td>'+
            '<td>'+ status +'</td>'+
            '<td>'+ rep +'</td>'+
            '<td>'+ (r.created || '-') +'</td>'+
            '<td><a class="btn btn-sm btn-outline-primary" href="'+ href +'" target="_blank">جزئیات</a></td>'+
          '</tr>';
        });
        if (!rows.length) {
          $('#wd-requests-body').html('<tr><td class="text-center py-3" colspan="7"><span class="text-muted">رکوردی یافت نشد</span></td></tr>');
        } else {
          $('#wd-requests-body').html(rows.join(''));
        }
      })
      .fail(function(){ $('#wd-requests-body').html('<tr><td class="text-center py-3" colspan="7"><span class="text-danger">خطا در بارگذاری سوابق</span></td></tr>'); });
  }

  // حذف فایل موجود
  function removeCurrentFile() {
    document.getElementById('current-file-display').style.display = 'none';
    document.getElementById('remove-file').value = 'true';
    document.getElementById('id_representative_letter_file').style.display = 'block';
    // Reset فیلد فایل
    document.getElementById('id_representative_letter_file').value = '';
  }
  
  function editWell(id) {
    // Load well data and open edit form
    $.ajax({
      url: '{% url "wells:get_well_data" 0 %}'.replace('0', id),
      type: 'GET',
      success: function(response) {
        if (response.success) {
          const well = response.well;
          
          // Fill form with well data
          const fieldsMap = {
            'well-id': well.id,
            'id_representative': well.representative,
            'id_water_subscription_number': well.water_subscription_number,
            'id_electricity_subscription_number': well.electricity_subscription_number,
            'id_water_meter_serial_number': well.water_meter_serial_number,
            'id_water_meter_old_serial_number': well.water_meter_old_serial_number,
            'id_water_meter_manufacturer': well.water_meter_manufacturer,
            'id_utm_x': well.utm_x,
            'id_utm_y': well.utm_y,
            'id_utm_zone': well.utm_zone,
            'id_utm_hemisphere': well.utm_hemisphere,
            'id_well_power': well.well_power,
            'id_reference_letter_number': well.reference_letter_number,
            'id_reference_letter_date': well.reference_letter_date
          };
          
          // Loop through fields for easier maintenance
          Object.keys(fieldsMap).forEach(function(fieldId) {
            $('#' + fieldId).val(fieldsMap[fieldId] || '');
          });
          
          // تبدیل تاریخ میلادی به شمسی برای نمایش
          if (well.reference_letter_date) {
            try {
              if (window.persianDate) {
                const gregorianDate = new Date(well.reference_letter_date);
                const persianDateObj = new window.persianDate(gregorianDate);
                const persianDateString = persianDateObj.format('YYYY/MM/DD');
                $('#id_reference_letter_date').val(persianDateString);
              } else {
                // اگر persianDate در دسترس نبود، تاریخ میلادی را نمایش بده
                $('#id_reference_letter_date').val(well.reference_letter_date);
              }
              // ذخیره تاریخ میلادی در data attribute
              $('#id_reference_letter_date').attr('data-gregorian', well.reference_letter_date);
            } catch (error) {
              // اگر تبدیل نشد، تاریخ میلادی را نمایش بده
              $('#id_reference_letter_date').val(well.reference_letter_date);
            }
          }
          
          // نمایش فایل موجود اگر وجود داشته باشد
          if (well.representative_letter_file_url) {
            document.getElementById('current-file-display').style.display = 'block';
            const fileName = well.representative_letter_file_name || 'فایل موجود';
            document.getElementById('current-file-name').textContent = fileName;
            document.getElementById('current-file-name').title = fileName; // برای tooltip
            document.getElementById('id_representative_letter_file').style.display = 'none';
            document.getElementById('remove-file').value = 'false';
          } else {
            document.getElementById('current-file-display').style.display = 'none';
            document.getElementById('id_representative_letter_file').style.display = 'block';
            document.getElementById('remove-file').value = 'false';
          }
          
          // Update modal title and button
          $('#exampleModalLabel').text('ویرایش چاه');
          $('.data-submit').text('ویرایش');
          
          // Open modal
          $('#add-new-record').offcanvas('show');
        } else {
          showToast('خطا در بارگذاری اطلاعات چاه', 'danger');
        }
      },
      error: function() {
        showToast('خطا در ارتباط با سرور', 'danger');
      }
    });
  }

  function deleteWell(id, waterSubscriptionNumber) {
    // Set modal content
    document.getElementById('deleteConfirmText').textContent = `آیا از حذف چاه ${waterSubscriptionNumber} اطمینان دارید؟`;
    
    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('deleteConfirmModal'));
    modal.show();
    
    // Handle confirm button click
    document.getElementById('confirmDeleteBtn').onclick = function() {
      $.ajax({
        url: '{% url "wells:delete_well" 0 %}'.replace('0', id),
        type: 'POST',
        data: {
          'csrfmiddlewaretoken': $('[name=csrfmiddlewaretoken]').val()
        },
        success: function(response) {
          if (response.success) {
            showToast(response.message, 'success');
            modal.hide();
            setTimeout(() => {
              window.location.reload();
            }, 1500);
          } else {
            showToast(response.message, 'danger');
          }
        },
        error: function() {
          showToast('خطا در ارتباط با سرور', 'danger');
        }
      });
    };
  }
  
  function prepareAddForm() {
    // Reset form for adding new well
    const form = $('#form-add-new-record')[0];
    form.reset();
    currentWellId = null;
    isEditMode = false;
    $('#well-id').val('');
    $('#exampleModalLabel').text('افزودن چاه جدید');
    $('.data-submit').text('ذخیره');
    
    // Hide new manufacturer field
    document.getElementById('new-manufacturer-field').style.display = 'none';
    document.getElementById('id_new_manufacturer').style.display = 'none';
    
    // Reset file display
    document.getElementById('current-file-display').style.display = 'none';
    document.getElementById('id_representative_letter_file').style.display = 'block';
    document.getElementById('remove-file').value = 'false';
    
    // Clear validation errors
    $('.is-invalid').removeClass('is-invalid');
    $('.invalid-feedback').remove();
    
    // Open modal
    $('#add-new-record').offcanvas('show');
  }
</script>
{% endblock %}
