<?php $title=__('orders.create_order', 'Create Order'); ob_start(); ?>

<div class="d-flex justify-content-between align-items-center mb-4 flex-wrap flex-md-row flex-column">
    <h1 class="h3 mb-3">
        <i class="fas fa-receipt"></i> <?= __('orders.create_order', 'Create Order') ?>
    </h1>
    <div class="d-flex align-items-center gap-2">
       
        <a href="/samanta_crm/orders" class="btn btn-secondary">
            <i class="fas fa-arrow-left me-1"></i><?= __('common.back', 'Back') ?>
        </a>
    </div>
</div>

<div class="card-x">
    <div class="card-header py-2 d-flex">
        
         <span id="autoSaveIndicator" class="badge bg-secondary d-none ms-auto">
            <i class="fas fa-save me-1"></i><span id="autoSaveText"><?= __('orders.auto_saved', 'Auto-saved') ?></span>
        </span>
    </div>
    <div class="card-body">
        <form method="POST" action="/samanta_crm/orders" id="orderForm">
            <?php $order=[]; $items=[]; require __DIR__.'/form_fields.php'; ?>
        </form>
    </div>

</div>

<?php require __DIR__.'/items_modal.php'; ?>

<!-- Restore order modal -->
<div class="modal fade" id="restoreOrderModal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><i class="fas fa-history me-2"></i><?= __('orders.restore_order', 'Restore Order') ?></h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <p><?= __('orders.restore_order_message', 'An unsaved order was found in local storage. Do you want to restore it?') ?></p>
        <div class="alert alert-info mb-0">
          <small>
            <strong><?= __('orders.saved_at', 'Saved at') ?>:</strong> <span id="restoreSavedTime"></span><br>
            <strong><?= __('orders.items_count', 'Items') ?>:</strong> <span id="restoreItemsCount"></span>
          </small>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-danger" id="btnDiscardDraft">
          <i class="fas fa-trash me-1"></i><?= __('common.discard', 'Discard') ?>
        </button>
        <button type="button" class="btn btn-primary" id="btnRestoreDraft">
          <i class="fas fa-undo me-1"></i><?= __('common.restore', 'Restore') ?>
        </button>
      </div>
    </div>
  </div>


