/**
 * Tehnikas pārvaldības modulis
 * 
 * Pieejams tikai darba devējiem
 * 
 * Funkcijas:
 *  - Apskatīt visu savas lauksaimniecības tehniku
 *  - Pievienot lauksaimniecībai jaunu tehniku un tās degvielas bākas tilpumu
 *  - Reģidēt esošo tehniku
 *  - Izdzēst tehniku
 *  - Saglabā degvielas uzpildes reizi, bet tehnikas identifikatoru iestata uz 0
 * Veidoja: Edijs Dunavskis
 */

const EquipmentManager = (() => {
  let currentUser = null;
  let editModal = null;

  /**
   * Inicializē tehnikas pārvaldības lapu
   * Ielādē tehniku
   */
  const init = async () => {
    await HeaderManager.loadHeader('header-container');
    
    // Pārbauda vai lietotājs ir pieslēdzies
    currentUser = JSON.parse(localStorage.getItem('user'));
    if (!currentUser) {
      window.location.href = 'login_lapa.html';
      return;
    }

    // Pārbauda vai lietotājs ir darba devējs
    if (currentUser.status !== 2) {
      showError('You do not have permission to manage equipment.');
      setTimeout(() => window.location.href = 'index.html', 2000);
      return;
    }
    
    // Inicializē bootstrap moduli
    editModal = new bootstrap.Modal(document.getElementById('editEquipmentModal'));
    
    // Ielādē tehnikas datus no servera
    await loadEquipment();
    
    // Izveido formu "event listeners"
    document.getElementById('addEquipmentForm').addEventListener('submit', handleAddEquipment);
    document.getElementById('editEquipmentForm').addEventListener('submit', (e) => {
      e.preventDefault();
      saveEdit();
    });
  };

  /**
   * Nosūta tehnikas datus no servera
   * Filtrē esošā lietotāja lauksaimniecību
   */
  const loadEquipment = async () => {
    try {
      const response = await fetch(`http://localhost:3001/api/equipment?farm_id=${currentUser.farm_id}`);
      if (!response.ok) throw new Error('Failed to load equipment');
      
      const equipment = await response.json();
      displayEquipmentTable(equipment);
      
    } catch (error) {
      console.error('Error loading equipment:', error);
      showError('Failed to load equipment.');
    }
  };

  /**
   * Parāda tehniku tabulas formātā
   * Parāda nosaukumu, bākas tilpumu un pogas
   */
  const displayEquipmentTable = (equipment) => {
    const tbody = document.getElementById('equipmentTableBody');
    
    if (equipment.length === 0) {
      tbody.innerHTML = '<tr><td colspan="3" class="text-center text-muted">No equipment found</td></tr>';
      return;
    }

    tbody.innerHTML = equipment.map(item => `
      <tr>
        <td>${item.name}</td>
        <td>${item.fuel_tank}</td>
        <td>
          <button class="btn btn-sm btn-warning" onclick="EquipmentManager.openEditModal(${item.id}, '${item.name}', ${item.fuel_tank})">
            Edit
          </button>
          <button class="btn btn-sm btn-danger" onclick="EquipmentManager.deleteEquipment(${item.id})">
            Delete
          </button>
        </td>
      </tr>
    `).join('');
  };

  /**
   * Apstrādā jaunas tehnikas pievienošanu
   * Pārbauda ievadi un nosūta uz serveri
   */
  const handleAddEquipment = async (e) => {
    e.preventDefault();
    
    const name = document.getElementById('equipmentName').value.trim();
    const fuelTank = parseInt(document.getElementById('fuelTank').value);

    if (!name || !fuelTank) {
      showError('All fields are required.');
      return;
    }

    try {
      const response = await fetch('http://localhost:3001/api/equipment', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          name,
          fuel_tank: fuelTank,
          farm_id: currentUser.farm_id
        })
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to add equipment');
      }

      await response.json();
      showSuccess('Equipment added successfully!');
      document.getElementById('addEquipmentForm').reset();
      
      // Pārlādē tehnikas tabulu
      await loadEquipment();

    } catch (error) {
      console.error('Error adding equipment:', error);
      showError(error.message || 'Failed to add equipment.');
    }
  };

  /**
   * Atver reģidēšanas moduli ar tehnikas datiem
   */
  const openEditModal = (id, name, fuelTank) => {
    document.getElementById('editEquipmentId').value = id;
    document.getElementById('editEquipmentName').value = name;
    document.getElementById('editFuelTank').value = fuelTank;
    editModal.show();
  };

  /**
   * Saglabā veiktās izmaiņas datos
   * Noūta atjaunotos datus uz serveri
   */
  const saveEdit = async () => {
    const id = document.getElementById('editEquipmentId').value;
    const name = document.getElementById('editEquipmentName').value.trim();
    const fuelTank = parseInt(document.getElementById('editFuelTank').value);

    if (!name || !fuelTank) {
      showError('All fields are required.');
      return;
    }

    try {
      const response = await fetch(`http://localhost:3001/api/equipment/${id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          name,
          fuel_tank: fuelTank
        })
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to update equipment');
      }

      await response.json();
      showSuccess('Equipment updated successfully!');
      editModal.hide();
      
      // Pārlādē tehnikas tabuli
      await loadEquipment();

    } catch (error) {
      console.error('Error updating equipment:', error);
      showError(error.message || 'Failed to update equipment.');
    }
  };

  /**
   * Izdzēš tehniku
   * Saglabā degvielas uzpildes reizi, taču iestata tehnikas identifikatoru uz 0
   */
  const deleteEquipment = async (id) => {
    if (!confirm('Are you sure you want to delete this equipment?')) {
      return;
    }

    try {
      const response = await fetch(`http://localhost:3001/api/equipment/${id}`, {
        method: 'DELETE'
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to delete equipment');
      }

      await response.json();
      showSuccess('Equipment deleted successfully!');
      await loadEquipment();

    } catch (error) {
      console.error('Error deleting equipment:', error);
      showError(error.message || 'Failed to delete equipment.');
    }
  };

  /**
   * Parāda veiksmes paziņojumu
   */
  const showSuccess = (message) => {
    const successDiv = document.getElementById('successMessage');
    successDiv.textContent = '✅ ' + message;
    successDiv.style.display = 'block';
    document.getElementById('errorMessage').style.display = 'none';
    setTimeout(() => {
      successDiv.style.display = 'none';
    }, 3000);
  };

  /**
   * Parāda kļūdas paziņojumu
   */
  const showError = (message) => {
    const errorDiv = document.getElementById('errorMessage');
    errorDiv.textContent = '❌ ' + message;
    errorDiv.style.display = 'block';
    document.getElementById('successMessage').style.display = 'none';
  };

  // Publiskais API
  return {
    init,
    deleteEquipment,
    openEditModal,
    saveEdit
  };
})();



// Inicializē, kad "DOM" ir ielādējies
document.addEventListener('DOMContentLoaded', EquipmentManager.init);
