common.js

9.35 KB
27/04/2025 16:44
JS
common.js
document.addEventListener('DOMContentLoaded', function() {
  // Check authentication
  const token = localStorage.getItem('posToken');
  if (!token) {
    window.location.href = `${basePath}/index.html`;
    return;
  }

  // Toggle user dropdown
  const userDropdown = document.querySelector('.user-dropdown-toggle');
  if (userDropdown) {
    userDropdown.addEventListener('click', function(e) {
      e.preventDefault();
      e.stopPropagation(); // หยุดการ propagate event ไปยัง document
      const dropdownMenu = document.querySelector('.user-dropdown-menu');
      dropdownMenu.classList.toggle('show');
    });
  }

  // Prevent dropdown close when clicking on dropdown menu items
  const dropdownMenu = document.querySelector('.user-dropdown-menu');
  if (dropdownMenu) {
    dropdownMenu.addEventListener('click', function(e) {
      // อนุญาตให้ click ที่ logout ทำงานได้ แต่ป้องกันการปิด dropdown เมื่อคลิกที่เมนูอื่น
      if (!e.target.matches('#logoutBtn') && !e.target.closest('#logoutBtn')) {
        e.stopPropagation();
      }
    });
  }

  // Toggle sidebar (responsive)
  const toggleSidebar = document.querySelector('.toggle-sidebar');
  if (toggleSidebar) {
    toggleSidebar.addEventListener('click', function() {
      document.querySelector('.sidebar').classList.toggle('collapsed');
      document.querySelector('.content-area').classList.toggle('expanded');
    });
  }

  // Setup profile link
  const profileLink = document.querySelector('.user-dropdown-menu a[href="#"]:first-child');
  if (profileLink) {
    profileLink.addEventListener('click', function(e) {
      e.preventDefault();
      openProfileModal();
    });
  }

  // Change password button
  const changePasswordBtn = document.getElementById('changePasswordBtn');
  if (changePasswordBtn) {
    changePasswordBtn.addEventListener('click', function(e) {
      e.preventDefault();
      localStorage.removeItem('posToken');
      localStorage.removeItem('posUser');
      window.location.href = `${basePath}/index.html`;
    });
  }

  // Set user name
  const userJson = localStorage.getItem('posUser');
  if (userJson) {
    const user = JSON.parse(userJson);
    const userNameElem = document.querySelector('.user-name');
    if (userNameElem) {
      userNameElem.textContent = user.full_name || user.username;
    }
  }

  // Logout button
  const logoutBtn = document.getElementById('logoutBtn');
  if (logoutBtn) {
    logoutBtn.addEventListener('click', function(e) {
      e.preventDefault();
      localStorage.removeItem('posToken');
      localStorage.removeItem('posUser');
      window.location.href = `${basePath}/index.html`;
    });
  }
});

