{% extends '_base.html' %}
{% load static %}
{% load processes_tags %}
{% load common_tags %}
{% load accounts_tags %}
{% load humanize %}

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

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

{% block title %}{{ step.name }} - درخواست {{ instance.code }}{% endblock %}

{% block style %}
<link rel="stylesheet" href="{% static 'assets/vendor/libs/bs-stepper/bs-stepper.css' %}">

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

<style>
  /* Red styling for removal checkboxes when checked */
  .removal-checkbox:checked {
    background-color: #dc3545 !important;
    border-color: #dc3545 !important;
  }
  
  .removal-checkbox:checked:focus {
    box-shadow: 0 0 0 0.25rem rgba(220, 53, 69, 0.25) !important;
  }
</style>
{% endblock %}

{% block content %}

{% include '_toasts.html' %}

<!-- Instance Info Modal -->
{% instance_info_modal instance %}

<div class="container-xxl flex-grow-1 container-p-y">
  <div class="row">
    <div class="col-12 mb-4">
      <div class="d-flex align-items-center justify-content-between mb-3">
        <div>
          <h4 class="mb-1">{{ step.name }}: {{ instance.process.name }}</h4>
          <small class="text-muted d-block">
            {% instance_info instance %}
          </small>
        </div>
        <a href="{% url 'processes:request_list' %}" class="btn btn-outline-secondary">
          <i class="bx bx-chevron-right bx-sm ms-sm-n2"></i>
          بازگشت
        </a>
      </div>

      <div class="bs-stepper wizard-vertical vertical mt-2">
        {% stepper_header instance step %}
        
        <div class="bs-stepper-content">
          {% if report and not edit_mode %}
          <div class="mb-3 text-end">
            {% if user_is_installer and not report.approved %}
              <a href="?edit=1" class="btn btn-primary">
                <i class="bx bx-edit bx-sm me-2"></i>
                ویرایش گزارش نصب
              </a>
            {% endif %}
          </div>
          {% if step_instance and step_instance.status == 'rejected' and step_instance.get_latest_rejection %}
              <div class="alert alert-danger d-flex align-items-start" role="alert">
                <i class="bx bx-error-circle me-2"></i>
                <div>
                  <div><strong>این گزارش رد شده است.</strong></div>
                </div>
              </div>
              {% endif %}
          <div class="card mb-3 border">
            <div class="card-body">
              <div class="row">
                <div class="col-md-6">
                  <p class="text-nowrap mb-2"><i class="bx bx-calendar-event bx-sm me-2"></i>تاریخ مراجعه: {{ report.visited_date|to_jalali|default:'-' }}</p>
                  <p class="text-nowrap mb-2"><i class="bx bx-purchase-tag bx-sm me-2"></i>سریال جدید: {{ report.new_water_meter_serial|default:'-' }}</p>
                  <p class="text-nowrap mb-2"><i class="bx bx-lock-alt bx-sm me-2"></i>شماره پلمپ: {{ report.seal_number|default:'-' }}</p>
                  <p class="text-nowrap mb-2"><i class="bx bx-chip bx-sm me-2"></i>نوع کنتور: {{ report.get_meter_type_display|default:'-' }}</p>
                  {% if report.meter_type == 'smart' %}
                  <p class="text-nowrap mb-2"><i class="bx bx-chip bx-sm me-2"></i>مدل کنتور: {{ report.get_meter_model_display|default:'-' }}</p>
                  {% else %}
                  <p class="text-nowrap mb-2"><i class="bx bx-ruler bx-sm me-2"></i>سایز کنتور: {{ report.meter_size|default:'-' }}</p>
                  {% endif %}
                  <p class="text-nowrap mb-2"><i class="bx bx-tachometer bx-sm me-2"></i>قطر لوله آبده (اینچ): {{ report.discharge_pipe_diameter|default:'-' }}</p>
                  <p class="text-nowrap mb-2"><i class="bx bx-building bx-sm me-2"></i>سازنده کنتور: {{ report.water_meter_manufacturer|default:'-' }}</p>
                  <p class="text-nowrap mb-2"><i class="bx bx-sim-card bx-sm me-2"></i>شماره سیمکارت: {{ report.sim_number|default:'-' }}</p>
                  <p class="text-nowrap mb-2"><i class="bx bx-cog bx-sm me-2"></i>نیرو محرکه چاه: {{ report.driving_force|default:'-' }}</p>
                </div>
                <div class="col-md-6">
                  <p class="text-nowrap mb-2"><i class="bx bx-help-circle bx-sm me-2"></i>کنتور مشکوک: {{ report.is_meter_suspicious|yesno:'بله,خیر' }}</p>
                  <p class="text-nowrap mb-2"><i class="bx bx-map bx-sm me-2"></i>UTM X: {{ report.utm_x|default:'-' }}</p>
                  <p class="text-nowrap mb-2"><i class="bx bx-map-pin bx-sm me-2"></i>UTM Y: {{ report.utm_y|default:'-' }}</p>
                  <p class="text-nowrap mb-2"><i class="bx bx-category bx-sm me-2"></i>نوع مصرف: {{ report.get_usage_type_display|default:'-' }}</p>
                  <p class="text-nowrap mb-2"><i class="bx bx-id-card bx-sm me-2"></i>شماره پروانه بهره‌برداری: {{ report.exploitation_license_number|default:'-' }}</p>
                  <p class="text-nowrap mb-2"><i class="bx bx-bolt-circle bx-sm me-2"></i>قدرت موتور(کیلووات ساعت): {{ report.motor_power|default:'-' }}</p>
                  <p class="text-nowrap mb-2"><i class="bx bx-water bx-sm me-2"></i>دبی قبل کالیبراسیون(لیتر/ثانیه): {{ report.pre_calibration_flow_rate|default:'-' }}</p>
                  <p class="text-nowrap mb-2"><i class="bx bx-water bx-sm me-2"></i>دبی بعد کالیبراسیون(لیتر/ثانیه): {{ report.post_calibration_flow_rate|default:'-' }}</p>
                  
                </div>
              </div>
              {% if report.description %}
              <div class="mt-2">
                <p class="mb-0"><i class="bx bx-text bx-sm me-2"></i><strong>توضیحات:</strong></p>
                <div class="text-muted">{{ report.description|default:'-' }}</div>
              </div>
              {% endif %}
              <hr>
              {% if request.user|is_manager or request.user|is_admin %}
              <hr>
              {% endif %}
              <h6>عکس‌ها</h6>
              <div class="row">
                {% for p in report.photos.all %}
                  <div class="col-6 col-md-3 mb-2"><img class="img-fluid rounded border" src="{{ p.image.url }}" alt="photo"></div>
                {% empty %}
                  <div class="text-muted">بدون عکس</div>
                {% endfor %}
              </div>
              <hr>
              <div class="row g-3">
                <div class="col-12">
                  <h6 class="mb-2">اقلام</h6>
                  <div class="table-responsive">
                    <table class="table table-sm align-middle">
                      <thead>
                        <tr>
                          <th style="width:40px">نوع</th>
                          <th>آیتم</th>
                          <th>تعداد</th>
                          <th>قیمت واحد</th>
                          <th>قیمت کل</th>
                        </tr>
                      </thead>
                      <tbody>
                        {% for ch in report.item_changes.all %}
                        <tr>
                          <td>{% if ch.change_type == 'add' %}<span class="text-success"><i class="bx bx-plus"></i></span>{% else %}<span class="text-danger"><i class="bx bx-minus"></i></span>{% endif %}</td>
                          <td>{{ ch.item.name }}</td>
                          <td>{{ ch.quantity }}</td>
                          <td>{% if ch.unit_price %}{{ ch.unit_price|floatformat:0|intcomma:False }}{% else %}-{% endif %}</td>  
                          <td>
                            {% if ch.total_price %}
                              {{ ch.total_price|floatformat:0|intcomma:False }}
                            {% elif ch.unit_price %}
                              {{ ch.unit_price|floatformat:0|intcomma:False }}
                            {% else %}-{% endif %}
                          </td>
                        </tr>
                        {% empty %}
                        <tr><td colspan="5" class="text-center text-muted">تغییری ثبت نشده است</td></tr>
                        {% endfor %}
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
            </div>
          </div>
          {% if approver_statuses %}
          <div class="card border mt-2">
            <div class="card-header d-flex justify-content-between align-items-center">
              <h6 class="mb-0">وضعیت تاییدها</h6>
              {% if can_approve_reject %}
                {% if current_user_has_decided %}
                <div class="d-flex gap-2">
                  <button type="button" class="btn btn-success btn-sm" disabled>تایید</button>
                  <button type="button" class="btn btn-danger btn-sm" disabled>رد</button>
                </div>
                {% else %}
                <div class="d-flex gap-2">
                  <button type="button" class="btn btn-success btn-sm" data-bs-toggle="modal" data-bs-target="#approveModal">تایید</button>
                  <button type="button" class="btn btn-danger btn-sm" data-bs-toggle="modal" data-bs-target="#rejectModal">رد</button>
                </div>
                {% endif %}
              {% endif %}
            </div>
            <div class="card-body py-3">
              <div class="row g-2">
                {% for st in approver_statuses %}
                <div class="col-12 col-md-6 col-lg-4">
                  <div class="d-flex flex-column border rounded px-2 py-1">
                    <div class="d-flex align-items-center gap-2">
                      <span class="badge bg-light text-dark">{{ st.role.name }}</span>
                      {% if st.status == 'approved' %}
                        <span class="badge bg-success">تایید شد</span>
                      {% elif st.status == 'rejected' %}
                        <span class="badge bg-danger">رد شد</span>
                      {% else %}
                        <span class="badge bg-warning text-dark">در انتظار</span>
                      {% endif %}
                    </div>
                    {% if st.status == 'rejected' and st.reason %}
                      <div class="mt-1 small text-danger">علت: {{ st.reason }}</div>
                    {% endif %}
                  </div>
                </div>
                {% endfor %}
              </div>
            </div>
          </div>
          {% endif %}
          <!-- Persistent nav in edit mode (outside cards) -->
          <div class="d-flex justify-content-between mt-3">
            {% if previous_step %}
              <a href="{% url 'processes:step_detail' instance.id previous_step.id %}" class="btn btn-label-secondary">
                <i class="bx bx-chevron-right bx-sm ms-sm-n2"></i>
                قبلی
              </a>
            {% else %}
              <span></span>
            {% endif %}
            {% if next_step %}
              <a href="{% url 'processes:step_detail' instance.id next_step.id %}" class="btn btn-primary">
                بعدی
                <i class="bx bx-chevron-left bx-sm me-sm-n2"></i>
              </a>
            {% endif %}
          </div>
          {% else %}

          {% if not user_is_installer %}
          <div class="alert alert-warning">شما مجوز ثبت/ویرایش گزارش نصب را ندارید.</div>
          {% endif %}

          {% if user_is_installer %}
          <!-- Installation Report Form -->
          <form method="post" enctype="multipart/form-data" id="installation-report-form">
            {% csrf_token %}         
            <div class="mb-3">
              <div class="">
                <div class="row g-3">
                  <div class="col-md-3">
                    {{ form.visited_date.label_tag }}
                    <!-- Custom date picker handling -->
                    <input type="text" id="id_visited_date_display" class="form-control{% if form.visited_date.errors %} is-invalid{% endif %}" placeholder="انتخاب تاریخ" {% if not user_is_installer %}disabled{% endif %} readonly required value="{% if report and edit_mode and report.visited_date %}{{ report.visited_date|date:'Y/m/d' }}{% elif form.visited_date.value %}{{ form.visited_date.value|date:'Y/m/d' }}{% endif %}">
                    <input type="hidden" id="id_visited_date" name="visited_date" value="{% if report and edit_mode and report.visited_date %}{{ report.visited_date|date:'Y-m-d' }}{% elif form.visited_date.value %}{{ form.visited_date.value }}{% endif %}">
                    {% if form.visited_date.errors %}
                      <div class="invalid-feedback">{{ form.visited_date.errors.0 }}</div>
                    {% endif %}
                  </div>
                  <div class="col-md-3">
                    {{ form.new_water_meter_serial.label_tag }}
                    {{ form.new_water_meter_serial }}
                    {% if form.new_water_meter_serial.errors %}
                      <div class="invalid-feedback">{{ form.new_water_meter_serial.errors.0 }}</div>
                    {% endif %}
                  </div>
                  <div class="col-md-3">
                    {{ form.seal_number.label_tag }}
                    {{ form.seal_number }}
                    {% if form.seal_number.errors %}
                      <div class="invalid-feedback">{{ form.seal_number.errors.0 }}</div>
                    {% endif %}
                  </div>
                  <div class="col-md-3">
                    {{ form.utm_x.label_tag }}
                    {{ form.utm_x }}
                    {% if form.utm_x.errors %}
                      <div class="invalid-feedback">{{ form.utm_x.errors.0 }}</div>
                    {% endif %}
                  </div>
                  <div class="col-md-3">
                    {{ form.utm_y.label_tag }}
                    {{ form.utm_y }}
                    {% if form.utm_y.errors %}
                      <div class="invalid-feedback">{{ form.utm_y.errors.0 }}</div>
                    {% endif %}
                  </div>
                  <div class="col-md-3">
                    {{ form.meter_type.label_tag }}
                    {{ form.meter_type }}
                    {% if form.meter_type.errors %}
                      <div class="invalid-feedback">{{ form.meter_type.errors.0 }}</div>
                    {% endif %}
                  </div>
                  <div class="col-md-3" id="meter_size_wrapper">
                    {{ form.meter_size.label_tag }}
                    {{ form.meter_size }}
                    {% if form.meter_size.errors %}
                      <div class="invalid-feedback">{{ form.meter_size.errors.0 }}</div>
                    {% endif %}
                  </div>
                  <div class="col-md-3" id="meter_model_wrapper">
                    {{ form.meter_model.label_tag }}
                    {{ form.meter_model }}
                    {% if form.meter_model.errors %}
                      <div class="invalid-feedback">{{ form.meter_size.errors.0 }}</div>
                    {% endif %}
                  </div>
                  <div class="col-md-3">
                    {{ form.discharge_pipe_diameter.label_tag }}
                    {{ form.discharge_pipe_diameter }}
                    {% if form.discharge_pipe_diameter.errors %}
                      <div class="invalid-feedback">{{ form.discharge_pipe_diameter.errors.0 }}</div>
                    {% endif %}
                  </div>
                  <div class="col-md-3">
                    {{ form.usage_type.label_tag }}
                    {{ form.usage_type }}
                    {% if form.usage_type.errors %}
                      <div class="invalid-feedback">{{ form.usage_type.errors.0 }}</div>
                    {% endif %}
                  </div>
                  <div class="col-md-3">
                    {{ form.exploitation_license_number.label_tag }}
                    {{ form.exploitation_license_number }}
                    {% if form.exploitation_license_number.errors %}
                      <div class="invalid-feedback">{{ form.exploitation_license_number.errors.0 }}</div>
                    {% endif %}
                  </div>
                  <div class="col-md-3">
                    {{ form.motor_power.label_tag }}
                    {{ form.motor_power }}
                    {% if form.motor_power.errors %}
                      <div class="invalid-feedback">{{ form.motor_power.errors.0 }}</div>
                    {% endif %}
                  </div>
                  <div class="col-md-3">
                    {{ form.pre_calibration_flow_rate.label_tag }}
                    {{ form.pre_calibration_flow_rate }}
                    {% if form.pre_calibration_flow_rate.errors %}
                      <div class="invalid-feedback">{{ form.pre_calibration_flow_rate.errors.0 }}</div>
                    {% endif %}
                  </div>
                  <div class="col-md-3">
                    {{ form.post_calibration_flow_rate.label_tag }}
                    {{ form.post_calibration_flow_rate }}
                    {% if form.post_calibration_flow_rate.errors %}
                      <div class="invalid-feedback">{{ form.post_calibration_flow_rate.errors.0 }}</div>
                    {% endif %}
                  </div>
                  <div class="col-md-3">
                    {{ form.water_meter_manufacturer.label_tag }}حجمی
                    <div class="input-group">
                      {{ form.water_meter_manufacturer }}
                      {{ form.new_manufacturer }}
                      {% if user_is_installer %}
                      <button class="btn btn-outline-primary" type="button" id="btnToggleManufacturer"><i class="bx bx-plus"></i></button>
                      {% endif %}
                    </div>
                    {% if form.water_meter_manufacturer.errors %}
                      <div class="invalid-feedback">{{ form.water_meter_manufacturer.errors.0 }}</div>
                    {% endif %}
                    {% if form.new_manufacturer.errors %}
                      <div class="invalid-feedback">{{ form.new_manufacturer.errors.0 }}</div>
                    {% endif %}
                  </div>
                  <div class="col-md-3">
                    {{ form.sim_number.label_tag }}
                    {{ form.sim_number }}
                    {% if form.sim_number.errors %}
                      <div class="invalid-feedback">{{ form.sim_number.errors.0 }}</div>
                    {% endif %}
                  </div>
                  <div class="col-md-3">
                    {{ form.driving_force.label_tag }}
                    {{ form.driving_force }}
                    {% if form.driving_force.errors %}
                      <div class="invalid-feedback">{{ form.driving_force.errors.0 }}</div>
                    {% endif %}
                  </div>
                  <div class="col-md-3 d-flex align-items-end">
                    <div class="form-check">
                      {{ form.is_meter_suspicious }}
                      {{ form.is_meter_suspicious.label_tag }}
                    </div>
                    {% if form.is_meter_suspicious.errors %}
                      <div class="invalid-feedback">{{ form.is_meter_suspicious.errors.0 }}</div>
                    {% endif %}
                  </div>
                </div>
                <div class="my-3">
                  {{ form.description.label_tag }}
                  {{ form.description }}
                  {% if form.description.errors %}
                    <div class="invalid-feedback">{{ form.description.errors.0 }}</div>
                  {% endif %}
                </div>
                <div class="mb-3">
                  <div class="d-flex justify-content-between align-items-center">
                    <label class="form-label mb-0">عکس‌ها</label>
                    {% if user_is_installer %}
                      <button type="button" class="btn btn-sm btn-outline-primary" id="btnAddPhoto"><i class="bx bx-plus"></i> افزودن عکس</button>
                    {% endif %}
                  </div>
                  {% if report %}
                  <div class="row mt-2">
                    {% for p in report.photos.all %}
                      <div class="col-6 col-md-3 mb-2" id="existing-photo-{{ p.id }}">
                        <div class="position-relative border rounded p-1">
                          <img class="img-fluid rounded" src="{{ p.image.url }}" alt="photo">
                          {% if user_is_installer %}
                            <button type="button" class="btn btn-sm btn-danger position-absolute" style="top:6px; left:6px;" onclick="markDeletePhoto('{{ p.id }}')" title="حذف/برگردان"><i class="bx bx-trash"></i></button>
                          {% endif %}
                          <input type="hidden" name="del_photo_{{ p.id }}" id="del-photo-{{ p.id }}" value="0">
                        </div>
                      </div>
                    {% empty %}
                    {% endfor %}
                  </div>
                  {% endif %}
                  <div class="row mt-2" id="photosPreview"></div>
                  <div id="photoInputs" class="d-none"></div>
                </div>
              </div>
            </div>

            <div class="card border">
              <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">اقلام</h5>
              </div>
              <div class="card-body">
                <div class="row g-3">
                  <div class="col-12 mb-4 d-none">
                    <h6 class="mb-2">اقلام انتخاب‌شده قبلی <small class="text-muted">(برای حذف در نصب تیک بزنید)</small></h6>
                    <div class="table-responsive">
                      <table class="table table-sm align-middle">
                        <thead>
                          <tr>
                            <th style="width:40px">حذف</th>
                            <th>آیتم</th>
                            <th>قیمت واحد</th>
                            <th style="width:140px">تعداد</th>
                          </tr>
                        </thead>
                        <tbody>
                          {% for qi in quote_items %}
                          <tr>
                            <td>
                              <input type="checkbox" class="form-check-input removal-checkbox" name="rem_{{ qi.item.id }}_type" value="remove" title="حذف در نصب" {% if removed_qty|get_item:qi.item.id %}checked{% endif %}>
                              <input type="hidden" name="rem_{{ qi.item.id }}_qty" value="{% if removed_qty|get_item:qi.item.id %}{{ removed_qty|get_item:qi.item.id }}{% else %}{{ qi.quantity }}{% endif %}">
                            </td>
                            <td>
                              <div class="d-flex flex-column">
                                <span class="fw-semibold">{{ qi.item.name }}</span>
                                {% if qi.item.description %}<small class="text-muted">{{ qi.item.description }}</small>{% endif %}
                              </div>
                            </td>
                            <td>{{ qi.unit_price|floatformat:0|intcomma:False }} ریال</td>
                            <td>
                              <span class="text-muted">{% if removed_qty|get_item:qi.item.id %}{{ removed_qty|get_item:qi.item.id }}{% else %}{{ qi.quantity }}{% endif %}</span>
                            </td>
                          </tr>
                          {% empty %}
                          <tr><td colspan="4" class="text-center text-muted">اقلامی ثبت نشده است</td></tr>
                          {% endfor %}
                        </tbody>
                      </table>
                    </div>
                  </div>
                  <div class="col-12">
                    <h6 class="mb-2">افزودن اقلام جدید</h6>
                    <div class="table-responsive">
                      <table class="table table-sm align-middle">
                        <thead>
                          <tr>
                            <th style="width:40px"></th>
                            <th>آیتم</th>
                            <th>قیمت واحد</th>
                            <th style="width:140px">تعداد</th>
                          </tr>
                        </thead>
                        <tbody>
                          {% for it in all_items %}
                          <tr>
                            <td>
                              {% with add_entry=added_map|get_item:it.id %}
                              <input type="checkbox" name="add_{{ it.id }}_type" value="add" class="form-check-input" {% if add_entry %}checked{% endif %}>
                              <input type="hidden" name="add_{{ it.id }}_price" value="{{ it.unit_price }}">
                              {% endwith %}
                            </td>
                            <td>
                              <div class="d-flex flex-column">
                                <span class="fw-semibold">{{ it.name }}</span>
                                {% if it.description %}<small class="text-muted">{{ it.description }}</small>{% endif %}
                              </div>
                            </td>
                            <td>{{ it.unit_price|floatformat:0|intcomma:False }} ریال</td>
                            <td>
                              {% with add_entry=added_map|get_item:it.id %}
                              <input class="form-control form-control-sm" type="number" min="1" name="add_{{ it.id }}_qty" value="{% if add_entry %}{{ add_entry.qty }}{% endif %}">
                              {% endwith %}
                            </td>
                          </tr>
                          {% endfor %}
                        </tbody>
                      </table>
                    </div>
                  </div>
                </div>
              </div>

            </div>
          </form>
          {% endif %}
          <div class="mt-3 d-flex justify-content-between">
            {% if previous_step %}
              <a href="{% url 'processes:step_detail' instance.id previous_step.id %}" class="btn btn-label-secondary">
                <i class="bx bx-chevron-right bx-sm ms-sm-n2"></i>
                قبلی
              </a>
            {% else %}
              <span></span>
            {% endif %}
            <div class="d-flex gap-2">
              {% if user_is_installer %}
                <button type="submit" class="btn btn-success" form="installation-report-form">ثبت گزارش</button>
              {% endif %}
              {% if next_step and not edit_mode %}
                <a href="{% url 'processes:step_detail' instance.id next_step.id %}" class="btn btn-primary">
                  بعدی
                  <i class="bx bx-chevron-left bx-sm me-sm-n2"></i>
                </a>
              {% endif %}
            </div>
          </div>
          {% endif %}

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


