{% extends 'base.html' %}

{% block title %}إدارة المنشآت - ICIS{% endblock %}

{% block content %}
<div class="card">
  <div class="card-header">
    <h3 class="card-title">إدارة المنشآت</h3>
  </div>
  <div class="card-body">
    <!-- فلتر الموقع -->
    <div class="row mb-3">
      <div class="col-md-4">
        <label for="filterLocation" class="form-label">تصفية حسب الموقع:</label>
        <select id="filterLocation" class="form-select select2-search">
          <option value="all">جميع المواقع</option>
        </select>
      </div>
    </div>

    <!-- نموذج إضافة منشأة -->
    <form id="establishmentForm" class="row g-3 mb-4">
      <div class="col-md-3">
        <input type="text" class="form-control" id="estNameAr" placeholder="الاسم بالعربية" required>
      </div>
      <div class="col-md-3">
        <input type="text" class="form-control" id="estNameEn" placeholder="الاسم بالإنجليزية">
      </div>
      <div class="col-md-2">
        <div class="input-group">
          <select id="estType" class="form-select" required>
            <option value="">نوع المنشأة</option>
          </select>
          <button type="button" class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#addTypeModal">
            <i class="fas fa-plus"></i>
          </button>
        </div>
      </div>
      <div class="col-md-2">
        <input type="text" class="form-control" id="estLicense" placeholder="رقم الترخيص">
      </div>
      <div class="col-md-2">
        <input type="text" class="form-control" id="estOwner" placeholder="اسم المالك">
      </div>
      <div class="col-md-2">
        <input type="text" class="form-control" id="estPhone" placeholder="الهاتف">
      </div>
      <div class="col-md-3">
        <textarea class="form-control" id="estAddress" rows="1" placeholder="العنوان"></textarea>
      </div>
      <div class="col-md-3">
        <div class="input-group">
          <select id="estLocation" class="form-select select2-search" required>
            <option value="">اختر الموقع</option>
          </select>
          <button type="button" class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#addLocationModal">
            <i class="fas fa-plus"></i>
          </button>
        </div>
      </div>
      <div class="col-md-3">
        <button type="submit" class="btn btn-primary" id="submitEstBtn">إضافة منشأة</button>
        <button type="button" class="btn btn-secondary" id="cancelEstEdit" style="display:none;">إلغاء</button>
      </div>
    </form>

    <!-- جدول المنشآت -->
    <div class="table-responsive">
      <table id="establishmentsTable" class="table table-bordered table-striped" style="width:100%">
        <thead>
          <tr>
            <th>ID</th>
            <th>الاسم (عربي)</th>
            <th>الاسم (إنجليزي)</th>
            <th>النوع</th>
            <th>الموقع</th>
            <th>المنطقة</th>
            <th>المحلية</th>
            <th>الولاية</th>
            <th>الترخيص</th>
            <th>المالك</th>
            <th>الهاتف</th>
            <th>العنوان</th>
            <th>تاريخ الإنشاء</th>
            <th>الإجراءات</th>
           </tr>
        </thead>
      </table>
    </div>
  </div>
</div>

<!-- Modal لإضافة نوع منشأة جديد -->
<div class="modal fade" id="addTypeModal" tabindex="-1" aria-labelledby="addTypeModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="addTypeModalLabel">إضافة نوع منشأة جديد</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="addTypeForm">
          <div class="mb-3">
            <label for="newTypeName" class="form-label">الاسم (عربي)</label>
            <input type="text" class="form-control" id="newTypeName" required>
          </div>
          <div class="mb-3">
            <label for="newTypeCode" class="form-label">الكود (مثلاً: bakery)</label>
            <input type="text" class="form-control" id="newTypeCode" required>
          </div>
          <div class="alert alert-danger d-none" id="typeModalError"></div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
        <button type="button" class="btn btn-primary" id="saveTypeBtn">حفظ</button>
      </div>
    </div>
  </div>
</div>