// API Request helper
async function apiRequest(endpoint, method = 'GET', data = null) {
  const token = localStorage.getItem('posToken');
  const headers = {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${token}`
  };

  const options = {
    method,
    headers
  };

  if (data && (method === 'POST' || method === 'PUT')) {
    options.body = JSON.stringify(data);
  }

  try {
    console.log(`API Request to: ${apiPath}/${endpoint}`, options); // Debug line

    const response = await fetch(`${apiPath}/${endpoint}`, options);
    const result = await response.json();

    console.log('API Response:', result); // Debug line

    if (!response.ok) {
      // Handle unauthorized (token expired)
      if (response.status === 401) {
        localStorage.removeItem('posToken');
        localStorage.removeItem('posUser');
        window.location.href = `${basePath}/index.html`;
        return {status: 'error', message: 'Session expired. Please login again.'};
      }

      throw new Error(result.message || 'API request failed');
    }

    return result;
  } catch (error) {
    console.error('API Request Error:', error);
    return {status: 'error', message: error.message};
  }
}

// Format currency
function formatCurrency(amount) {
  return new Intl.NumberFormat('th-TH', {
    style: 'currency',
    currency: 'THB',
    minimumFractionDigits: 2
  }).format(amount);
}

function showNotification(message, type = 'info') {
  const container = document.getElementById('notification-container');

  if (!container) return;

  const notification = document.createElement('div');
  notification.className = `notification notification-${type}`;
  notification.innerHTML = `
      <div class="notification-message">${message}</div>
      <button class="notification-close">&times;</button>
  `;

  container.appendChild(notification);

  // Auto remove after 5 seconds
  setTimeout(() => {
    if (notification.parentNode) {
      notification.parentNode.removeChild(notification);
    }
  }, 5000);

  // Close button
  const closeBtn = notification.querySelector('.notification-close');
  if (closeBtn) {
    closeBtn.addEventListener('click', () => {
      if (notification.parentNode) {
        notification.parentNode.removeChild(notification);
      }
    });
  }
}

function openProfileModal() {
  // ตรวจสอบว่า modal มีอยู่แล้วหรือไม่
  let profileModal = document.getElementById('profileModal');

  // ถ้ายังไม่มี modal ให้สร้างใหม่
  if (!profileModal) {
    // สร้าง modal element
    profileModal = document.createElement('div');
    profileModal.id = 'profileModal';
    profileModal.className = 'modal';

    // สร้าง HTML content สำหรับ modal
    profileModal.innerHTML = `
      <div class="modal-content modal-sm">
        <div class="modal-header">
          <h2>Edit Profile</h2>
          <button class="close-modal">&times;</button>
        </div>
        <div class="modal-body">
          <form id="profileForm">
            <div class="form-group">
              <label for="profileUsername">Username</label>
              <input type="text" id="profileUsername" class="form-control" disabled>
            </div>
            <div class="form-group">
              <label for="profileFullName">Full Name</label>
              <input type="text" id="profileFullName" class="form-control" required>
            </div>
            <div class="form-group">
              <label for="profileEmail">Email</label>
              <input type="email" id="profileEmail" class="form-control" required>
            </div>
            <div class="form-group">
              <label for="profileRole">Role</label>
              <input type="text" id="profileRole" class="form-control" disabled>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" id="cancelProfileBtn">Cancel</button>
          <button class="btn btn-primary" id="saveProfileBtn">Save Changes</button>
        </div>
      </div>
    `;

    // เพิ่ม modal เข้าไปใน document
    document.body.appendChild(profileModal);

    // เพิ่ม event listeners สำหรับปุ่ม
    document.querySelector('#profileModal .close-modal').addEventListener('click', function() {
      profileModal.classList.remove('show');
    });

    document.getElementById('cancelProfileBtn').addEventListener('click', function() {
      profileModal.classList.remove('show');
    });

    document.getElementById('saveProfileBtn').addEventListener('click', saveProfileChanges);
  }

  // ดึงข้อมูลผู้ใช้จาก localStorage
  const userJson = localStorage.getItem('posUser');
  if (userJson) {
    const user = JSON.parse(userJson);

    // กรอกข้อมูลในฟอร์ม
    document.getElementById('profileUsername').value = user.username || '';
    document.getElementById('profileFullName').value = user.full_name || '';
    document.getElementById('profileEmail').value = user.email || '';
    document.getElementById('profileRole').value = user.role || '';
  }

  // แสดง modal
  profileModal.classList.add('show');
}

// Function to save profile changes
async function saveProfileChanges() {
  try {
    const fullName = document.getElementById('profileFullName').value;
    const email = document.getElementById('profileEmail').value;

    if (!fullName || !email) {
      showNotification('Please fill in all required fields', 'error');
      return;
    }

    const response = await apiRequest('users/profile', 'PUT', {
      full_name: fullName,
      email: email
    });

    if (response.status === 'success') {
      // อัพเดตข้อมูลใน localStorage
      const userJson = localStorage.getItem('posUser');
      if (userJson) {
        const user = JSON.parse(userJson);
        user.full_name = fullName;
        user.email = email;
        localStorage.setItem('posUser', JSON.stringify(user));

        // อัพเดตชื่อที่แสดงบน UI
        const userNameElem = document.querySelector('.user-name');
        if (userNameElem) {
          userNameElem.textContent = fullName || user.username;
        }
      }

      showNotification('Profile updated successfully', 'success');
      document.getElementById('profileModal').classList.remove('show');
    } else {
      showNotification(response.message || 'Failed to update profile', 'error');
    }
  } catch (error) {
    console.error('Error updating profile:', error);
    showNotification('Error updating profile: ' + error.message, 'error');
  }
}