{% extends '_base.html' %}
{% load static %}
{% load processes_tags %}
{% load common_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">
{% 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 show_denied_msg %}
            <div class="alert alert-warning mb-3">شما اجازه تعیین نصاب را ندارید.</div>
          {% endif %}
          <form method="post">
            {% csrf_token %}
            <div class="row g-3">
              <div class="col-md-6">
                <label class="form-label">نصاب</label>
                <select name="installer_id" class="form-select" {% if read_only %}disabled{% endif %} required>
                  <option value="">انتخاب کنید...</option>
                  {% for p in installers %}
                    <option value="{{ p.user.id }}" {% if assignment.installer and p.user.id == assignment.installer.id %}selected{% endif %}>{{ p.user.get_full_name }} ({{ p.user.username }})</option>
                  {% endfor %}
                </select>
              </div>
              <div class="col-md-6">
                <label class="form-label">تاریخ مراجعه نصاب</label>
                <input type="text" id="id_scheduled_date_display" class="form-control" placeholder="انتخاب تاریخ" {% if read_only %}disabled{% endif %} readonly required value="{% if assignment.scheduled_date %}{{ assignment.scheduled_date|date:'Y/m/d' }}{% endif %}">
                <input type="hidden" id="id_scheduled_date" name="scheduled_date" value="{% if assignment.scheduled_date %}{{ assignment.scheduled_date|date:'Y-m-d' }}{% endif %}">
              </div>
            </div>
            {% if assignment.assigned_by or assignment.installer %}
            <div class="mt-3 alert alert-primary">
              <div class="row g-2">
                {% if assignment.assigned_by %}
                <div class="col-12 col-md-6">
                  <div class="small text-dark">تعیین‌کننده نصاب</div>
                  <div>{{ assignment.assigned_by.get_full_name|default:assignment.assigned_by.username }} <span class="text-muted">({{ assignment.assigned_by.username }})</span></div>
                </div>
                {% endif %}
                {% if assignment.updated %}
                <div class="col-12 col-md-6">
                  <div class="small text-dark">تاریخ ثبت/ویرایش</div>
                  <div>{{ assignment.updated|to_jalali }}</div>
                </div>
                {% endif %}
              </div>
            </div>
            {% endif %}
            <div class="d-flex justify-content-between mt-4">
              {% 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 is_manager %}
                <button class="btn btn-primary" type="submit">ثبت و ادامه
                  <i class="bx bx-chevron-left bx-sm me-sm-n2"></i>
                </button>
              {% else %}
              <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>
          </form>
        </div>
      </div>
    </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>
  (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('');
    }

    function initPersianDatePicker() {
      if ($.fn.persianDatepicker && $('#id_scheduled_date_display').length) {
        try {
          var $display = $('#id_scheduled_date_display');
          var $hidden = $('#id_scheduled_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) {}
          }

          $display.persianDatepicker({
            calendarType: 'persian',
            altField: '#id_scheduled_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);
        }
      }
    }

    document.addEventListener('DOMContentLoaded', initPersianDatePicker);
  })();

  // Require date and show success toast on submit
  (function(){
    const form = document.querySelector('form');
    if (!form) return;
    form.addEventListener('submit', function(ev){
      const display = document.getElementById('id_scheduled_date_display');
      const hidden = document.getElementById('id_scheduled_date');
      if (!display.value || !hidden.value) {
        ev.preventDefault(); ev.stopPropagation();
        if (typeof showToast === 'function') showToast('تاریخ مراجعه نصاب را انتخاب کنید', 'danger');
        display.scrollIntoView({behavior:'smooth', block:'center'});
        return false;
      }
      try { sessionStorage.setItem('assign_saved', '1'); } catch(_) {}
    }, false);

    try {
      if (sessionStorage.getItem('assign_saved') === '1') {
        sessionStorage.removeItem('assign_saved');
        if (typeof showToast === 'function') showToast('با موفقیت ثبت شد', 'success');
      }
    } catch(_) {}
  })();
</script>
{% endblock %}


