{% 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' %}">

{% 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="customers-table">
        <thead>
          <tr>
            <th>ردیف</th>
            <th>کاربر</th>
            <th>نوع کاربر</th>
            <th>کد ملی</th>
            <th>تلفن</th>
            <th>آدرس</th>
            <th>بانک</th>
            <th>وضعیت</th>
            <th>عملیات</th>
          </tr>
        </thead>
        <tbody>
          {% for customer in customers %}
          <tr>
            <td>{{forloop.counter}}</td>
            <td>
              <div class="d-flex justify-content-start align-items-center user-name">
                <div class="avatar-wrapper">
                  <div class="avatar me-2">
                    {% if customer.pic and customer.pic.url %}
                      <img src="{{ customer.pic.url }}" alt="Avatar" class="rounded-circle" style="width: 40px; height: 40px; object-fit: cover;">
                    {% else %}
                      <span class="avatar-initial rounded-circle bg-label-primary">
                        {% if customer.user.first_name and customer.user.last_name %}
                          {{ customer.user.first_name|first|upper }}{{ customer.user.last_name|first|upper }}
                        {% elif customer.user.first_name %}
                          {{ customer.user.first_name|first|upper }}
                        {% elif customer.user.last_name %}
                          {{ customer.user.last_name|first|upper }}
                        {% else %}
                          {{ customer.user.username|first|upper }}
                        {% endif %}
                      </span>
                    {% endif %}
                  </div>
                </div>
                <div class="d-flex flex-column">
                  <span class="emp_name text-truncate text-heading">{{ customer.user.get_full_name|default:customer.user.username }}</span>
                  <small class="emp_post text-truncate">{{ customer.user.username }}</small>
                </div>
              </div>
            </td>
            <td>
              {% if customer.user_type == 'legal' %}
                <span class="badge bg-label-info">
                  <i class="bx bx-buildings me-1"></i>حقوقی
                </span>
                <div class="mt-1">
                  {% if customer.company_name %}
                    <small class="text-muted d-block">{{ customer.company_name|truncatechars:25 }}</small>
                  {% endif %}
                  {% if customer.company_national_id %}
                    <small class="text-muted d-block">
                      <i class="bx bx-id-card me-1"></i>{{ customer.company_national_id }}
                    </small>
                  {% endif %}
                </div>
              {% else %}
                <span class="badge bg-label-primary">
                  <i class="bx bx-user me-1"></i>حقیقی
                </span>
              {% endif %}
            </td>
            <td>{{ customer.national_code|default:"کد ملی ثبت نشده" }}</td>
            <td>
              <div class="d-flex flex-column">
                {% if customer.phone_number_1 %}
                  <span class="fw-medium">{{ customer.phone_number_1 }}</span>
                {% endif %}
                {% if customer.phone_number_2 %}
                  <small class="text-muted">{{ customer.phone_number_2 }}</small>
                {% endif %}
                {% if not customer.phone_number_1 and not customer.phone_number_2 %}
                  <span class="text-muted">تلفن ثبت نشده</span>
                {% endif %}
              </div>
            </td>
            <td>
              {% if customer.address %}
                <span class="text-truncate d-inline-block" style="max-width: 200px;" title="{{ customer.address }}">
                  {{ customer.address|truncatechars:50 }}
                </span>
              {% else %}
                <span class="text-muted">آدرس ثبت نشده</span>
              {% endif %}
            </td>
            <td>
              <div class="d-flex flex-column">
                {% if customer.bank_name %}
                  <span class="fw-medium">{{ customer.get_bank_name_display }}</span>
                  <span class="text-muted">{{ customer.card_number }}</span>
                  <span class="text-muted">{{ customer.account_number }}</span>
                {% else %}
                  <span class="text-muted">بانک ثبت نشده</span>
                {% endif %}
              </div>
            </td>
            <td>
              {% if customer.is_completed %}
                <span class="badge bg-label-success">تکمیل شده</span>
              {% else %}
                <span class="badge bg-label-warning">ناقص</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-customer-id="{{ customer.id }}" onclick="viewCustomer(this.getAttribute('data-customer-id'))">
                      <i class="bx bx-show me-1"></i>مشاهده جزئیات
                    </a>
                  </li>
                  <li>
                    <a href="#" class="dropdown-item" data-customer-id="{{ customer.id }}" onclick="editCustomer(this.getAttribute('data-customer-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-customer-id="{{ customer.id }}" data-customer-name="{{ customer.user.get_full_name|default:customer.user.username }}" onclick="deleteCustomer(this.getAttribute('data-customer-id'), this.getAttribute('data-customer-name'))">
                      <i class="bx bx-trash me-1"></i>حذف
                    </a>
                  </li>
                </ul>
              </div>
              <a href="#" class="btn btn-icon item-edit" data-customer-id="{{ customer.id }}" onclick="editCustomer(this.getAttribute('data-customer-id'))">
                <i class="icon-base bx bx-edit icon-sm"></i>
              </a>
            </td>
          </tr>
                      {% empty %}
            <tr>
              <td class="text-center py-4">
                <div class="d-flex flex-column align-items-center">
                  <i class="bx bx-user-x bx-lg text-muted mb-2"></i>
                  <span class="text-muted">هیچ کاربری یافت نشد</span>
                </div>
              </td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            {% endfor %}
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- Modal to add/edit record -->
<div class="offcanvas offcanvas-end" id="add-new-record">
  <div class="offcanvas-header border-bottom">
    <h5 class="offcanvas-title" id="exampleModalLabel">افزودن کاربر جدید</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-2" id="form-add-new-record" method="post" enctype="multipart/form-data">
      {% csrf_token %}
      <input type="hidden" id="customer-id" name="customer_id" value="">
      
      <!-- User Information -->
      <div class="col-sm-12">
        <label class="form-label fw-bold" for="{{ form.user_type.id_for_label }}">{{ form.user_type.label }}</label>
        <div class="input-group input-group-merge">
          <span class="input-group-text"><i class="bx bx-user-circle"></i></span>
          {{ form.user_type }}
        </div>
        {% if form.user_type.errors %}
          <div class="invalid-feedback d-block">{{ form.user_type.errors.0 }}</div>
        {% endif %}
      </div>
     
      <div class="col-sm-6">
        <label class="form-label fw-bold" for="{{ form.first_name.id_for_label }}">{{ form.first_name.label }}</label>
        <div class="input-group input-group-merge">
          <span class="input-group-text"><i class="bx bx-user"></i></span>
          {{ form.first_name }}
        </div>
        {% if form.first_name.errors %}
          <div class="invalid-feedback d-block">{{ form.first_name.errors.0 }}</div>
        {% endif %}
      </div>
      
      <div class="col-sm-6">
        <label class="form-label fw-bold" for="{{ form.last_name.id_for_label }}">{{ form.last_name.label }}</label>
        <div class="input-group input-group-merge">
          <span class="input-group-text"><i class="bx bx-user"></i></span>
          {{ form.last_name }}
        </div>
        {% if form.last_name.errors %}
          <div class="invalid-feedback d-block">{{ form.last_name.errors.0 }}</div>
        {% endif %}
      </div>
      
      <div class="col-sm-6">
        <label class="form-label fw-bold" for="{{ form.phone_number_1.id_for_label }}">{{ form.phone_number_1.label }}</label>
        <div class="input-group input-group-merge">
          <span class="input-group-text"><i class="bx bx-phone"></i></span>
          {{ form.phone_number_1 }}
        </div>
        {% if form.phone_number_1.errors %}
          <div class="invalid-feedback d-block">{{ form.phone_number_1.errors.0 }}</div>
        {% endif %}
      </div>
      
      <div class="col-sm-6">
        <label class="form-label fw-bold" for="{{ form.phone_number_2.id_for_label }}">{{ form.phone_number_2.label }}</label>
        <div class="input-group input-group-merge">
          <span class="input-group-text"><i class="bx bx-phone"></i></span>
          {{ form.phone_number_2 }}
        </div>
        {% if form.phone_number_2.errors %}
          <div class="invalid-feedback d-block">{{ form.phone_number_2.errors.0 }}</div>
        {% endif %}
      </div>
      
      <div class="col-sm-12">
        <label class="form-label fw-bold" for="{{ form.national_code.id_for_label }}">{{ form.national_code.label }}</label>
        <div class="input-group input-group-merge">
          <span class="input-group-text"><i class="bx bx-id-card"></i></span>
          {{ form.national_code }}
        </div>
        {% if form.national_code.errors %}
          <div class="invalid-feedback d-block">{{ form.national_code.errors.0 }}</div>
        {% endif %}
      </div>

      <!-- Company Information (for legal entities) -->
      <div class="col-sm-12 company-fields" style="display: none;">
        <label class="form-label fw-bold" for="{{ form.company_name.id_for_label }}">{{ form.company_name.label }}</label>
        <div class="input-group input-group-merge">
          <span class="input-group-text"><i class="bx bx-buildings"></i></span>
          {{ form.company_name }}
        </div>
        {% if form.company_name.errors %}
          <div class="invalid-feedback d-block">{{ form.company_name.errors.0 }}</div>
        {% endif %}
      </div>
      
      <div class="col-sm-12 company-fields" style="display: none;">
        <label class="form-label fw-bold" for="{{ form.company_national_id.id_for_label }}">{{ form.company_national_id.label }}</label>
        <div class="input-group input-group-merge">
          <span class="input-group-text"><i class="bx bx-id-card"></i></span>
          {{ form.company_national_id }}
        </div>
        {% if form.company_national_id.errors %}
          <div class="invalid-feedback d-block">{{ form.company_national_id.errors.0 }}</div>
        {% endif %}
      </div>

      <div class="col-sm-12">
        <label class="form-label fw-bold" for="{{ form.bank_name.id_for_label }}">{{ form.bank_name.label }}</label>
        <div class="input-group input-group-merge">
          <span class="input-group-text"><i class="bx bx-credit-card"></i></span>
          {{ form.bank_name }}
        </div>
        {% if form.bank_name.errors %}
          <div class="invalid-feedback d-block">{{ form.bank_name.errors.0 }}</div>
        {% endif %}
      </div>
      
      <div class="col-sm-12">
        <label class="form-label fw-bold" for="{{ form.card_number.id_for_label }}">{{ form.card_number.label }}</label>
        <div class="input-group input-group-merge">
          <span class="input-group-text"><i class="bx bx-credit-card"></i></span>
          {{ form.card_number }}
        </div>
        {% if form.card_number.errors %}
          <div class="invalid-feedback d-block">{{ form.card_number.errors.0 }}</div>
        {% endif %}
      </div>
      
      <div class="col-sm-12">
        <label class="form-label fw-bold" for="{{ form.account_number.id_for_label }}">{{ form.account_number.label }}</label>
        <div class="input-group input-group-merge">
          <span class="input-group-text"><i class="bx bx-credit-card"></i></span>
          {{ form.account_number }}
        </div>
        {% if form.account_number.errors %}
          <div class="invalid-feedback d-block">{{ form.account_number.errors.0 }}</div>
        {% endif %}
      </div>
      
      <div class="col-sm-12">
        <label class="form-label fw-bold" for="{{ form.address.id_for_label }}">{{ form.address.label }}</label>
        <div class="input-group input-group-merge">
          <span class="input-group-text"><i class="bx bx-map"></i></span>
          {{ form.address }}
        </div>
        {% if form.address.errors %}
          <div class="invalid-feedback d-block">{{ form.address.errors.0 }}</div>
        {% endif %}
      </div>
      
      <div class="col-sm-12">
        <button type="submit" class="btn btn-primary data-submit me-sm-3 me-1">ذخیره</button>
        <button type="reset" class="btn btn-outline-secondary" data-bs-dismiss="offcanvas">انصراف</button>
      </div>
    </form>
  </div>
</div>

<!-- Customer Details Modal -->
<div class="modal fade" id="customerDetailsModal" tabindex="-1" aria-labelledby="customerDetailsModalLabel" 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="customerDetailsModalLabel">جزئیات مشترک</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div id="customer-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="customer-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-user me-1"></i>نام کاربری</td>
                        <td><strong id="cd-username">-</strong></td>
                      </tr>
                      <tr>
                        <td class="text-muted"><i class="bx bx-id-card me-1"></i>نام و نام خانوادگی</td>
                        <td><strong id="cd-fullname">-</strong></td>
                      </tr>
                      <tr>
                        <td class="text-muted"><i class="bx bx-fingerprint me-1"></i>کد ملی</td>
                        <td><strong id="cd-national-code">-</strong></td>
                      </tr>
                      <tr>
                        <td class="text-muted"><i class="bx bx-user-circle me-1"></i>نوع کاربر</td>
                        <td><strong id="cd-user-type">-</strong></td>
                      </tr>
                      <tr id="cd-company-name-row" style="display: none;">
                        <td class="text-muted"><i class="bx bx-buildings me-1"></i>نام شرکت</td>
                        <td><strong id="cd-company-name">-</strong></td>
                      </tr>
                      <tr id="cd-company-id-row" style="display: none;">
                        <td class="text-muted"><i class="bx bx-id-card me-1"></i>شناسه ملی شرکت</td>
                        <td><strong id="cd-company-id">-</strong></td>
                      </tr>
                      <tr>
                        <td class="text-muted"><i class="bx bx-phone me-1"></i>شماره تلفن اول</td>
                        <td><strong id="cd-phone1">-</strong></td>
                      </tr>
                      <tr>
                        <td class="text-muted"><i class="bx bx-phone me-1"></i>شماره تلفن دوم</td>
                        <td><strong id="cd-phone2">-</strong></td>
                      </tr>
                      <tr>
                        <td class="text-muted"><i class="bx bx-envelope me-1"></i>ایمیل</td>
                        <td><strong id="cd-email">-</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-credit-card me-1"></i>شماره کارت</td>
                        <td><strong id="cd-card">-</strong></td>
                      </tr>
                      <tr>
                        <td class="text-muted"><i class="bx bx-wallet me-1"></i>شماره حساب</td>
                        <td><strong id="cd-account">-</strong></td>
                      </tr>
                      <tr>
                        <td class="text-muted"><i class="bx bx-bank me-1"></i>نام بانک</td>
                        <td><strong id="cd-bank">-</strong></td>
                      </tr>
                      <tr>
                        <td class="text-muted"><i class="bx bx-map me-1"></i>آدرس</td>
                        <td><strong id="cd-address">-</strong></td>
                      </tr>
                      <tr>
                        <td class="text-muted"><i class="bx bx-calendar me-1"></i>تاریخ عضویت</td>
                        <td><strong id="cd-joined">-</strong></td>
                      </tr>
                      <tr>
                        <td class="text-muted"><i class="bx bx-check-circle me-1"></i>وضعیت</td>
                        <td><span id="cd-status" class="badge">-</span></td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>

          <!-- Wells Section -->
          <div class="card mb-4">
            <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="cd-wells-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>
                    </tr>
                  </thead>
                  <tbody id="cd-wells-body">
                    <tr><td class="text-center py-3" colspan="5"><span class="text-muted">رکوردی یافت نشد</span></td></tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>

          <!-- Requests Section -->
          <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="cd-requests-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="cd-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>

<script>
  $(document).ready(function() {
    // Initialize DataTable with Persian language
    $('#customers-table').DataTable({
      pageLength: 10,
      lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "همه"]],
      order: [[0, 'asc']],
      responsive: true,
      columnDefs: [
        { targets: [8], orderable: false } // عملیات column غیرقابل مرتب‌سازی
      ]
    });
    
    // Handle form submission
    $('#form-add-new-record').on('submit', function(e) {
      e.preventDefault();
      
      const form = this;
      const formData = new FormData(form);
      const customerId = $('#customer-id').val();
      
      // Determine URL based on whether we're editing or adding
      const url = customerId ? '{% url "accounts:edit_customer_ajax" 0 %}'.replace('0', customerId) : '{% url "accounts:add_customer_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 customer
            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) {
          // Show error message
          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 customer
      $('#customer-id').val('');
      $('#exampleModalLabel').text('افزودن کاربر جدید');
      $('.data-submit').text('ذخیره');
      
      // Clear validation errors
      $('.is-invalid').removeClass('is-invalid');
      $('.invalid-feedback').remove();
    });
    
    // Clear validation errors when user starts typing
    $('input, textarea').on('input', function() {
      $(this).removeClass('is-invalid');
      $(this).siblings('.invalid-feedback').remove();
    });
  });
  
  // Customer functions
  function viewCustomer(id) {
    const modalEl = document.getElementById('customerDetailsModal');
    const modal = new bootstrap.Modal(modalEl);
    // reset content
    $('#customer-details-content').hide();
    $('#customer-details-loading').show();
    $('#cd-wells-body').html('<tr><td class="text-center py-3" colspan="5"><span class="text-muted">در حال بارگذاری...</span></td></tr>');
    $('#cd-requests-body').html('<tr><td class="text-center py-3" colspan="7"><span class="text-muted">در حال بارگذاری...</span></td></tr>');
    $('#cd-wells-count').text('0');
    $('#cd-requests-count').text('0');
    modal.show();

    // Fetch customer details
    $.get('{% url "accounts:get_customer_details" 0 %}'.replace('0', id))
      .done(function(resp){
        if (!resp.success) { showToast('خطا در دریافت جزئیات مشترک', 'danger'); return; }
        const c = resp.customer;
        $('#customerDetailsModalLabel').text('جزئیات مشترک ' + (c.user.full_name || c.user.username));
        $('#cd-username').text(c.user.username || '-');
        $('#cd-fullname').text(c.user.full_name || '-');
        $('#cd-national-code').text(c.national_code || '-');
        
        // User type and company information
        const userTypeDisplay = c.user_type === 'legal' ? 'حقوقی' : 'حقیقی';
        $('#cd-user-type').text(userTypeDisplay);
        
        if (c.user_type === 'legal') {
          $('#cd-company-name').text(c.company_name || '-');
          $('#cd-company-id').text(c.company_national_id || '-');
          $('#cd-company-name-row').show();
          $('#cd-company-id-row').show();
        } else {
          $('#cd-company-name-row').hide();
          $('#cd-company-id-row').hide();
        }
        
        $('#cd-phone1').text(c.phone_number_1 || '-');
        $('#cd-phone2').text(c.phone_number_2 || '-');
        $('#cd-email').text(c.user.email || '-');
        $('#cd-card').text(c.card_number || '-');
        $('#cd-account').text(c.account_number || '-');
        $('#cd-bank').text(c.bank_name || '-');
        $('#cd-address').text(c.address || '-');
        $('#cd-joined').text(c.user.date_joined || '-');
        
        // Status badge
        if (c.is_completed) {
          $('#cd-status').removeClass().addClass('badge bg-success').text('تکمیل شده');
        } else {
          $('#cd-status').removeClass().addClass('badge bg-warning').text('ناقص');
        }
        
        $('#cd-wells-count').text(resp.total_wells || '0');
        $('#cd-requests-count').text(resp.total_requests || '0');
        $('#customer-details-loading').hide();
        $('#customer-details-content').show();
      })
      .fail(function(){ showToast('خطا در ارتباط با سرور', 'danger'); $('#customer-details-loading').hide(); });

    // Fetch wells
    $.get('{% url "accounts:get_customer_wells" 0 %}'.replace('0', id))
      .done(function(resp){
        if (!resp.success) { $('#cd-wells-body').html('<tr><td class="text-center py-3" colspan="5"><span class="text-danger">خطا در بارگذاری چاه‌ها</span></td></tr>'); return; }
        const rows = (resp.wells || []).map(function(w){
          return '<tr>'+
            '<td>'+ (w.water_subscription_number || '-') +'</td>'+
            '<td>'+ (w.electricity_subscription_number || '-') +'</td>'+
            '<td>'+ (w.water_meter_serial_number || '-') +'</td>'+
            '<td>'+ (w.water_meter_manufacturer || '-') +'</td>'+
            '<td>'+ (w.created || '-') +'</td>'+
          '</tr>';
        });
        if (!rows.length) {
          $('#cd-wells-body').html('<tr><td class="text-center py-3" colspan="5"><span class="text-muted">رکوردی یافت نشد</span></td></tr>');
        } else {
          $('#cd-wells-body').html(rows.join(''));
        }
      })
      .fail(function(){ $('#cd-wells-body').html('<tr><td class="text-center py-3" colspan="5"><span class="text-danger">خطا در بارگذاری چاه‌ها</span></td></tr>'); });

    // Fetch requests
    $.get('{% url "accounts:get_customer_requests" 0 %}'.replace('0', id))
      .done(function(resp){
        if (!resp.success) { $('#cd-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 well = r.well_subscription || '-';
          return '<tr>'+
            '<td>'+ (r.code || '-') +'</td>'+
            '<td>'+ (r.process || '-') +'</td>'+
            '<td>'+ well +'</td>'+
            '<td>'+ step +'</td>'+
            '<td>'+ status +'</td>'+
            '<td>'+ (r.created || '-') +'</td>'+
            '<td><a class="btn btn-sm btn-outline-primary" href="'+ href +'" target="_blank">جزئیات</a></td>'+
          '</tr>';
        });
        if (!rows.length) {
          $('#cd-requests-body').html('<tr><td class="text-center py-3" colspan="7"><span class="text-muted">رکوردی یافت نشد</span></td></tr>');
        } else {
          $('#cd-requests-body').html(rows.join(''));
        }
      })
      .fail(function(){ $('#cd-requests-body').html('<tr><td class="text-center py-3" colspan="7"><span class="text-danger">خطا در بارگذاری درخواست‌ها</span></td></tr>'); });
  }
  
  function editCustomer(id) {
    // Load customer data and open edit form
    $.ajax({
      url: '{% url "accounts:get_customer_data" 0 %}'.replace('0', id),
      type: 'GET',
      success: function(response) {
        if (response.success) {
          const customer = response.customer;
          
          // Fill form with customer data
          const fieldsMap = {
            'customer-id': customer.id,
            'id_first_name': customer.first_name,
            'id_last_name': customer.last_name,
            'user-type-select': customer.user_type,
            'id_phone_number_1': customer.phone_number_1,
            'id_phone_number_2': customer.phone_number_2,
            'id_national_code': customer.national_code,
            'id_company_name': customer.company_name,
            'id_company_national_id': customer.company_national_id,
            'id_card_number': customer.card_number,
            'id_account_number': customer.account_number,
            'id_address': customer.address,
            'id_bank_name': customer.bank_name
          };
          
          // Loop through fields for easier maintenance
          Object.keys(fieldsMap).forEach(function(fieldId) {
            $('#' + fieldId).val(fieldsMap[fieldId] || '');
          });
          
          // Update modal title and button
          $('#exampleModalLabel').text('ویرایش کاربر');
          $('.data-submit').text('ویرایش');
          
          // Ensure select value is applied (for some browsers/plugins)
          if (customer.bank_name !== undefined && customer.bank_name !== null) {
            $('#id_bank_name').val(customer.bank_name);
          }
          
          // Ensure user type is applied and toggle company fields
          if (customer.user_type !== undefined && customer.user_type !== null) {
            $('#user-type-select').val(customer.user_type);
          }
          
          // Toggle company fields based on user type
          toggleCompanyFields();

          // Open modal
          $('#add-new-record').offcanvas('show');
        } else {
          showToast('خطا در بارگذاری اطلاعات کاربر', 'danger');
        }
      },
      error: function() {
        showToast('خطا در ارتباط با سرور', 'danger');
      }
    });
  }
  
  function deleteCustomer(id, name) {
    // Set modal content
    document.getElementById('deleteConfirmText').textContent = `آیا از حذف کاربر "${name}" اطمینان دارید؟`;
    
    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('deleteConfirmModal'));
    modal.show();
    
    // Handle confirm button click
    document.getElementById('confirmDeleteBtn').onclick = function() {
      // Implement delete functionality
      console.log('Delete customer:', id);
      showToast('کاربر با موفقیت حذف شد.', 'success');
      modal.hide();
    };
  }
  
  function prepareAddForm() {
    // Reset form for adding new customer
    const form = $('#form-add-new-record')[0];
    form.reset();
    $('#customer-id').val('');
    $('#exampleModalLabel').text('افزودن کاربر جدید');
    $('.data-submit').text('ذخیره');
    
    // Clear validation errors
    $('.is-invalid').removeClass('is-invalid');
    $('.invalid-feedback').remove();
    
    // Reset user type to individual and hide company fields
    $('#user-type-select').val('individual');
    toggleCompanyFields();
    
    // Open modal
    $('#add-new-record').offcanvas('show');
  }
  
  function toggleCompanyFields() {
    const userType = $('#user-type-select').val();
    const companyFields = $('.company-fields');
    
    if (userType === 'legal') {
      companyFields.show();
      // Make company fields required
      $('input[name="company_name"]').attr('required', true);
      $('input[name="company_national_id"]').attr('required', true);
    } else {
      companyFields.hide();
      // Remove required attribute from company fields
      $('input[name="company_name"]').removeAttr('required').val('');
      $('input[name="company_national_id"]').removeAttr('required').val('');
      // Clear any validation errors for company fields
      $('.company-fields .is-invalid').removeClass('is-invalid');
      $('.company-fields .invalid-feedback').remove();
    }
  }
  
  // Initialize user type toggle functionality
  $(document).ready(function() {
    $('#user-type-select').on('change', toggleCompanyFields);
    // Initialize on page load
    toggleCompanyFields();
  });
</script>
{% endblock %}