<div class="main-content">
  <div class="container">
    <h2>Update Default Start Date</h2>
    <form id="settingsForm">
      <div class="form-group">
        <label for="companyName">Company Name</label>
        <input type="text" id="companyName" placeholder="Enter company name">
      </div>

      <div class="form-group">
        <label for="companyLogo">Company Logo</label>
        <div style="display: flex; flex-direction: column; gap: 10px;">
          <div style="display: flex; align-items: center; gap: 15px;">
            <img id="logoPreview" src="/uploads/cyber.jpeg" alt="Company Logo" style="max-width: 150px; max-height: 150px; border: 1px solid #ccc; border-radius: 4px; padding: 5px; object-fit: contain;">
            <div style="display: flex; flex-direction: column; gap: 10px;">
              <input type="file" id="companyLogo" accept="image/*" style="padding: 5px;">
              <button type="button" id="uploadLogoBtn" style="background-color: #007bff; color: white; border: none; padding: 8px 15px; border-radius: 4px; cursor: pointer; width: fit-content;">
                Upload Logo
              </button>
            </div>
          </div>
          <small style="color: #666;">Recommended: Square image, max 5MB (JPG, PNG, GIF)</small>
        </div>
      </div>

      <div class="form-group">
        <label for="defaultStartDate">Default Start Date</label>
        <input type="date" id="defaultStartDate">
      </div>

      <div class="form-group">
        <label for="startUpStockValue">Start-Up Stock Value</label>
        <input type="number" id="startUpStockValue">
      </div>

      
      <div class="form-group">
        <label for="defaultTimeOut">Time Out</label>
        <select id="defaultTimeOut" >
          <option value="2">2 Minutes</option>
          <option value="5">5 Minutes</option>
          <option value="10">10 Minutes</option>
          <option value="15">15 Minutes</option>
          <option value="30">30 Minutes</option>
          <option value="45">45 Minutes</option>
          <option value="60">1 Hour</option>
          <option value="90">1.5 Hours</option>
          <option value="120">2 Hours</option>
          <option value="180">3 Hours</option>
          <option value="240">4 Hours</option>
          <option value="360">6 Hours</option>
          <option value="480">8 Hours</option>
          <option value="720">12 Hours</option>
          <option value="1440">24 Hours</option>
        </select>
      </div>


      <div class="form-group">
        <label for="defaultSmsUser">Default SMS User</label>
        <select id="defaultSmsUser"></select>
      </div>

      <div class="form-group">
        <label for="kitchenAlertSound">Kitchen Alert Sound</label>
        <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
          <select id="kitchenAlertSound" style="padding: 5px 10px; border: 1px solid #ccc; border-radius: 4px;">
            <option value="beep">🔔 Simple Beep</option>
            <option value="chime">🎵 Pleasant Chime</option>
            <option value="ding">🔔 Kitchen Ding</option>
            <option value="notification">📢 Notification</option>
            <option value="bell">🛎️ Bell Ring</option>
            <option value="alert">🚨 Alert Tone</option>
          </select>
          <button type="button" id="testSoundBtn" style="background-color: #007bff; color: white; border: none; padding: 5px 10px; border-radius: 4px; cursor: pointer;">
            🔊 Test Sound
          </button>
          <button type="button" id="enableAudioBtn" style="background-color: #04b12a; color: white; border: none; padding: 5px 10px; border-radius: 4px; cursor: pointer;">
            🔔 Enable Audio
          </button>
          <span id="audioStatus" style="font-size: 14px; color: #666;"></span>
        </div>
      </div>

      <div class="form-group">
        <label for="printerIP">Kitchen Printer IP Address</label>
        <input type="text" id="printerIP" placeholder="192.168.20.100" style="padding: 8px; border: 1px solid #ccc; border-radius: 4px; width: 100%; max-width: 300px;">
        <small style="display: block; color: #666; margin-top: 5px;">Default: 192.168.20.100</small>
      </div>

      <div class="form-group">
        <label for="printerBridgeProtocol">Printer Bridge Protocol</label>
        <select id="printerBridgeProtocol" style="padding: 8px; border: 1px solid #ccc; border-radius: 4px; width: 100%; max-width: 300px;">
          <option value="http">HTTP</option>
          <option value="https">HTTPS</option>
        </select>
        <small style="display: block; color: #666; margin-top: 5px;">Default: HTTP (Use HTTPS if page is loaded over HTTPS)</small>
      </div>

      <div class="form-group">
        <label for="printerBridgeUrl">Printer Bridge IP Address</label>
        <input type="text" id="printerBridgeUrl" placeholder="localhost" style="padding: 8px; border: 1px solid #ccc; border-radius: 4px; width: 100%; max-width: 300px;">
        <small style="display: block; color: #666; margin-top: 5px;">Default: localhost (Enter IP address like 192.168.1.100 or localhost)</small>
      </div>

      <div class="form-group">
        <label for="printerBridgePort">Printer Bridge Port</label>
        <input type="number" id="printerBridgePort" placeholder="3000" style="padding: 8px; border: 1px solid #ccc; border-radius: 4px; width: 100%; max-width: 300px;">
        <small style="display: block; color: #666; margin-top: 5px;">Default: 3000</small>
      </div>

      <button type="submit">Save Settings</button>

      <div class="result" id="result"></div>
      <div class="error" id="error"></div>
    </form>
  </div>

  <script>
    document.addEventListener('DOMContentLoaded', async () => {
      const companyId = sessionStorage.getItem('companyId');
      const branchId = sessionStorage.getItem('branchId');

      if (!companyId || !branchId) {
        alert('Company or Branch not set in session.');
        return;
      }

      // Audio variables
      let audioEnabled = false;
      const testSoundBtn = document.getElementById('testSoundBtn');
      const enableAudioBtn = document.getElementById('enableAudioBtn');
      const audioStatus = document.getElementById('audioStatus');
      const kitchenAlertSound = document.getElementById('kitchenAlertSound');

      // Load saved sound preference from localStorage
      const savedSound = localStorage.getItem('kitchenAlertSound');
      if (savedSound) {
        kitchenAlertSound.value = savedSound;
      }

      // Get printer input elements
      const printerIPInput = document.getElementById('printerIP');
      const printerBridgeProtocolSelect = document.getElementById('printerBridgeProtocol');
      const printerBridgeUrlInput = document.getElementById('printerBridgeUrl');
      const printerBridgePortInput = document.getElementById('printerBridgePort');

      // Fetch users and populate dropdown
      await fetchUsers(companyId);

      try {
        // Fetch the current settings from the server
        const response = await fetch(`/api/settings?companyId=${companyId}&branchId=${branchId}`);
        const data = await response.json();

        if (response.ok ) {
          console.log(data);

          // Load general settings
          const formattedDate = data.defaultStartDate ? data.defaultStartDate.split('T')[0] : '';
          document.getElementById('companyName').value = data.companyName || 'Zad';
          document.getElementById('defaultStartDate').value = formattedDate;
          document.getElementById('startUpStockValue').value = data.startUpStockValue || '';
          document.getElementById('defaultSmsUser').value = data.defaultSmsUserId || '';
          document.getElementById('defaultTimeOut').value = data.defaultTimeOut || '';
          
          // Load and display company logo
          if (data.companyLogo) {
            const logoPreview = document.getElementById('logoPreview');
            if (logoPreview) {
              logoPreview.src = data.companyLogo;
            }
            localStorage.setItem('companyLogo', data.companyLogo);
          }
          
          // Store company name in localStorage
          if (data.companyName) {
            localStorage.setItem('companyName', data.companyName);
          }

          // Load printer settings from database first, then fallback to localStorage, then defaults
          const printerIP = data.kitchenPrinterIP || localStorage.getItem('kitchenPrinterIP') || '192.168.20.100';
          printerIPInput.value = printerIP;
          localStorage.setItem('kitchenPrinterIP', printerIP);

          const printerBridgeProtocol = data.kitchenPrinterBridgeProtocol || 
                                       localStorage.getItem('kitchenPrinterBridgeProtocol') || 
                                       (window.location.protocol === 'https:' ? 'https' : 'http');
          printerBridgeProtocolSelect.value = printerBridgeProtocol;
          localStorage.setItem('kitchenPrinterBridgeProtocol', printerBridgeProtocol);

          const printerBridgeIP = data.kitchenPrinterBridgeIP || 
                                 localStorage.getItem('kitchenPrinterBridgeIP') || 
                                 'localhost';
          printerBridgeUrlInput.value = printerBridgeIP;
          localStorage.setItem('kitchenPrinterBridgeIP', printerBridgeIP);

          const printerBridgePort = data.kitchenPrinterBridgePort || 
                                   localStorage.getItem('kitchenPrinterBridgePort') || 
                                   '3000';
          printerBridgePortInput.value = printerBridgePort;
          localStorage.setItem('kitchenPrinterBridgePort', printerBridgePort);
        } else {
          // If database fetch fails, load from localStorage with defaults
          const savedPrinterIP = localStorage.getItem('kitchenPrinterIP');
          printerIPInput.value = savedPrinterIP || '192.168.20.100';
          if (savedPrinterIP) localStorage.setItem('kitchenPrinterIP', savedPrinterIP);

          const savedPrinterBridgeProtocol = localStorage.getItem('kitchenPrinterBridgeProtocol');
          const defaultProtocol = window.location.protocol === 'https:' ? 'https' : 'http';
          printerBridgeProtocolSelect.value = savedPrinterBridgeProtocol || defaultProtocol;
          if (savedPrinterBridgeProtocol) localStorage.setItem('kitchenPrinterBridgeProtocol', savedPrinterBridgeProtocol);

          const savedPrinterBridgeIP = localStorage.getItem('kitchenPrinterBridgeIP');
          printerBridgeUrlInput.value = savedPrinterBridgeIP || 'localhost';
          if (savedPrinterBridgeIP) localStorage.setItem('kitchenPrinterBridgeIP', savedPrinterBridgeIP);

          const savedPrinterBridgePort = localStorage.getItem('kitchenPrinterBridgePort');
          printerBridgePortInput.value = savedPrinterBridgePort || '3000';
          if (savedPrinterBridgePort) localStorage.setItem('kitchenPrinterBridgePort', savedPrinterBridgePort);
        }
      } catch (error) {
        console.error('Error fetching settings:', error);
        // Fallback to localStorage on error
        const savedPrinterIP = localStorage.getItem('kitchenPrinterIP');
        printerIPInput.value = savedPrinterIP || '192.168.20.100';
        
        const savedPrinterBridgeProtocol = localStorage.getItem('kitchenPrinterBridgeProtocol');
        const defaultProtocol = window.location.protocol === 'https:' ? 'https' : 'http';
        printerBridgeProtocolSelect.value = savedPrinterBridgeProtocol || defaultProtocol;
        
        const savedPrinterBridgeIP = localStorage.getItem('kitchenPrinterBridgeIP');
        printerBridgeUrlInput.value = savedPrinterBridgeIP || 'localhost';
        
        const savedPrinterBridgePort = localStorage.getItem('kitchenPrinterBridgePort');
        printerBridgePortInput.value = savedPrinterBridgePort || '3000';
      }

      document.getElementById('settingsForm').addEventListener('submit', async function(e) {
        e.preventDefault();

        const companyName = document.getElementById('companyName').value;
        const defaultStartDate = document.getElementById('defaultStartDate').value;
        const startUpStockValue = document.getElementById('startUpStockValue').value;
        const defaultSmsUserId = document.getElementById('defaultSmsUser').value;
        const defaultTimeOut = document.getElementById('defaultTimeOut').value;
        
        // Save company name to localStorage immediately
        if (companyName) {
          localStorage.setItem('companyName', companyName);
        }
        
        // Get printer values
        const ipValue = printerIPInput.value.trim();
        const bridgeProtocolValue = printerBridgeProtocolSelect.value;
        const bridgeIPValue = printerBridgeUrlInput.value.trim();
        const bridgePortValue = printerBridgePortInput.value.trim();
        
        // Save printer settings to localStorage first (for immediate use by other pages)
        localStorage.setItem('kitchenPrinterIP', ipValue);
        localStorage.setItem('kitchenPrinterBridgeProtocol', bridgeProtocolValue);
        localStorage.setItem('kitchenPrinterBridgeIP', bridgeIPValue);
        localStorage.setItem('kitchenPrinterBridgePort', bridgePortValue);

        try {
          const response = await fetch('/api/settings', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ 
              companyId, 
              branchId, 
              companyName,
              defaultStartDate,
              defaultTimeOut, 
              startUpStockValue, 
              defaultSmsUserId,
              kitchenPrinterIP: ipValue,
              kitchenPrinterBridgeProtocol: bridgeProtocolValue,
              kitchenPrinterBridgeIP: bridgeIPValue,
              kitchenPrinterBridgePort: bridgePortValue
            })
          });

          const data = await response.json();

          if (response.ok) {
            document.getElementById('result').textContent = 'Settings updated successfully!';
            document.getElementById('result').style.display = 'block';
            document.getElementById('error').style.display = 'none';
          } else {
            document.getElementById('error').textContent = data.message || 'Error updating settings.';
            document.getElementById('error').style.display = 'block';
          }
        } catch (error) {
          document.getElementById('error').textContent = 'Server error occurred.';
          document.getElementById('error').style.display = 'block';
        }
      });

      // Audio Functions
      function enableAudio() {
        try {
          const audioContext = new (window.AudioContext || window.webkitAudioContext)();
          
          if (audioContext.state === 'suspended') {
            audioContext.resume();
          }
          
          const oscillator = audioContext.createOscillator();
          const gainNode = audioContext.createGain();
          
          oscillator.connect(gainNode);
          gainNode.connect(audioContext.destination);
          
          oscillator.frequency.setValueAtTime(1000, audioContext.currentTime);
          oscillator.type = 'sine';
          gainNode.gain.setValueAtTime(0.1, audioContext.currentTime);
          
          oscillator.start(audioContext.currentTime);
          oscillator.stop(audioContext.currentTime + 0.1);
          
          audioEnabled = true;
          audioStatus.textContent = '✅ Audio enabled';
          audioStatus.style.color = '#04b12a';
          enableAudioBtn.style.display = 'none';
          console.log('Audio enabled successfully');
          
        } catch (error) {
          console.log('Failed to enable audio:', error);
          audioStatus.textContent = '❌ Audio blocked by browser';
          audioStatus.style.color = '#e74c3c';
        }
      }

      function playSound(soundType) {
        try {
          const audioContext = new (window.AudioContext || window.webkitAudioContext)();
          const gainNode = audioContext.createGain();
          gainNode.connect(audioContext.destination);
          
          switch(soundType) {
            case 'beep':
              playBeep(audioContext, gainNode);
              break;
            case 'chime':
              playChime(audioContext, gainNode);
              break;
            case 'ding':
              playDing(audioContext, gainNode);
              break;
            case 'notification':
              playNotification(audioContext, gainNode);
              break;
            case 'bell':
              playBell(audioContext, gainNode);
              break;
            case 'alert':
              playAlert(audioContext, gainNode);
              break;
            default:
              playBeep(audioContext, gainNode);
          }
          
          console.log(`${soundType} sound played successfully`);
        } catch (error) {
          console.log('Error playing sound:', error);
        }
      }

      function playBeep(audioContext, gainNode) {
        const oscillator = audioContext.createOscillator();
        oscillator.connect(gainNode);
        
        oscillator.frequency.setValueAtTime(800, audioContext.currentTime);
        oscillator.type = 'sine';
        
        gainNode.gain.setValueAtTime(0, audioContext.currentTime);
        gainNode.gain.linearRampToValueAtTime(0.8, audioContext.currentTime + 0.2);
        gainNode.gain.linearRampToValueAtTime(0.8, audioContext.currentTime + 1.0);
        gainNode.gain.linearRampToValueAtTime(0, audioContext.currentTime + 1.5);
        
        oscillator.start(audioContext.currentTime);
        oscillator.stop(audioContext.currentTime + 1.5);
      }

      function playChime(audioContext, gainNode) {
        const osc1 = audioContext.createOscillator();
        const osc2 = audioContext.createOscillator();
        osc1.connect(gainNode);
        osc2.connect(gainNode);
        
        osc1.frequency.setValueAtTime(523, audioContext.currentTime);
        osc2.frequency.setValueAtTime(659, audioContext.currentTime + 0.3);
        osc1.type = 'sine';
        osc2.type = 'sine';
        
        gainNode.gain.setValueAtTime(0, audioContext.currentTime);
        gainNode.gain.linearRampToValueAtTime(0.6, audioContext.currentTime + 0.1);
        gainNode.gain.linearRampToValueAtTime(0.6, audioContext.currentTime + 0.8);
        gainNode.gain.linearRampToValueAtTime(0, audioContext.currentTime + 1.2);
        
        osc1.start(audioContext.currentTime);
        osc1.stop(audioContext.currentTime + 0.6);
        osc2.start(audioContext.currentTime + 0.3);
        osc2.stop(audioContext.currentTime + 0.9);
      }

      function playDing(audioContext, gainNode) {
        const oscillator = audioContext.createOscillator();
        oscillator.connect(gainNode);
        
        oscillator.frequency.setValueAtTime(1000, audioContext.currentTime);
        oscillator.type = 'triangle';
        
        gainNode.gain.setValueAtTime(0, audioContext.currentTime);
        gainNode.gain.linearRampToValueAtTime(0.7, audioContext.currentTime + 0.1);
        gainNode.gain.linearRampToValueAtTime(0.7, audioContext.currentTime + 0.4);
        gainNode.gain.linearRampToValueAtTime(0, audioContext.currentTime + 0.8);
        
        oscillator.start(audioContext.currentTime);
        oscillator.stop(audioContext.currentTime + 0.8);
      }

      function playNotification(audioContext, gainNode) {
        const oscillator = audioContext.createOscillator();
        oscillator.connect(gainNode);
        
        oscillator.frequency.setValueAtTime(400, audioContext.currentTime);
        oscillator.frequency.setValueAtTime(600, audioContext.currentTime + 0.2);
        oscillator.type = 'square';
        
        gainNode.gain.setValueAtTime(0, audioContext.currentTime);
        gainNode.gain.linearRampToValueAtTime(0.5, audioContext.currentTime + 0.1);
        gainNode.gain.linearRampToValueAtTime(0.5, audioContext.currentTime + 0.6);
        gainNode.gain.linearRampToValueAtTime(0, audioContext.currentTime + 1.0);
        
        oscillator.start(audioContext.currentTime);
        oscillator.stop(audioContext.currentTime + 1.0);
      }

      function playBell(audioContext, gainNode) {
        const oscillator = audioContext.createOscillator();
        oscillator.connect(gainNode);
        
        oscillator.frequency.setValueAtTime(800, audioContext.currentTime);
        oscillator.frequency.setValueAtTime(600, audioContext.currentTime + 0.1);
        oscillator.frequency.setValueAtTime(800, audioContext.currentTime + 0.2);
        oscillator.type = 'sine';
        
        gainNode.gain.setValueAtTime(0, audioContext.currentTime);
        gainNode.gain.linearRampToValueAtTime(0.6, audioContext.currentTime + 0.1);
        gainNode.gain.linearRampToValueAtTime(0.6, audioContext.currentTime + 0.8);
        gainNode.gain.linearRampToValueAtTime(0, audioContext.currentTime + 1.2);
        
        oscillator.start(audioContext.currentTime);
        oscillator.stop(audioContext.currentTime + 1.2);
      }

      function playAlert(audioContext, gainNode) {
        const oscillator = audioContext.createOscillator();
        oscillator.connect(gainNode);
        
        oscillator.frequency.setValueAtTime(300, audioContext.currentTime);
        oscillator.frequency.setValueAtTime(800, audioContext.currentTime + 0.2);
        oscillator.frequency.setValueAtTime(300, audioContext.currentTime + 0.4);
        oscillator.type = 'sawtooth';
        
        gainNode.gain.setValueAtTime(0, audioContext.currentTime);
        gainNode.gain.linearRampToValueAtTime(0.8, audioContext.currentTime + 0.1);
        gainNode.gain.linearRampToValueAtTime(0.8, audioContext.currentTime + 1.0);
        gainNode.gain.linearRampToValueAtTime(0, audioContext.currentTime + 1.5);
        
        oscillator.start(audioContext.currentTime);
        oscillator.stop(audioContext.currentTime + 1.5);
      }

      // Audio event listeners
      enableAudioBtn.addEventListener('click', enableAudio);
      testSoundBtn.addEventListener('click', () => {
        if (audioEnabled) {
          playSound(kitchenAlertSound.value);
        } else {
          alert('Please enable audio first!');
        }
      });

      // Save sound preference to localStorage when changed
      kitchenAlertSound.addEventListener('change', () => {
        localStorage.setItem('kitchenAlertSound', kitchenAlertSound.value);
      });

      // Save printer IP to localStorage when changed (allow empty values)
      printerIPInput.addEventListener('change', () => {
        const ipValue = printerIPInput.value.trim();
        localStorage.setItem('kitchenPrinterIP', ipValue);
      });

      // Save printer bridge protocol to localStorage when changed
      printerBridgeProtocolSelect.addEventListener('change', () => {
        const bridgeProtocolValue = printerBridgeProtocolSelect.value;
        localStorage.setItem('kitchenPrinterBridgeProtocol', bridgeProtocolValue);
      });

      // Save printer bridge IP to localStorage when changed (store only IP)
      printerBridgeUrlInput.addEventListener('change', () => {
        const bridgeIPValue = printerBridgeUrlInput.value.trim();
        localStorage.setItem('kitchenPrinterBridgeIP', bridgeIPValue);
      });

      // Save printer bridge port to localStorage when changed
      printerBridgePortInput.addEventListener('change', () => {
        const bridgePortValue = printerBridgePortInput.value.trim();
        localStorage.setItem('kitchenPrinterBridgePort', bridgePortValue);
      });

      // Logo upload functionality
      const logoInput = document.getElementById('companyLogo');
      const logoPreview = document.getElementById('logoPreview');
      const uploadLogoBtn = document.getElementById('uploadLogoBtn');

      // Preview logo when file is selected
      logoInput.addEventListener('change', (e) => {
        const file = e.target.files[0];
        if (file) {
          const reader = new FileReader();
          reader.onload = (e) => {
            logoPreview.src = e.target.result;
          };
          reader.readAsDataURL(file);
        }
      });

      // Upload logo button handler
      uploadLogoBtn.addEventListener('click', async () => {
        const file = logoInput.files[0];
        if (!file) {
          alert('Please select an image file first.');
          return;
        }

        const formData = new FormData();
        formData.append('logo', file);
        formData.append('companyId', companyId);
        formData.append('branchId', branchId);

        try {
          const response = await fetch('/api/settings/upload-logo', {
            method: 'POST',
            body: formData
          });

          const data = await response.json();

          if (response.ok) {
            // Update preview with the uploaded image path
            logoPreview.src = data.logoPath;
            localStorage.setItem('companyLogo', data.logoPath);
            alert('Logo uploaded successfully!');
          } else {
            alert(data.message || 'Error uploading logo. Please try again.');
          }
        } catch (error) {
          console.error('Error uploading logo:', error);
          alert('Error uploading logo. Please try again.');
        }
      });
    });

    async function fetchUsers(companyId) {
      try {
        const response = await fetch(`/api/users?companyId=${companyId}`);
        const users = await response.json();
        
        const userSelect = document.getElementById('defaultSmsUser');
        users.forEach((user) => {
          const option = document.createElement('option');
          option.value = user._id;
          option.textContent = user.username;
          userSelect.appendChild(option);
        });
      } catch (error) {
        console.error('Error:', error);
      }
    }
  </script>
</body>
</html>