<!-- Modal لإضافة موقع جديد (كما هو) -->
<div class="modal fade" id="addLocationModal" tabindex="-1" aria-labelledby="addLocationModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="addLocationModalLabel">إضافة موقع جديد</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="addLocationForm">
          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label">اسم الموقع</label>
              <input type="text" class="form-control" id="newLocationName" required>
            </div>
            <div class="col-md-6">
              <label class="form-label">الكود</label>
              <input type="text" class="form-control" id="newLocationCode">
            </div>
            <div class="col-md-6">
              <label class="form-label">المنطقة التصنيفية</label>
              <select id="newLocationZoning" class="form-select">
                <option value="">اختر</option>
                <option value="commercial">تجارية</option>
                <option value="residential">سكنية</option>
                <option value="industrial">صناعية</option>
                <option value="services">خدمية</option>
                <option value="mixed">مختلطة</option>
              </select>
            </div>
            <div class="col-md-3">
              <label class="form-label">خط العرض</label>
              <input type="text" class="form-control" id="newLocationLatitude">
            </div>
            <div class="col-md-3">
              <label class="form-label">خط الطول</label>
              <input type="text" class="form-control" id="newLocationLongitude">
            </div>
            <div class="col-md-12">
              <label class="form-label">المنطقة</label>
              <select id="newLocationArea" class="form-select" required>
                <option value="">اختر المنطقة</option>
              </select>
            </div>
          </div>
          <div class="alert alert-danger d-none mt-3" id="locationModalError"></div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
        <button type="button" class="btn btn-primary" id="saveLocationBtn">حفظ</button>
      </div>
    </div>
  </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
  // CSRF token helper
  function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
      const cookies = document.cookie.split(';');
      for (let i = 0; i < cookies.length; i++) {
        const cookie = cookies[i].trim();
        if (cookie.substring(0, name.length + 1) === (name + '=')) {
          cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
          break;
        }
      }
    }
    return cookieValue;
  }
  const csrftoken = getCookie('csrftoken');

  // Elements
  const estForm = document.getElementById('establishmentForm');
  const nameArInput = document.getElementById('estNameAr');
  const nameEnInput = document.getElementById('estNameEn');
  const typeSelect = document.getElementById('estType');
  const licenseInput = document.getElementById('estLicense');
  const ownerInput = document.getElementById('estOwner');
  const phoneInput = document.getElementById('estPhone');
  const addressInput = document.getElementById('estAddress');
  const locationSelect = document.getElementById('estLocation');
  const submitBtn = document.getElementById('submitEstBtn');
  const cancelBtn = document.getElementById('cancelEstEdit');
  const filterLocationSelect = document.getElementById('filterLocation');

  let editingId = null;

  // Populate establishment types
  async function populateEstablishmentTypes() {
    try {
      const response = await fetch('http://127.0.0.1:8000/api/establishment-types/');
      const types = await response.json();
      typeSelect.innerHTML = '<option value="">نوع المنشأة</option>';
      types.forEach(type => {
        const option = document.createElement('option');
        option.value = type.id;
        option.textContent = type.name;
        typeSelect.appendChild(option);
      });
    } catch (error) {
      console.error('خطأ في جلب أنواع المنشآت:', error);
    }
  }

  // Populate locations (filter & form)
  async function populateLocationSelects() {
    try {
      const response = await fetch('http://127.0.0.1:8000/api/locations/');
      const locations = await response.json();

      filterLocationSelect.innerHTML = '<option value="all">جميع المواقع</option>';
      locationSelect.innerHTML = '<option value="">اختر الموقع</option>';

      locations.forEach(loc => {
        const text = `${loc.name} (${loc.area_name}, ${loc.locality_name})`;
        const optFilter = document.createElement('option');
        optFilter.value = loc.id;
        optFilter.textContent = text;
        filterLocationSelect.appendChild(optFilter);

        const optAdd = document.createElement('option');
        optAdd.value = loc.id;
        optAdd.textContent = text;
        locationSelect.appendChild(optAdd);
      });

      if (typeof $ !== 'undefined' && $.fn.select2) {
        $('#filterLocation, #estLocation').each(function() {
          if ($(this).hasClass('select2-hidden-accessible')) $(this).select2('destroy');
        });
        $('#filterLocation').select2({ theme: 'bootstrap-5', language: 'ar', dir: 'rtl', width: '100%', allowClear: true });
        $('#estLocation').select2({ theme: 'bootstrap-5', language: 'ar', dir: 'rtl', width: '100%', placeholder: 'اختر الموقع', allowClear: true });
      }
    } catch (error) {
      console.error('خطأ في جلب المواقع:', error);
    }
  }

  // CRUD functions for establishments
  window.editEstablishment = async function(id) {
    try {
      const res = await fetch(`http://127.0.0.1:8000/api/establishments/${id}/`);
      if (!res.ok) throw new Error('لا يمكن جلب البيانات');
      const data = await res.json();
      nameArInput.value = data.name_ar;
      nameEnInput.value = data.name_en || '';
      typeSelect.value = data.establishment_type;
      licenseInput.value = data.license_number || '';
      ownerInput.value = data.owner_name || '';
      phoneInput.value = data.phone || '';
      addressInput.value = data.address || '';
      $('#estLocation').val(data.location).trigger('change');
      editingId = id;
      submitBtn.textContent = 'تحديث منشأة';
      cancelBtn.style.display = 'inline-block';
    } catch (error) {
      alert('خطأ في جلب بيانات المنشأة: ' + error.message);
    }
  };

  window.deleteEstablishment = async function(id) {
    if (!confirm('هل أنت متأكد من الحذف؟')) return;
    try {
      const res = await fetch(`http://127.0.0.1:8000/api/establishments/${id}/`, {
        method: 'DELETE',
        headers: { 'X-CSRFToken': csrftoken }
      });
      if (!res.ok) throw new Error('فشل في الحذف');
      $('#establishmentsTable').DataTable().ajax.reload();
    } catch (error) {
      alert('خطأ في الحذف: ' + error.message);
    }
  };

  cancelBtn.addEventListener('click', () => {
    estForm.reset();
    $('#estLocation').val('').trigger('change');
    editingId = null;
    submitBtn.textContent = 'إضافة منشأة';
    cancelBtn.style.display = 'none';
  });

  estForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    const payload = {
      name_ar: nameArInput.value.trim(),
      name_en: nameEnInput.value.trim() || null,
      establishment_type: typeSelect.value,
      location: $('#estLocation').val(),
      license_number: licenseInput.value.trim() || null,
      owner_name: ownerInput.value.trim() || null,
      phone: phoneInput.value.trim() || null,
      address: addressInput.value.trim() || null,
    };
    if (!payload.name_ar || !payload.establishment_type || !payload.location) {
      alert('الرجاء إدخال الاسم بالعربية ونوع المنشأة واختيار الموقع');
      return;
    }
    try {
      let url = 'http://127.0.0.1:8000/api/establishments/';
      let method = 'POST';
      if (editingId) {
        url = `http://127.0.0.1:8000/api/establishments/${editingId}/`;
        method = 'PUT';
      }
      const res = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
          'X-CSRFToken': csrftoken
        },
        body: JSON.stringify(payload)
      });
      if (!res.ok) {
        const errData = await res.json();
        let msg = Object.values(errData).flat().join(', ');
        throw new Error(msg);
      }
      estForm.reset();
      $('#estLocation').val('').trigger('change');
      editingId = null;
      submitBtn.textContent = 'إضافة منشأة';
      cancelBtn.style.display = 'none';
      $('#establishmentsTable').DataTable().ajax.reload();
    } catch (error) {
      alert('خطأ: ' + error.message);
    }
  });

  // Modal for adding new establishment type
  document.getElementById('saveTypeBtn').addEventListener('click', async function() {
    const name = document.getElementById('newTypeName').value.trim();
    const code = document.getElementById('newTypeCode').value.trim();
    const errorDiv = document.getElementById('typeModalError');

    if (!name || !code) {
      errorDiv.textContent = 'الرجاء إدخال الاسم والكود';
      errorDiv.classList.remove('d-none');
      return;
    }

    try {
      const response = await fetch('http://127.0.0.1:8000/api/establishment-types/', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-CSRFToken': csrftoken
        },
        body: JSON.stringify({ name, code })
      });
      if (!response.ok) {
        let errorMsg = 'فشل في إضافة النوع';
        try {
          const errData = await response.json();
          errorMsg = Object.values(errData).flat().join(', ');
        } catch (e) {
          const text = await response.text();
          errorMsg = text || errorMsg;
        }
        throw new Error(errorMsg);
      }
      const newType = await response.json();

      // Add new option to dropdown
      const option = document.createElement('option');
      option.value = newType.id;
      option.textContent = newType.name;
      typeSelect.appendChild(option);
      // Select the new type
      typeSelect.value = newType.id;

      // Close modal and clear fields
      const modal = bootstrap.Modal.getInstance(document.getElementById('addTypeModal'));
      modal.hide();
      document.getElementById('newTypeName').value = '';
      document.getElementById('newTypeCode').value = '';
      errorDiv.classList.add('d-none');

    } catch (error) {
      errorDiv.textContent = error.message;
      errorDiv.classList.remove('d-none');
    }
  });

  // Modal for adding new location (existing code with CSRF)
  document.getElementById('saveLocationBtn').addEventListener('click', async function() {
    const name = document.getElementById('newLocationName').value.trim();
    const code = document.getElementById('newLocationCode').value.trim() || null;
    const zoning = document.getElementById('newLocationZoning').value || null;
    const latitude = document.getElementById('newLocationLatitude').value.trim() || null;
    const longitude = document.getElementById('newLocationLongitude').value.trim() || null;
    const areaId = document.getElementById('newLocationArea').value;
    const errorDiv = document.getElementById('locationModalError');

    if (!name || !areaId) {
      errorDiv.textContent = 'الرجاء إدخال اسم الموقع واختيار المنطقة';
      errorDiv.classList.remove('d-none');
      return;
    }

    try {
      const payload = { name, code: code, area: areaId, zoning, latitude, longitude };
      const res = await fetch('http://127.0.0.1:8000/api/locations/', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-CSRFToken': csrftoken
        },
        body: JSON.stringify(payload)
      });
      if (!res.ok) {
        let msg = 'فشل في إضافة الموقع';
        try {
          const err = await res.json();
          msg = Object.values(err).flat().join(', ');
        } catch (e) {}
        throw new Error(msg);
      }
      const newLoc = await res.json();

      // Update selects
      const filterSelect = filterLocationSelect;
      const addSelect = locationSelect;
      const text = `${newLoc.name} (${newLoc.area_name}, ${newLoc.locality_name})`;
      const optFilter = document.createElement('option');
      optFilter.value = newLoc.id;
      optFilter.textContent = text;
      filterSelect.appendChild(optFilter);
      const optAdd = document.createElement('option');
      optAdd.value = newLoc.id;
      optAdd.textContent = text;
      addSelect.appendChild(optAdd);

      if (typeof $ !== 'undefined' && $.fn.select2) {
        $('#filterLocation').select2('destroy');
        $('#estLocation').select2('destroy');
        $('#filterLocation').select2({ theme: 'bootstrap-5', language: 'ar', dir: 'rtl', width: '100%', allowClear: true });
        $('#estLocation').select2({ theme: 'bootstrap-5', language: 'ar', dir: 'rtl', width: '100%', placeholder: 'اختر الموقع', allowClear: true });
      }

      $('#estLocation').val(newLoc.id).trigger('change');

      const modal = bootstrap.Modal.getInstance(document.getElementById('addLocationModal'));
      modal.hide();
      document.getElementById('newLocationName').value = '';
      document.getElementById('newLocationCode').value = '';
      document.getElementById('newLocationZoning').value = '';
      document.getElementById('newLocationLatitude').value = '';
      document.getElementById('newLocationLongitude').value = '';
      document.getElementById('newLocationArea').value = '';
      errorDiv.classList.add('d-none');
    } catch (error) {
      errorDiv.textContent = error.message;
      errorDiv.classList.remove('d-none');
    }
  });

  // Populate area select for location modal
  async function populateAreaSelectForModal() {
    try {
      const res = await fetch('http://127.0.0.1:8000/api/areas/');
      const areas = await res.json();
      const areaSelect = document.getElementById('newLocationArea');
      areaSelect.innerHTML = '<option value="">اختر المنطقة</option>';
      areas.forEach(area => {
        const opt = document.createElement('option');
        opt.value = area.id;
        opt.textContent = `${area.name} (${area.locality_name})`;
        areaSelect.appendChild(opt);
      });
    } catch (error) {
      console.error('خطأ في جلب المناطق:', error);
    }
  }

  // DataTables initialization
  $(document).ready(function() {
    if (typeof $ !== 'undefined' && $.fn.select2) {
      $('.select2-search:not(.select2-hidden-accessible)').select2({
        theme: 'bootstrap-5', language: 'ar', dir: 'rtl', width: '100%', placeholder: 'ابحث...', allowClear: true
      });
    }

    const table = $('#establishmentsTable').DataTable({
      processing: true,
      serverSide: true,
      ajax: {
        url: 'http://127.0.0.1:8000/api/establishments-datatable/',
        type: 'GET',
        data: function(d) {
          const locFilter = $('#filterLocation').val();
          d.filter_location = (locFilter === 'all') ? '' : locFilter;
        }
      },
      columns: [
        { data: 'id' },
        { data: 'name_ar' },
        { data: 'name_en' },
        { data: 'establishment_type' },
        { data: 'location_name' },
        { data: 'area_name' },
        { data: 'locality_name' },
        { data: 'state_name' },
        { data: 'license_number' },
        { data: 'owner_name' },
        { data: 'phone' },
        { data: 'address' },
        { data: 'created_at' },
        {
          data: null,
          render: function(data, type, row) {
            return '<button class="btn btn-sm btn-warning" onclick="editEstablishment(' + row.id + ')">تعديل</button> ' +
                   '<button class="btn btn-sm btn-danger" onclick="deleteEstablishment(' + row.id + ')">حذف</button>';
          },
          orderable: false,
          searchable: false
        }
      ],
      language: { url: '//cdn.datatables.net/plug-ins/1.13.7/i18n/ar.json' },
      order: [[0, 'desc']],
      pageLength: 10,
      lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]]
    });

    $('#filterLocation').on('change', () => table.ajax.reload());

    populateLocationSelects();
    populateEstablishmentTypes();
    $('#addLocationModal').on('show.bs.modal', populateAreaSelectForModal);
  });
</script>
{% endblock %}