<!-- Approve Modal  -->
<div class="modal fade" id="approveModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <form method="post">
        {% csrf_token %}
        <input type="hidden" name="action" value="approve">
        <div class="modal-header">
          <h5 class="modal-title">تایید گزارش نصب</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          آیا از تایید این گزارش اطمینان دارید؟
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal">انصراف</button>
          <button type="submit" class="btn btn-success">تایید</button>
        </div>
      </form>
    </div>
  </div>
  </div>

<!-- Reject Modal -->
<div class="modal fade" id="rejectModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <form method="post">
        {% csrf_token %}
        <input type="hidden" name="action" value="reject">
        <div class="modal-header">
          <h5 class="modal-title">رد گزارش نصب</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <div class="mb-2">
            <label class="form-label">علت رد</label>
            <textarea class="form-control" name="reject_reason" rows="3" required></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal">انصراف</button>
          <button type="submit" class="btn btn-danger">ثبت رد</button>
        </div>
      </form>
    </div>
  </div>
  </div>


{% endblock %}

{% block 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>
  // Persian datepicker for visited_date (exact pattern like sample: display + altField)
  (function(){
    function convertPersianToEnglishNumbers(str) {
      const persianNumbers = '۰۱۲۳۴۵۶۷۸۹';
      const englishNumbers = '0123456789';
      return String(str || '').split('').map(function(char){
        const index = persianNumbers.indexOf(char);
        return index !== -1 ? englishNumbers[index] : char;
      }).join('');
    }

    if (window.$ && $.fn.persianDatepicker && $('#id_visited_date_display').length) {
      try {
        var $display = $('#id_visited_date_display');
        var $hidden = $('#id_visited_date');

        // Prefill from hidden Gregorian to visible Jalali
        var initialGregorian = $hidden.val();
        if (initialGregorian) {
          try {
            var initialJalali = new window.persianDate(new Date(initialGregorian)).format('YYYY/MM/DD');
            $display.val(initialJalali);
          } catch (e) {}
        }

        // Initialize datepicker with altField exactly like the sample
        var picker = $display.persianDatepicker({
          calendarType: 'persian',
          altField: '#id_visited_date',
          format: 'YYYY/MM/DD',
          altFormat: 'YYYY-MM-DD',
          observer: true,
          autoClose: true,
          initialValue: false,
          calendar:{ persian: { leapYearMode: 'astronomical' } },
          onSelect: function (unixDate) {
            var g = new window.persianDate(unixDate).toCalendar('gregorian').format('YYYY-MM-DD');
            g = convertPersianToEnglishNumbers(g);
            $hidden.val(g);
          }
        });
      } catch (e) { console.error('Error initializing Persian Date Picker:', e); }
    }
  })();

  // Require date and show success toast on submit (persist across redirect)
  (function(){
    const form = document.querySelector('form[enctype]') || document.querySelector('form');
    if (!form) return;
    form.addEventListener('submit', function(ev){
      const display = document.getElementById('id_visited_date_display');
      const hidden = document.getElementById('id_visited_date');
      if (!display || !hidden) return;
      if (!display.value || !hidden.value) {
        ev.preventDefault(); ev.stopPropagation();
        showToast('تاریخ مراجعه را انتخاب کنید', 'danger');
        display.scrollIntoView({behavior:'smooth', block:'center'});
        return false;
      }
      // Require at least one photo: either existing (not marked for deletion) or newly added
      try {
        var keptExisting = 0;
        document.querySelectorAll('input[id^="del-photo-"]').forEach(function(inp){
          if (String(inp.value) !== '1') keptExisting += 1;
        });
        var newFiles = document.querySelectorAll('#photoInputs input[type="file"]').length;
        if ((keptExisting + newFiles) <= 0) {
          ev.preventDefault(); ev.stopPropagation();
          showToast('بارگذاری حداقل یک عکس الزامی است', 'danger');
          (document.getElementById('btnAddPhoto') || form).scrollIntoView({behavior:'smooth', block:'center'});
          return false;
        }
      } catch(_) {}
      try { sessionStorage.setItem('install_report_saved', '1'); } catch(_) {}
    }, false);
    // on load, if saved flag exists, show toast
    try {
      if (sessionStorage.getItem('install_report_saved') === '1') {
        sessionStorage.removeItem('install_report_saved');
      }
    } catch(_) {}
  })();

  // Dynamic photo add/remove
  (function(){
    const photoInputs = document.getElementById('photoInputs');
    const photosPreview = document.getElementById('photosPreview');
    const btnAddPhoto = document.getElementById('btnAddPhoto');
    let photoCounter = 0;
    function createPhotoInput() {
      photoCounter += 1;
      const input = document.createElement('input');
      input.type = 'file';
      input.name = 'photos';
      input.accept = 'image/*';
      input.className = 'd-none';
      input.dataset.key = String(photoCounter);
      input.addEventListener('change', function(){
        const file = input.files && input.files[0];
        if (!file) return;
        const reader = new FileReader();
        reader.onload = function(){
          const col = document.createElement('div');
          col.className = 'col-6 col-md-3 mb-2';
          col.id = 'photo-preview-' + input.dataset.key;
          col.innerHTML = `
            <div class="position-relative border rounded p-1">
              <img src="${reader.result}" class="img-fluid rounded" alt="photo">
              <button type="button" class="btn btn-sm btn-danger position-absolute" style="top:6px; left:6px;" data-key="${input.dataset.key}"><i class=\"bx bx-trash\"></i></button>
            </div>
          `;
          photosPreview.appendChild(col);
          col.querySelector('button').addEventListener('click', function(ev){
            const key = ev.currentTarget.getAttribute('data-key');
            const preview = document.getElementById('photo-preview-' + key);
            if (preview) preview.remove();
            const inp = photoInputs.querySelector(`input[data-key="${key}"]`);
            if (inp) inp.remove();
          });
        };
        reader.readAsDataURL(file);
      });
      photoInputs.appendChild(input);
      input.click();
    }
    if (btnAddPhoto) btnAddPhoto.addEventListener('click', createPhotoInput);
  })();

  // Toggle manufacturer select/input (like request_list)
  (function(){
    const $select = $('#id_water_meter_manufacturer');
    const $input = $('#id_new_manufacturer');
    const $btn = $('#btnToggleManufacturer');
    if (!$select.length || !$btn.length) return;
    $btn.on('click', function(){
      if ($select.is(':visible')) {
        $select.hide();
        $input.show().focus();
        $btn.html('<i class="bx bx-check"></i>');
      } else {
        // When switching back, if input has value, append it as selected option
        const val = ($input.val() || '').trim();
        if (val) {
          // Add a temporary option with value prefixed 'new:' to be handled server-side
          const exists = $select.find('option').filter(function(){ return $(this).text().trim() === val; }).length > 0;
          if (!exists) {
            const opt = $('<option></option>').val('').text(val);
            $select.append(opt);
          }
          $select.val('');
        }
        $input.hide();
        $select.show();
        $btn.html('<i class="bx bx-plus"></i>');
      }
    });
  })();

  // Mark delete for existing photos
  function markDeletePhoto(id){
    const hidden = document.getElementById('del-photo-' + id);
    const wrap = document.getElementById('existing-photo-' + id);
    if (hidden && wrap){
      // toggle behavior
      if (hidden.value === '1') {
        hidden.value = '0';
        wrap.style.opacity = '1';
        // update button title back to delete
        const btn = wrap.querySelector('button');
        if (btn) btn.title = 'حذف';
      } else {
        hidden.value = '1';
        wrap.style.opacity = '0.5';
        wrap.style.position = 'relative';
        // update button title to undo
        const btn = wrap.querySelector('button');
        if (btn) btn.title = 'انصراف از حذف';
      }
    }
  }

  // Dynamic meter field visibility based on meter type
  (function() {
    const meterTypeSelect = document.getElementById('{{ form.meter_type.id_for_label }}');
    const meterSizeWrapper = document.getElementById('meter_size_wrapper');
    const meterModelWrapper = document.getElementById('meter_model_wrapper');

    function updateMeterFields() {
      if (!meterTypeSelect) return;
      
      const selectedType = meterTypeSelect.value;
      
      if (selectedType === 'smart') {
        // Show meter_model, hide meter_size
        meterModelWrapper.style.display = '';
        meterSizeWrapper.style.display = 'none';
        // Clear meter_size value when hidden
        const meterSizeInput = meterSizeWrapper.querySelector('input, select');
        if (meterSizeInput) meterSizeInput.value = '';
      } else if (selectedType === 'volumetric') {
        // Show meter_size, hide meter_model
        meterSizeWrapper.style.display = '';
        meterModelWrapper.style.display = 'none';
        // Clear meter_model value when hidden
        const meterModelSelect = meterModelWrapper.querySelector('select');
        if (meterModelSelect) meterModelSelect.value = '';
      } else {
        // No selection: hide both
        meterSizeWrapper.style.display = 'none';
        meterModelWrapper.style.display = 'none';
      }
    }

    // Initial update on page load
    updateMeterFields();

    // Update on change
    if (meterTypeSelect) {
      meterTypeSelect.addEventListener('change', updateMeterFields);
    }
  })();
</script>
{% endblock %}

