{% extends '_base.html' %}
{% load static %}
{% load processes_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' %}">
<style>
@media print {
  .no-print { display: none !important; }
}
</style>
{% endblock %}

{% block content %}
{% include '_toasts.html' %}

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

{% csrf_token %}
<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 no-print">
        <div>
          <h4 class="mb-1">{{ step.name }}: {{ instance.process.name }}</h4>
          <small class="text-muted d-block">
            {% instance_info instance %}
          </small>
        </div>
        <div class="d-flex gap-2">
          <a href="{% url 'invoices:quote_print' instance.id %}" target="_blank" class="btn btn-outline-secondary">
            <i class="bx bx-printer me-2"></i> پرینت
          </a>
          <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>

      <div class="bs-stepper wizard-vertical vertical mt-2 no-print">
        {% stepper_header instance step %}
        <div class="bs-stepper-content">
            <!-- Invoice Preview Card -->
      <div class="card invoice-preview-card mt-4 border">
        <div class="card-body">
          <div class="d-flex justify-content-between flex-xl-row flex-md-column flex-sm-row flex-column p-sm-3 p-0 align-items-center">
            <div class="mb-xl-0 mb-4">
              <!-- Company Logo & Info -->
              <div class="d-flex align-items-center">
                <div class="avatar avatar-lg me-3">
                  <span class="avatar-initial rounded bg-label-primary">
                    {% if instance.broker.company %}
                      <img src="{{ instance.broker.company.logo.url }}" alt="لوگوی شرکت" style="max-height:80px;">
                    {% else %}
                      <i class="bx bx-buildings bx-md"></i>
                    {% endif %}
                  </span>
                </div>
                <div>
                  <h5 class="mb-1">
                    {% if instance.broker.company %}
                      {{ instance.broker.company.name }}
                    {% else %}
                      شرکت آب منطقه‌ای
                    {% endif %}
                  </h5>
                  {% if instance.broker.company %}
                    <div class="text-muted small">
                      {% if instance.broker.company.address %}
                        <div><i class="bx bx-map me-1"></i>{{ instance.broker.company.address }}</div>
                      {% endif %}
                      {% if instance.broker.affairs.county.city.name %}
                        <div><i class="bx bx-current-location me-1"></i>{{ instance.broker.affairs.county.city.name }}، ایران</div>
                      {% endif %}
                      {% if instance.broker.company.phone %}
                        <div><i class="bx bx-phone me-1"></i>{{ instance.broker.company.phone }}</div>
                      {% endif %}
                    </div>
                  {% endif %}
                </div>
              </div>
            </div>
            <!-- Invoice Details -->
            <div class="text-center">
              <div class="mb-3">
                <h5 class="text-body">#{{ quote.name }}</h5>
              </div>
              <div class="invoice-details">
                <div class="d-flex justify-content-end align-items-center mb-2">
                  <span class="text-muted me-2">تاریخ صدور:</span>
                  <span class="fw-medium text-body">{{ quote.jcreated_date }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <hr class="my-0">
        <div class="card-body py-1">
          <div class="row">
            <div class="col-xl-6 col-md-12 col-sm-6 col-12 mb-3">
              <div class="">
                <div class="card-body p-3">
                  <h6 class="card-title text-primary mb-2">
                    <i class="bx bx-user me-1"></i>
                    {% if instance.representative.profile.user_type == 'legal' %}
                      اطلاعات مشترک (حقوقی)
                    {% else %}
                      اطلاعات مشترک (حقیقی)
                    {% endif %}
                  </h6>
                  {% if instance.representative.profile.user_type == 'legal' %}
                  <div class="d-flex gap-2 mb-1">
                    <span class="text-muted small">نام شرکت:</span>
                    <span class="fw-medium small">{{ instance.representative.profile.company_name|default:"-" }}</span>
                  </div>
                  <div class="d-flex gap-2 mb-1">
                    <span class="text-muted small">شناسه ملی:</span>
                    <span class="fw-medium small">{{ instance.representative.profile.company_national_id|default:"-" }}</span>
                  </div>
                  {% endif %}
                  <div class="d-flex gap-2 mb-1">
                    <span class="text-muted small">نام:</span>
                    <span class="fw-medium small">{{ quote.customer.get_full_name }}</span>
                  </div>
                  {% if instance.representative.profile.national_code %}
                  <div class="d-flex gap-2 mb-1">
                    <span class="text-muted small">کد ملی:</span>
                    <span class="fw-medium small">{{ instance.representative.profile.national_code }}</span>
                  </div>
                  {% endif %}
                  {% if instance.representative.profile.phone_number_1 %}
                  <div class="d-flex gap-2 mb-1">
                    <span class="text-muted small">تلفن:</span>
                    <span class="fw-medium small">{{ instance.representative.profile.phone_number_1 }}</span>
                  </div>
                  {% endif %}
                  {% if instance.representative.profile.address %}
                  <div class="d-flex gap-2">
                    <span class="text-muted small">آدرس:</span>
                    <span class="fw-medium small">{{ instance.representative.profile.address }}</span>
                  </div>
                  {% endif %}

                </div>
              </div>
            </div>
            <div class="col-xl-6 col-md-12 col-sm-6 col-12 mb-3">
              <div class="border-0 bg-light">
                <div class="card-body p-3">
                  <h6 class="card-title text-primary mb-2">
                    <i class="bx bx-droplet me-1"></i>اطلاعات چاه
                  </h6>
                  <div class="d-flex gap-2 mb-1">
                    <span class="text-muted small">شماره اشتراک آب:</span>
                    <span class="fw-medium small">{{ instance.well.water_subscription_number }}</span>
                  </div>
                  <div class="d-flex gap-2 mb-1">
                    <span class="text-muted small">شماره اشتراک برق:</span>
                    <span class="fw-medium small">{{ instance.well.electricity_subscription_number|default:"-" }}</span>
                  </div>
                  <div class="d-flex gap-2 mb-1">
                    <span class="text-muted small">سریال کنتور:</span>
                    <span class="fw-medium small">{{ instance.well.water_meter_serial_number|default:"-" }}</span>
                  </div>
                  <div class="d-flex gap-2">
                    <span class="text-muted small">قدرت چاه:</span>
                    <span class="fw-medium small">{{ instance.well.well_power|default:"-" }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="table-responsive">
          <table class="table border-top m-0">
            <thead>
              <tr>
                <th>آیتم</th>
                <th>توضیحات</th>
                <th>قیمت واحد</th>
                <th>تعداد</th>
                <th>قیمت کل</th>
              </tr>
            </thead>
            <tbody>
              {% for quote_item in quote.items.all %}
              <tr>
                <td class="text-nowrap">{{ quote_item.item.name }}</td>
                <td class="text-nowrap">{{ quote_item.item.description|default:"-" }}</td>
                <td>{{ quote_item.unit_price|floatformat:0|intcomma:False }} ریال</td>
                <td>{{ quote_item.quantity }}</td>
                <td>{{ quote_item.total_price|floatformat:0|intcomma:False }} ریال</td>
              </tr>
              {% endfor %}
              <tr>
                <td colspan="3" class="align-top px-4 py-5">
                </td>
                <td class="text-end px-4 py-5">
                  <p class="mb-2">جمع کل:</p>
                  {% if quote.discount_amount > 0 %}
                  <p class="mb-2">تخفیف:</p>
                  {% endif %}
                  <p class="mb-2">مالیات بر ارزش افزوده:</p>
                  <p class="mb-0 fw-bold">مبلغ نهایی (شامل مالیات):</p>
                </td>
                <td class="px-4 py-5">
                  <p class="fw-medium mb-2">{{ quote.total_amount|floatformat:0|intcomma:False }} ریال</p>
                  {% if quote.discount_amount > 0 %}
                  <p class="fw-medium mb-2">{{ quote.discount_amount|floatformat:0|intcomma:False }} ریال</p>
                  {% endif %}
                  <p class="fw-medium mb-2">{{ quote.get_vat_amount|floatformat:0|intcomma:False }} ریال</p>
                  <p class="fw-bold mb-0">{{ quote.final_amount|floatformat:0|intcomma:False }} ریال</p>
                </td>
              </tr>
            </tbody>
          </table>
          <!-- Footer Information -->
          <div class="card-body border-top">
            <div class="row">
              <div class="col-md-8">
                <h6 class="mb-3">شرایط و ضوابط:</h6>
                <ul class="list-unstyled mb-0">
                  <li class="mb-2">
                    <i class="bx bx-time-five text-muted me-2"></i>
                    اعتبار پیش‌فاکتور صادر شده ۴۸ ساعت پس از تاریخ صدور می‌باشد
                  </li>
                  <li class="mb-2">
                    <i class="bx bx-money text-muted me-2"></i>
                    مبلغ فوق به صورت علی‌الحساب دریافت می‌گردد
                  </li>
                  <li class="mb-0">
                    <i class="bx bx-info-circle text-muted me-2"></i>
                    این برگه صرفاً جهت اعلام قیمت بوده و ارزش قانونی دیگری ندارد
                  </li>
                  {% if instance.broker.company.signature %}
                  <li class="mb-0 text-start mt-4 ms-5">
                    <img src="{{ instance.broker.company.signature.url }}" alt="امضای شرکت" style="height: 200px;">
                  </li>
                  {% endif %}
                </ul>
              </div>
              {% if instance.broker.company %}
              <div class="col-md-4">
                <h6 class="mb-3">اطلاعات پرداخت:</h6>
                <div class="d-flex flex-column gap-2">
                  {% if instance.broker.company.card_number %}
                  <div>
                    <small class="text-muted">شماره کارت:</small>
                    <div class="fw-medium">{{ instance.broker.company.card_number }}</div>
                  </div>
                  {% endif %}
                  {% if instance.broker.company.account_number %}
                  <div>
                    <small class="text-muted">شماره حساب:</small>
                    <div class="fw-medium">{{ instance.broker.company.account_number }}</div>
                  </div>
                  {% endif %}
                  {% if instance.broker.company.sheba_number %}
                  <div>
                    <small class="text-muted">شماره شبا:</small>
                    <div class="fw-medium">{{ instance.broker.company.sheba_number }}</div>
                  </div>
                  {% endif %}
                  {% if instance.broker.company.bank_name %}
                  <div>
                    <small class="text-muted">بانک:</small>
                    <div class="fw-medium">{{ instance.broker.company.get_bank_name_display }}</div>
                  </div>
                  {% endif %}
                  {% if instance.broker.company.branch_name %}
                  <div>
                    <small class="text-muted">شعبه:</small>
                    <div class="fw-medium">{{ instance.broker.company.branch_name }}</div>
                  </div>
                  {% endif %}
                  
                </div>

              </div>
              {% endif %}
            </div>
          </div>
        </div>

        {% if quote.notes %}
        <div class="card-body">
          <div class="row">
            <div class="col-12">
              <span class="fw-medium">یادداشت:</span>
              <span>{{ quote.notes }}</span>
            </div>
          </div>
        </div>
        {% endif %}
      </div>
      
      <!-- Action Buttons -->
      <div class="row mt-4 no-print">
        <div class="col-12">
          <div class="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>
                <span class="align-middle d-sm-inline-block d-none">ویرایش اقلام</span>
              </a>
            {% else %}
              <span></span>
            {% endif %}
            
            {% if is_broker %}
              {% if step_instance.status == 'completed' %}
                {% if next_step %}
                  <a href="{% url 'processes:step_detail' instance.id next_step.id %}" 
                     class="btn btn-primary">
                    <span class="align-middle d-sm-inline-block d-none me-sm-1">بعدی</span>
                    <i class="bx bx-chevron-left bx-sm me-sm-n2"></i>
                  </a>
                {% else %}
                  <button class="btn btn-success" type="button">اتمام</button>
                {% endif %}
              {% else %}
                <button type="button" class="btn btn-primary" id="btnApproveQuote">
                  تایید پیش‌فاکتور
                </button>
              {% endif %}
            {% else %}
              {% 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>
              {% else %}
                <a href="{% url 'processes:request_list' %}" class="btn btn-success">اتمام</a>
              {% endif %}
            {% endif %}
          </div>
        </div>
      </div>

        </div>
      </div>
      
      
    </div>
  </div>
</div>
{% endblock %}

{% block script %}
<script src="{% static 'assets/vendor/libs/bs-stepper/bs-stepper.js' %}"></script>
<script>
  document.addEventListener('DOMContentLoaded', function () {
    // Quote approval
    const btnApproveQuote = document.getElementById('btnApproveQuote');
    if (btnApproveQuote) {
      btnApproveQuote.addEventListener('click', function() {
        btnApproveQuote.disabled = true;
        fetch('{% url "invoices:approve_quote" instance.id step.id %}', {
          method: 'POST',
          headers: {
            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
            'Content-Type': 'application/x-www-form-urlencoded',
          }
        }).then(r => r.json()).then(resp => {
          if (resp.success) {
            showToast('پیش‌فاکتور با موفقیت تایید شد', 'success');
            if (resp.redirect) {
              window.location.href = resp.redirect;
              return;
            }
            setTimeout(() => { window.location.reload(); }, 800);
          } else {
            showToast(resp.message || 'خطا در تایید پیش‌فاکتور', 'danger');
            btnApproveQuote.disabled = false;
          }
        }).catch(() => {
          showToast('خطا در ارتباط با سرور', 'danger');
          btnApproveQuote.disabled = false;
        });
      });
    }
  });
</script>
{% endblock %}
