import permissionUtils from "./common.js";
import { ORDERS } from "./frontEndPermission.js";

//document.addEventListener('DOMContentLoaded', () => {
  const ordersSection = document.getElementById('ordersSection');
  const orderFormSection = document.getElementById('orderFormSection');
  const orderForm = document.getElementById('orderForm');
  const ordersTableBody = document.getElementById('ordersTable').querySelector('tbody');
  const viewOrdersBtn = document.getElementById('viewOrdersBtn');
  const addOrderBtn = document.getElementById('addOrderBtn');
  //const formTitle = document.getElementById('formTitle');
  const orderIdInput = document.getElementById('orderId');
  const companyId=sessionStorage.getItem('companyId');
  const branchId=sessionStorage.getItem('branchId');
  const filterButton = document.getElementById('filterButton');

  const startDateInput = document.getElementById('startDate');
  const endDateInput = document.getElementById('endDate');

  // Get today's date and a week before today in YYYY-MM-DD format
  const today = new Date().toISOString().split('T')[0];
  const lastWeek = new Date();
  lastWeek.setDate(lastWeek.getDate() - 7);
  const lastWeekDate = lastWeek.toISOString().split('T')[0];

  // Set default values
  startDateInput.value = lastWeekDate;
  endDateInput.value = today;

  const toggleForm = (show) => {
    if (show) {
      ordersSection.classList.add('hidden');
      orderFormSection.classList.remove('hidden');
    } else {
      ordersSection.classList.remove('hidden');
      orderFormSection.classList.add('hidden');
    }
  };






  const fetchOrders = async () => {
    try {

  const startDate = document.getElementById('startDate').value; // Get the start date
    const endDate = document.getElementById('endDate').value;     // Get the end date

const response = await fetch(`/api/order?companyId=${companyId}&branchId=${branchId}&start=${startDate}&end=${endDate}`);


      const orders = await response.json();

      ordersTableBody.innerHTML = '';
      orders.forEach((order) => {
        const row = document.createElement('tr');
        const statusChecked = order.status ? 'checked' : '';
        row.innerHTML = `
          <td>${order.itemName}</td>
          <td>${order.customerName}</td>
          <td>${order.advancePayment}</td>
          <td>${order.remainingPayment}</td>
    <td>
  <label class="switch">
    <input type="checkbox" ${statusChecked} }>
    <span class="slider round"></span>
  </label>
</td>
          <td class="row-action">
            <button class="edit-btn" data-id="${order._id}">Edit</button>
            <button class="delete-btn" data-id="${order._id}">Delete</button>
          </td>
        `;
        ordersTableBody.appendChild(row);
      });

      attachEventListeners();
    } catch (error) {
      console.error('Error fetching orders:', error);
    }
  };

  filterButton.addEventListener('click', () => fetchOrders());

  const saveOrder = async (orderData, orderId = null) => {
    try {
    
      const method = orderId ? 'PUT' : 'POST';
      const url =  `/api/order/${orderId}` 

      const response = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(orderData),
      });

      if (response.ok) {
        alert('Order saved successfully');
        fetchOrders();
        toggleForm(false);
      } else {
        alert('Failed to save order');
      }
    } catch (error) {
      console.error('Error saving order:', error);
    }
  };



  const deleteOrder = async (orderId) => {
    try {
      const response = await fetch(`/api/order/${orderId}`, {
        method: 'DELETE',
      });

      if (response.ok) {
        alert('Order deleted successfully');
        fetchOrders();
      } else {
        alert('Failed to delete order');
      }
    } catch (error) {
      console.error('Error deleting order:', error);
    }
  };

  const attachEventListeners = () => {



    const editButtons = document.querySelectorAll('.edit-btn');
    const deleteButtons = document.querySelectorAll('.delete-btn');

    editButtons.forEach((button) => {
      button.addEventListener('click', (e) => {
        const orderId = e.target.getAttribute('data-id');
        editOrder(orderId);
      });
    });


    


    deleteButtons.forEach((button) => {
          
      button.addEventListener('click', (e) => {
        const orderId = e.target.getAttribute('data-id');
        if (!permissionUtils.hasPermission(userPermissions,ORDERS .DELETE_ORDERS)) {
          alert("you do not have permission to delete this order");
          
           return 0;
         }
        
        if (confirm('Are you sure you want to delete this order?')) {
          deleteOrder(orderId);
        }
      });
    });



  };

  const editOrder = async (orderId) => {
    try {
      const response = await fetch(`/api/order/${orderId}`);
      const order = await response.json();

    //  formTitle.textContent = 'Edit Order';
      orderIdInput.value = order._id;
      orderForm.itemName.value = order.itemName;
      orderForm.customerName.value = order.customerName;
      orderForm.advancePayment.value = order.advancePayment;
      orderForm.remainingPayment.value = order.remainingPayment;

      toggleForm(true);
    } catch (error) {
      console.error('Error fetching order:', error);
    }
  };

  orderForm.addEventListener('submit', (e) => {
    e.preventDefault();
    const paymentStatusCheckbox = document.getElementById('paymentStatus');
    const status = paymentStatusCheckbox.checked ? true : false;
    const orderId = orderIdInput.value;
    const orderData = {
      itemName: orderForm.itemName.value,
      customerName: orderForm.customerName.value,
      advancePayment: orderForm.advancePayment.value,
      remainingPayment: orderForm.remainingPayment.value,
       companyId,
       branchId,status
    };

    saveOrder(orderData, orderId);
  });

  viewOrdersBtn.addEventListener('click', () => {
    toggleForm(false);
    fetchOrders();
  });

  addOrderBtn.addEventListener('click', () => {
   // formTitle.textContent = 'Add New Order';
    orderIdInput.value = '';
    orderForm.reset();
    toggleForm(true);
  });

  // Initial fetch
  fetchOrders();
//});



function getGPSLocation(onSuccess, onError) {
 
  if ('geolocation' in navigator) {
   
    navigator.geolocation.getCurrentPosition(
      (position) => {
        const latitude = position.coords.latitude;
        const longitude = position.coords.longitude;
      
        // Send the location to your Node.js server
        fetch('/api/location', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ latitude, longitude }),
        })
          .then((response) => response.json())
          .then((data) => {
            console.log('Server Response:', data);
            if (onSuccess) {
              onSuccess(data); // Call the success callback
            }
          })
          .catch((err) => {
            console.error('Error sending location to server:', err);
            if (onError) {
              onError(err); // Call the error callback
            }
          });
      },
      (error) => {
        console.error('Error getting location:', error);
        if (onError) {
          onError(error); // Call the error callback
        }
      }
    );
  } else {
    const error = new Error('Geolocation is not supported by this browser.');
    console.error(error.message);
    if (onError) {
      onError(error); // Call the error callback
    }
  }
}

// getGPSLocation(
 
//   (data) => {
//     console.log('Location sent to server successfully:', data);
//   },
//   (error) => {
//     console.error('Failed to get or send location:', error);
//   }
// );