<script>
// Order auto-save functionality
(function() {
  const STORAGE_KEY = 'order_draft';
  const AUTO_SAVE_DELAY = 2000; // 2 seconds
  let autoSaveTimeout;
  let isRestoring = false;

  function showAutoSaveIndicator(text = '<?= __('orders.auto_saved', 'Auto-saved') ?>') {
    const indicator = document.getElementById('autoSaveIndicator');
    const textSpan = document.getElementById('autoSaveText');
    if(indicator && textSpan) {
      textSpan.textContent = text;
      indicator.classList.remove('d-none', 'bg-secondary', 'bg-success', 'bg-warning');
      indicator.classList.add('bg-success');
      setTimeout(() => {
        indicator.classList.remove('bg-success');
        indicator.classList.add('bg-secondary');
      }, 2000);
    }
  }

  function collectFormData() {
    const form = document.getElementById('orderForm');
    if(!form) return null;

    const data = {
      customer_id: form.querySelector('[name="customer_id"]')?.value || '',
      order_date: form.querySelector('[name="order_date"]')?.value || '',
      order_time: form.querySelector('[name="order_time"]')?.value || '',
      delivery_date: form.querySelector('[name="delivery_date"]')?.value || '',
      order_type: form.querySelector('[name="order_type"]')?.value || 'daily',
      status: form.querySelector('[name="status"]')?.value || 'pending',
      assigned_user_id: form.querySelector('[name="assigned_user_id"]')?.value || '',
      confirm_flag: form.querySelector('[name="confirm_flag"]')?.checked || false,
      notes: form.querySelector('[name="notes"]')?.value || '',
      signature: form.querySelector('[name="signature"]')?.value || '',
      items: [],
      savedAt: new Date().toISOString()
    };

    // Collect items
    const hiddenContainer = document.getElementById('orderItemsHidden');
    if(hiddenContainer) {
      hiddenContainer.querySelectorAll('.order-item-hidden').forEach(row => {
        const productId = row.querySelector('[name="item_product_id[]"]')?.value;
        const qty = row.querySelector('[name="item_qty[]"]')?.value;
        const name = row.querySelector('[name="item_name_snapshot[]"]')?.value;
        const code = row.querySelector('[name="item_code_snapshot[]"]')?.value;
        const units = row.querySelector('[name="item_units_snapshot[]"]')?.value;
        
        if(productId && qty) {
          data.items.push({productId, qty, name, code, units});
        }
      });
    }

    return data;
  }

  function saveToLocalStorage() {
    if(isRestoring) return; // Don't auto-save while restoring
    
    const data = collectFormData();
    if(!data) return;

    // Only save if there's meaningful data
    if(data.customer_id || data.items.length > 0 || data.notes) {
      try {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
        showAutoSaveIndicator();
      } catch(e) {
        console.error('Failed to save to localStorage:', e);
      }
    }
  }

  function scheduleAutoSave() {
    clearTimeout(autoSaveTimeout);
    autoSaveTimeout = setTimeout(saveToLocalStorage, AUTO_SAVE_DELAY);
  }

  function restoreFromLocalStorage(data) {
    isRestoring = true;
    const form = document.getElementById('orderForm');
    if(!form || !data) return;

    // Restore basic fields
    if(data.customer_id) {
      const customerSelect = form.querySelector('[name="customer_id"]');
      if(customerSelect) {
        customerSelect.value = data.customer_id;
        customerSelect.dispatchEvent(new Event('change')); // Trigger customer change event
      }
    }
    if(data.order_date) {
      const orderDateEl = form.querySelector('[name="order_date"]');
      if(orderDateEl) orderDateEl.value = data.order_date;
    }
    if(data.order_time) {
      const orderTimeEl = form.querySelector('[name="order_time"]');
      if(orderTimeEl) orderTimeEl.value = data.order_time;
    }
    if(data.delivery_date) {
      const deliveryDateEl = form.querySelector('[name="delivery_date"]');
      if(deliveryDateEl) deliveryDateEl.value = data.delivery_date;
    }
    if(data.order_type) {
      const orderTypeEl = form.querySelector('[name="order_type"]');
      if(orderTypeEl) orderTypeEl.value = data.order_type;
    }
    if(data.status) {
      const statusEl = form.querySelector('[name="status"]');
      if(statusEl) statusEl.value = data.status;
    }
    if(data.assigned_user_id) {
      const assignedUserEl = form.querySelector('[name="assigned_user_id"]');
      if(assignedUserEl) assignedUserEl.value = data.assigned_user_id;
    }
    if(data.confirm_flag) {
      const confirmEl = form.querySelector('[name="confirm_flag"]');
      if(confirmEl) confirmEl.checked = true;
    }
    if(data.notes) {
      const notesEl = form.querySelector('[name="notes"]');
      if(notesEl) notesEl.value = data.notes;
    }
    if(data.signature) {
      const signatureEl = form.querySelector('[name="signature"]');
      if(signatureEl) signatureEl.value = data.signature;
    }

    // Restore items - need to wait for modal script to be ready
    if(data.items && data.items.length > 0) {
      setTimeout(() => {
        const hiddenContainer = document.getElementById('orderItemsHidden');
        if(hiddenContainer && window.syncHiddenRow) {
          data.items.forEach(item => {
            window.syncHiddenRow(item.productId, item.qty, item.name, item.code, item.units);
            
            // Update checkboxes and quantities in modal
            const checkbox = document.querySelector(`.item-check[data-id="${item.productId}"]`);
            const qtyInput = document.querySelector(`.item-qty[data-id="${item.productId}"]`);
            if(checkbox) checkbox.checked = true;
            if(qtyInput) qtyInput.value = parseFloat(item.qty).toFixed(1);
          });
          
          if(window.updateSummary) window.updateSummary();
        }
      }, 100);
    }

    showAutoSaveIndicator('<?= __('orders.restored', 'Restored') ?>');
    isRestoring = false;
  }

  function checkForSavedDraft() {
    try {
      const saved = localStorage.getItem(STORAGE_KEY);
      if(!saved) return;

      const data = JSON.parse(saved);
      
      // Show restore modal
      const restoreModal = document.getElementById('restoreOrderModal');
      if(restoreModal) {
        const savedTime = new Date(data.savedAt);
        document.getElementById('restoreSavedTime').textContent = savedTime.toLocaleString('pl-PL');
        document.getElementById('restoreItemsCount').textContent = data.items?.length || 0;
        
        const modal = new bootstrap.Modal(restoreModal);
        modal.show();

        // Restore button
        document.getElementById('btnRestoreDraft').onclick = function() {
          restoreFromLocalStorage(data);
          modal.hide();
        };

        // Discard button
        document.getElementById('btnDiscardDraft').onclick = function() {
          localStorage.removeItem(STORAGE_KEY);
          modal.hide();
        };
      }
    } catch(e) {
      console.error('Failed to check for saved draft:', e);
      localStorage.removeItem(STORAGE_KEY);
    }
  }

  function clearDraft() {
    localStorage.removeItem(STORAGE_KEY);
  }

  // Initialize
  document.addEventListener('DOMContentLoaded', function() {
    // Check for saved draft
    checkForSavedDraft();

    // Add auto-save listeners
    const form = document.getElementById('orderForm');
    if(form) {
      // Listen to all form inputs
      form.addEventListener('input', scheduleAutoSave);
      form.addEventListener('change', scheduleAutoSave);

      // Clear draft on successful submit
      form.addEventListener('submit', function(e) {
        // Don't prevent default - let form submit normally
        // Clear draft after a short delay to ensure submission succeeded
        setTimeout(clearDraft, 1000);
      });
    }

    // Listen to item changes from modal
    document.addEventListener('itemsChanged', scheduleAutoSave);

    // Warn before leaving if there's unsaved data
    window.addEventListener('beforeunload', function(e) {
      const data = collectFormData();
      if(data && (data.customer_id || data.items.length > 0 || data.notes)) {
        e.preventDefault();
        e.returnValue = '<?= __('orders.unsaved_changes', 'You have unsaved changes. Are you sure you want to leave?') ?>';
        return e.returnValue;
      }
    });
  });

  // Expose functions globally for modal script
  window.orderAutoSave = {
    save: saveToLocalStorage,
    scheduleSave: scheduleAutoSave,
    clear: clearDraft
  };
})();
</script>

<?php $content=ob_get_clean(); require __DIR__.'/../layout.php'; ?>
