{% 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">
    <!-- نموذج إضافة ولاية (بسيط) -->
    <form id="stateForm" class="row g-3 mb-4">
      <div class="col-md-4">
        <input type="text" class="form-control" id="stateName" placeholder="اسم الولاية" required>
      </div>
      <div class="col-md-4">
        <input type="text" class="form-control" id="stateCode" placeholder="الكود" required>
      </div>
      <div class="col-md-4">
        <button type="submit" class="btn btn-primary" id="submitStateBtn">إضافة ولاية</button>
        <button type="button" class="btn btn-secondary" id="cancelEdit" style="display:none;">إلغاء</button>
      </div>
    </form>

    <!-- جدول عرض الولايات -->
    <div class="table-responsive">
      <table class="table table-bordered table-striped">
        <thead>
          <tr>
            <th>ID</th>
            <th>الاسم</th>
            <th>الكود</th>
            <th>تاريخ الإنشاء</th>
            <th>الإجراءات</th>
          </tr>
        </thead>
        <tbody id="statesTableBody">
          <tr><td colspan="5" class="text-center">جاري التحميل...</td></tr>
        </tbody>
      </table>
    </div>
  </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    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');
  const stateForm = document.getElementById('stateForm');
  const stateNameInput = document.getElementById('stateName');
  const stateCodeInput = document.getElementById('stateCode');
  const submitStateBtn = document.getElementById('submitStateBtn');
  const cancelEditBtn = document.getElementById('cancelEdit');
  const statesTableBody = document.getElementById('statesTableBody');

  let editingStateId = null;

  async function fetchStates() {
    try {
      const response = await fetch('http://127.0.0.1:8000/api/states/');
      if (!response.ok) throw new Error('فشل في جلب البيانات');
      const states = await response.json();
      displayStates(states);
    } catch (error) {
      statesTableBody.innerHTML = `<tr><td colspan="5" class="text-danger">خطأ: ${error.message}</td></tr>`;
    }
  }

  function displayStates(states) {
    if (states.length === 0) {
      statesTableBody.innerHTML = '<tr><td colspan="5" class="text-center">لا توجد ولايات</td></tr>';
      return;
    }
    let html = '';
    states.forEach(state => {
      const createdDate = new Date(state.created_at).toLocaleDateString('ar-EG');
      html += `
        <tr>
          <td>${state.id}</td>
          <td>${state.name}</td>
          <td>${state.code}</td>
          <td>${createdDate}</td>
          <td>
            <button class="btn btn-sm btn-warning" onclick="editState(${state.id})">تعديل</button>
            <button class="btn btn-sm btn-danger" onclick="deleteState(${state.id})">حذف</button>
          </td>
        </tr>
      `;
    });
    statesTableBody.innerHTML = html;
  }

  window.editState = async function(id) {
    try {
      const response = await fetch(`http://127.0.0.1:8000/api/states/${id}/`);
      if (!response.ok) throw new Error('لا يمكن جلب البيانات');
      const state = await response.json();
      stateNameInput.value = state.name;
      stateCodeInput.value = state.code;
      editingStateId = id;
      submitStateBtn.textContent = 'تحديث ولاية';
      cancelEditBtn.style.display = 'inline-block';
    } catch (error) {
      alert('خطأ في جلب بيانات الولاية: ' + error.message);
    }
  };

  window.deleteState = async function(id) {
    if (!confirm('هل أنت متأكد من الحذف؟')) return;
    try {
      const response = await fetch(`http://127.0.0.1:8000/api/states/${id}/`, {
        method: 'DELETE'
      });
      if (!response.ok) throw new Error('فشل في الحذف');
      fetchStates();
    } catch (error) {
      alert('خطأ في الحذف: ' + error.message);
    }
  };

  cancelEditBtn.addEventListener('click', () => {
    stateNameInput.value = '';
    stateCodeInput.value = '';
    editingStateId = null;
    submitStateBtn.textContent = 'إضافة ولاية';
    cancelEditBtn.style.display = 'none';
  });

  stateForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    const name = stateNameInput.value.trim();
    const code = stateCodeInput.value.trim();
    if (!name || !code) {
      alert('الرجاء إدخال جميع الحقول');
      return;
    }
    try {
      if (editingStateId) {
        await fetch(`http://127.0.0.1:8000/api/states/${editingStateId}/`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken },
          body: JSON.stringify({ name, code })
        });
      } else {
        await fetch('http://127.0.0.1:8000/api/states/', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken },
          body: JSON.stringify({ name, code })
        });
      }
      stateNameInput.value = '';
      stateCodeInput.value = '';
      editingStateId = null;
      submitStateBtn.textContent = 'إضافة ولاية';
      cancelEditBtn.style.display = 'none';
      fetchStates();
    } catch (error) {
      alert('خطأ: ' + error.message);
    }
  });

  fetchStates();



    // Delete state with notification
window.deleteState = async function(id) {
    if (!confirm('هل أنت متأكد من الحذف؟')) return;
    try {
        const response = await fetch(`http://127.0.0.1:8000/api/states/${id}/`, {
            method: 'DELETE',
            headers: { 'X-CSRFToken': csrftoken }
        });
        if (!response.ok) throw new Error('فشل في الحذف');
        showNotification('تم حذف الولاية بنجاح', 'success');
        fetchStates();
    } catch (error) {
        showNotification('خطأ في الحذف: ' + error.message, 'error');
    }
};

// Cancel edit button (reset form)
cancelEditBtn.addEventListener('click', () => {
    stateNameInput.value = '';
    stateCodeInput.value = '';
    editingStateId = null;
    submitStateBtn.textContent = 'إضافة ولاية';
    cancelEditBtn.style.display = 'none';
});

// Form submission
stateForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    const name = stateNameInput.value.trim();
    const code = stateCodeInput.value.trim();
    if (!name || !code) {
        showNotification('الرجاء إدخال جميع الحقول', 'warning');
        return;
    }
    try {
        if (editingStateId) {
            const response = await fetch(`http://127.0.0.1:8000/api/states/${editingStateId}/`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': csrftoken
                },
                body: JSON.stringify({ name, code })
            });
            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(Object.values(errorData).flat().join(', '));
            }
            showNotification('تم تحديث الولاية بنجاح', 'success');
        } else {
            const response = await fetch('http://127.0.0.1:8000/api/states/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': csrftoken
                },
                body: JSON.stringify({ name, code })
            });
            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(Object.values(errorData).flat().join(', '));
            }
            showNotification('تم إضافة الولاية بنجاح', 'success');
        }
        // Reset form
        stateNameInput.value = '';
        stateCodeInput.value = '';
        editingStateId = null;
        submitStateBtn.textContent = 'إضافة ولاية';
        cancelEditBtn.style.display = 'none';
        fetchStates();
    } catch (error) {
        showNotification('خطأ: ' + error.message, 'error');
    }
    if (!response.ok) {
    const errorData = await response.json();
    // Combine all error messages
    let errorMsg = '';
    for (const field in errorData) {
        errorMsg += `${field}: ${errorData[field].join(', ')} `;
    }
    throw new Error(errorMsg.trim());
}
});
</script>
{% endblock %}