<!DOCTYPE html>
<html lang="th">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
  <title>Employee Directory</title>
  
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css2?family=Sarabun:wght@300;400;500;600&display=swap" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet">
  
  <style>
    body { background-color: #1a1c1e; color: #e2e2e6; font-family: 'Sarabun', sans-serif; margin: 0; -webkit-tap-highlight-color: transparent; }
    .header-box { padding: 15px; position: sticky; top: 0; background: #1a1c1e; z-index: 100; border-bottom: 0.5px solid #333; }
    .search-wrapper { background: #2f3033; border-radius: 28px; padding: 5px 20px; display: flex; align-items: center; height: 48px; }
    .search-wrapper input { border: none !important; color: white !important; margin: 0 !important; box-shadow: none !important; font-size: 16px; font-family: 'Sarabun', sans-serif; }
    .section-title { padding: 15px 20px 5px; font-size: 0.9rem; color: #d1e4ff; display: flex; align-items: center; font-weight: 500; }
    .section-title i { font-size: 1.1rem; margin-right: 8px; }
    .contact-item { padding: 12px 20px; display: flex; align-items: center; border-radius: 12px; margin: 4px 10px; cursor: pointer; transition: background 0.2s; }
    .contact-item:active, .contact-item:hover { background: #2f3033; }
    .avatar { width: 44px; height: 44px; border-radius: 50%; object-fit: cover; margin-right: 16px; background: #444; }
    .contact-name { flex-grow: 1; font-size: 1rem; }
    
    /* Skeleton รอโหลดข้อมูล */
    @keyframes shimmer { 0% { background-position: -468px 0; } 100% { background-position: 468px 0; } }
    .skeleton-item { background: #2f3033; background-image: linear-gradient(to right, #2f3033 0%, #3e4043 20%, #2f3033 40%, #2f3033 100%); background-repeat: no-repeat; background-size: 800px 100%; display: flex; align-items: center; padding: 12px 20px; margin: 4px 10px; border-radius: 12px; animation: shimmer 1.5s infinite linear forwards; }
    .skeleton-avatar { width: 44px; height: 44px; border-radius: 50%; background: #444; margin-right: 16px; }
    .skeleton-text { height: 14px; background: #444; border-radius: 4px; width: 60%; }

    /* Modal หน้าโปรไฟล์พนักงาน */
    .modal.profile-modal { background-color: #1a1c1e; border-radius: 24px 24px 0 0 !important; max-height: 95% !important; bottom: 0 !important; top: auto !important; }
    .profile-header { text-align: center; padding: 10px 20px 10px; }
    .big-avatar { width: 120px; height: 120px; border-radius: 50%; object-fit: cover; margin-bottom: 16px; border: 2px solid #3e4043; background: #444; }
    
    .action-row { display: flex; justify-content: center; gap: 30px; padding: 10px 20px 20px; }
    .action-circle { display: flex; flex-direction: column; align-items: center; cursor: pointer; width: 65px; }
    .icon-bg { background: #3e4043; width: 56px; height: 56px; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin-bottom: 8px; transition: background 0.2s; }
    .action-circle:active .icon-bg { background: #505256; }
    .icon-bg i { color: #d1e4ff; font-size: 24px; }
    .action-label { font-size: 0.8rem; color: #c4c6cf; }

    #qrcode-container { display: none; flex-direction: column; align-items: center; padding: 20px; background: white; margin: 15px 20px; border-radius: 16px; text-align: center; }
    #qrcode img { margin: 0 auto; border: 4px solid white; }
    .qr-label { color: #1a1c1e; margin-top: 10px; font-weight: bold; font-size: 0.8rem; }

    .info-container { background: #2f3033; border-radius: 16px; margin: 10px 20px; padding: 16px; display: flex; align-items: center; cursor: pointer; }
    .info-icon { color: #d1e4ff; margin-right: 16px; }
    .btn-save { background-color: #0061a4 !important; width: 100%; border-radius: 25px; height: 48px; margin-top: 15px; text-transform: none; font-weight: 500; font-family: 'Sarabun', sans-serif; }
    .btn-delete-full { background-color: #ba1a1a !important; width: 100%; border-radius: 25px; height: 48px; margin-top: 10px; text-transform: none; font-weight: 500; font-family: 'Sarabun', sans-serif; }
    input { color: white !important; font-family: 'Sarabun', sans-serif; }
    label { color: #c4c6cf !important; font-family: 'Sarabun', sans-serif; }
    #loader { position: fixed; top: 0; left: 0; width: 100%; height: 4px; z-index: 1001; }
    
    .file-field .btn { background-color: #3e4043 !important; border-radius: 8px; line-height: 36px; height: 36px; text-transform: none; }
    .file-field .file-path-wrapper input { font-size: 14px; }
  </style>
</head>
<body>

  <div id="loader" class="progress blue hide"><div class="indeterminate"></div></div>

  <div class="header-box">
    <div class="search-wrapper">
      <i class="material-icons" style="color:#c4c6cf">search</i>
      <input type="text" id="search" placeholder="ค้นหารายชื่อพนักงาน..." onkeyup="filterData()">
    </div>
  </div>

  <div id="fav-section" class="hide">
    <div class="section-title"><i class="material-icons" style="color:#fbbc04">star</i> รายการโปรด</div>
    <div id="fav-list"></div>
    <div style="border-bottom: 0.5px solid #333; margin: 10px 20px;"></div>
  </div>

  <div class="section-title"><i class="material-icons">person</i> รายชื่อทั้งหมด</div>
  <div id="employee-list"></div>

  <div class="fixed-action-btn">
    <a class="btn-floating btn-large blue modal-trigger" href="#modal-edit" onclick="resetForm()">
      <i class="material-icons">add</i>
    </a>
  </div>

  <div id="modal-detail" class="modal profile-modal">
    <div class="modal-content" style="padding:0">
      <div style="padding: 15px; display: flex; justify-content: space-between; align-items: center;">
        <i class="material-icons modal-close" style="cursor:pointer">close</i>
        <div style="display: flex; gap: 20px; cursor:pointer">
          <i class="material-icons" id="view-fav-icon">star_border</i>
          <i class="material-icons" id="btn-edit-trigger">edit</i>
        </div>
      </div>
      
      <div class="profile-header">
        <img id="view-img" src="" class="big-avatar" onerror="this.src='https://ui-avatars.com/api/?background=random&name=User'">
        <div id="view-name" style="font-size: 1.4rem; font-weight: 500;"></div>
        <div id="view-id" style="color: #888; font-size: 0.8rem; margin-top: 2px;"></div>
        <div id="view-dept-div" style="color: #c4c6cf; margin-top:5px;"></div>
        <div id="view-pos" style="color: #888; font-size: 0.9rem;"></div>
      </div>

      <div class="action-row">
        <div class="action-circle" onclick="handleCall()"><div class="icon-bg"><i class="material-icons">phone</i></div><span class="action-label">โทร</span></div>
        <div class="action-circle" onclick="handleSMS()"><div class="icon-bg"><i class="material-icons">chat_bubble</i></div><span class="action-label">ข้อความ</span></div>
        <div class="action-circle" onclick="toggleQRCode()"><div class="icon-bg"><i class="material-icons">qr_code_2</i></div><span class="action-label">แชร์ QR</span></div>
      </div>

      <div id="qrcode-container">
        <div id="qrcode"></div>
        <div class="qr-label">สแกนผ่านกล้องมือถือเพื่อบันทึกผู้ติดต่อ</div>
      </div>

      <div class="info-container" onclick="handleCall()">
        <i class="material-icons info-icon">phone</i>
        <div id="view-phone" style="flex-grow:1; font-size: 1.1rem;"></div>
        <i class="material-icons" style="color:#c4c6cf">chevron_right</i>
      </div>
    </div>
  </div>

  <div id="modal-edit" class="modal" style="background:#1a1c1e; border-radius: 16px;">
    <div class="modal-content">
      <h5 id="form-title" style="color:white; margin-bottom:20px;">ข้อมูลพนักงาน</h5>
      <form id="empForm" enctype="multipart/form-data">
        <input type="hidden" id="isFavField" value="false">
        <input type="hidden" id="currentImg" value="">
        
        <div class="input-field"><input type="text" id="empId" required><label>ID พนักงาน</label></div>
        <div class="input-field"><input type="text" id="name" required><label>ชื่อ-นามสกุล</label></div>
        <div class="input-field"><input type="tel" id="phone"><label>เบอร์โทร</label></div>
        <div class="input-field"><input type="text" id="dept"><label>ฝ่าย</label></div>
        <div class="input-field"><input type="text" id="div"><label>แผนก</label></div>
        <div class="input-field"><input type="text" id="pos"><label>ตำแหน่ง</label></div>
        
        <div class="file-field input-field">
          <div class="btn">
            <span>เลือกรูปภาพ</span>
            <input type="file" id="imgFile" accept="image/*">
          </div>
          <div class="file-path-wrapper">
            <input class="file-path validate" type="text" placeholder="อัปโหลดรูปภาพประจำตัว (.jpg, .png)">
          </div>
        </div>
        
        <button type="submit" id="submit-btn" class="btn btn-save">บันทึกข้อมูล</button>
        <button type="button" id="btn-delete" class="btn btn-delete-full">ลบรายชื่อพนักงานนี้</button>
      </form>
    </div>
  </div>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>

  <script>
    let allData = [];
    let currentEmployeeData = null;
    let currentPhone = "";
    const API_URL = "api.php";

    document.addEventListener('DOMContentLoaded', () => {
      M.Modal.init(document.querySelectorAll('.modal'));
      loadData();
    });

    function showSkeleton() {
      const mainList = document.getElementById('employee-list');
      mainList.innerHTML = `<div class="skeleton-item"><div class="skeleton-avatar"></div><div class="skeleton-text"></div></div>`.repeat(6);
    }

    function loadData() {
      document.getElementById('loader').classList.remove('hide');
      showSkeleton();
      
      fetch(`${API_URL}?action=getEmployees`)
        .then(res => res.json())
        .then(data => {
          allData = data;
          renderLists(data);
          document.getElementById('loader').classList.add('hide');
        })
        .catch(err => {
          M.toast({html: 'ไม่สามารถโหลดข้อมูลได้'});
          document.getElementById('loader').classList.add('hide');
        });
    }

    function renderLists(data) {
      const mainList = document.getElementById('employee-list');
      const favList = document.getElementById('fav-list');
      mainList.innerHTML = ''; favList.innerHTML = '';
      let hasFav = false;

      for (let i = 0; i < data.length; i++) {
        const emp = data[i];
        const tags = `${emp.emp_id} ${emp.name} ${emp.dept} ${emp.division} ${emp.phone}`.toLowerCase();
        const fallback = `https://ui-avatars.com/api/?background=random&name=${encodeURIComponent(emp.name)}`;
        const imgSrc = emp.img ? `uploads/${emp.img}` : fallback;

        const html = `
          <div class="contact-item" onclick="showDetail(${i})" data-search="${tags}">
            <img src="${imgSrc}" class="avatar" onerror="this.src='${fallback}'">
            <div class="contact-name">${emp.name}</div>
            ${emp.is_fav ? '<i class="material-icons" style="color:#fbbc04; font-size:18px">star</i>' : ''}
          </div>`;
          
        mainList.innerHTML += html;
        if (emp.is_fav) { favList.innerHTML += html; hasFav = true; }
      }
      document.getElementById('fav-section').classList.toggle('hide', !hasFav);
    }

    function showDetail(index) {
      const emp = allData[index];
      currentEmployeeData = emp;
      currentPhone = emp.phone ? emp.phone.toString().replace(/[^0-9+]/g, '') : '';
      const fallback = `https://ui-avatars.com/api/?background=random&name=${encodeURIComponent(emp.name)}`;
      
      document.getElementById('view-name').innerText = emp.name;
      document.getElementById('view-id').innerText = "ID: " + emp.emp_id;
      document.getElementById('view-dept-div').innerText = `${emp.dept || ''} / ${emp.division || ''}`;
      document.getElementById('view-pos').innerText = emp.pos || '';
      document.getElementById('view-phone').innerText = emp.phone || 'ไม่ระบุเบอร์โทรศัพท์';
      document.getElementById('view-img').src = emp.img ? `uploads/${emp.img}` : fallback;
      document.getElementById('qrcode-container').style.display = 'none';

      const favIcon = document.getElementById('view-fav-icon');
      favIcon.innerText = emp.is_fav ? 'star' : 'star_border';
      favIcon.style.color = emp.is_fav ? '#fbbc04' : '#e2e2e6';
      
      favIcon.onclick = () => {
        document.getElementById('loader').classList.remove('hide');
        M.Modal.getInstance(document.getElementById('modal-detail')).close();
        
        fetch(`${API_URL}?action=toggleFavorite`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ empId: emp.emp_id, isFav: !emp.is_fav })
        })
        .then(res => res.json()).then(() => loadData());
      };

      document.getElementById('btn-edit-trigger').onclick = () => {
        M.Modal.getInstance(document.getElementById('modal-detail')).close();
        openEdit(emp);
      };
      M.Modal.getInstance(document.getElementById('modal-detail')).open();
    }

    // 🌟 แก้ไขฟังก์ชันสำหรับ DAVID SHIM QRCODE.JS ข้อมูลภาษาไทยหนาแน่นสูงโดยเฉพาะ 🌟
// 🌟 เวอร์ชันอัปเกรด: บีบอัดข้อมูลและขยายความจุโครงสร้าง QR ให้สูงสุด 🌟
    function toggleQRCode() {
      const container = document.getElementById('qrcode-container');
      const qrElement = document.getElementById('qrcode');
      
      if (container.style.display === 'flex') {
        container.style.display = 'none';
        return;
      }

      if (typeof QRCode === 'undefined') {
         M.toast({html: 'ระบบกำลังโหลดไลบรารี QR Code... กรุณาลองใหม่อีกครั้ง'});
         return;
      }

      container.style.display = 'flex';
      qrElement.innerHTML = `<div style="color:#1a1c1e; font-size:12px; padding:10px;">กำลังสร้าง QR Code...</div>`; 
      
      // คลีนข้อความ ป้องกันอักขระพิเศษพังโครงสร้าง
      const cleanText = (str) => {
        if (!str) return '';
        return str.toString().replace(/[\r\n;,:]/g, ' ').trim();
      };

      const name = cleanText(currentEmployeeData.name);
      const phone = cleanText(currentEmployeeData.phone);
      const dept = cleanText(currentEmployeeData.dept);
      const pos = cleanText(currentEmployeeData.pos);
      
      // ลดขนาด vCard ลงให้กระชับที่สุด (ตัดฟิลด์ VERSION เหลือ 2.1 และรวม ORG/TITLE เพื่อลดพื้นที่)
      const vCard = `BEGIN:VCARD\nVERSION:2.1\nFN;CHARSET=UTF-8:${name}\nTEL;CELL:${phone}\nORG;CHARSET=UTF-8:${dept} ${pos}\nEND:VCARD`;
      
      setTimeout(() => {
        try {
          qrElement.innerHTML = ""; // ล้างตัวอักษร "กำลังสร้าง"
          
          // แปลงข้อความภาษาไทยให้เข้ากันได้กับโครงสร้างเบราว์เซอร์
          const safeVCard = unescape(encodeURIComponent(vCard));

          // เคลียร์และสร้าง Instance ใหม่โดยตรงเพื่อล้างบั๊กหน่วยความจำเต็มของ qrcode.js
          const qr = new QRCode(qrElement, {
            text: safeVCard,
            width: 200,              // ขยายพื้นที่วาดภาพเป็น 200x200 เพื่อเพิ่มความละเอียดจุด
            height: 200,
            colorDark : "#000000",
            colorLight : "#ffffff",
            // ใช้ CorrectLevel.L (Low 7%) เพื่อลดจุดพิกเซลที่ซ้ำซ้อน ช่วยให้พื้นที่ตารางเหลือเยอะขึ้น 
            // และทำให้สแกนติดง่ายขึ้นมากเมื่อข้อมูลหนาแน่น
            correctLevel : QRCode.CorrectLevel.L 
          });

          setTimeout(() => container.scrollIntoView({ behavior: 'smooth', block: 'end' }), 150);
        } catch(e) {
          console.error("QRCode Premium Crash Log:", e);
          
          // แผนสำรอง (Fallback): หากชื่อยาวมากจนพังจริงๆ ระบบจะตัดเหลือเฉพาะ "ชื่อ + เบอร์โทร" เพื่อให้ใช้งานสแกนเมมเบอร์ได้แน่นอน
          try {
            qrElement.innerHTML = "";
            const backupVCard = unescape(encodeURIComponent(`BEGIN:VCARD\nVERSION:2.1\nFN;CHARSET=UTF-8:${name}\nTEL;CELL:${phone}\nEND:VCARD`));
            new QRCode(qrElement, { text: backupVCard, width: 200, height: 200, correctLevel: QRCode.CorrectLevel.L });
          } catch(err) {
            qrElement.innerHTML = `<span style="color:#ba1a1a; font-size:12px; font-weight:bold;">ไม่สามารถสร้าง QR Code ได้<br>เนื่องจากชื่อยาวเกินไป</span>`;
          }
        }
      }, 50);
    }
    function handleCall() { if(currentPhone) window.location.href = "tel:" + currentPhone; }
    function handleSMS() { if(currentPhone) window.location.href = "sms:" + currentPhone; }

    function openEdit(emp) {
      document.getElementById('form-title').innerText = "แก้ไขข้อมูลพนักงาน";
      document.getElementById('empId').value = emp.emp_id;
      document.getElementById('empId').readOnly = true; 
      document.getElementById('name').value = emp.name;
      document.getElementById('phone').value = emp.phone || '';
      document.getElementById('dept').value = emp.dept || '';
      document.getElementById('div').value = emp.division || '';
      document.getElementById('pos').value = emp.pos || '';
      document.getElementById('currentImg').value = emp.img || ''; 
      document.getElementById('imgFile').value = ''; 
      document.querySelector('.file-path').value = emp.img ? 'มีรูปภาพเดิมอยู่แล้ว (' + emp.img + ')' : '';
      document.getElementById('isFavField').value = emp.is_fav; 
      document.getElementById('btn-delete').style.display = 'block';
      
      M.updateTextFields();
      
      document.getElementById('btn-delete').onclick = () => {
        if(confirm(`คุณต้องการลบรายชื่อของคุณ "${emp.name}" ใช่หรือไม่?`)) {
          document.getElementById('loader').classList.remove('hide');
          M.Modal.getInstance(document.getElementById('modal-edit')).close();
          fetch(`${API_URL}?action=deleteEmployee`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ empId: emp.emp_id })
          }).then(res => res.json()).then(() => loadData());
        }
      };
      M.Modal.getInstance(document.getElementById('modal-edit')).open();
    }

    // ระบบส่ง FormData ไปยัง PHP อย่างเสถียร รองรับ Strict Web Server
    document.getElementById('empForm').onsubmit = (e) => {
      e.preventDefault();
      
      const empIdValue = document.getElementById('empId').value.trim();
      const nameValue = document.getElementById('name').value.trim();
      
      if(!empIdValue || !nameValue) {
         M.toast({html: 'กรุณากรอกรหัสพนักงานและชื่อ-นามสกุล'});
         return;
      }

      const btn = document.getElementById('submit-btn');
      btn.disabled = true; btn.innerText = "กำลังบันทึก...";
      document.getElementById('loader').classList.remove('hide');

      const formData = new FormData();
      formData.append('empId', empIdValue);
      formData.append('name', nameValue);
      formData.append('phone', document.getElementById('phone').value.trim());
      formData.append('dept', document.getElementById('dept').value.trim());
      formData.append('div', document.getElementById('div').value.trim());
      formData.append('pos', document.getElementById('pos').value.trim());
      formData.append('isFav', document.getElementById('isFavField').value);
      formData.append('currentImg', document.getElementById('currentImg').value);
      
      const fileInput = document.getElementById('imgFile');
      if (fileInput.files.length > 0) {
        formData.append('imgFile', fileInput.files[0]);
      }

      fetch(`${API_URL}?action=addOrUpdateEmployee`, {
        method: 'POST',
        body: formData
      })
      .then(res => {
         if (!res.ok) throw new Error('Network status not OK');
         return res.json();
      })
      .then(res => {
        btn.disabled = false; btn.innerText = "บันทึกข้อมูล";
        if(res.success) { 
            M.Modal.getInstance(document.getElementById('modal-edit')).close();
            M.toast({html: 'บันทึกข้อมูลเสร็จสิ้น'}); 
            loadData();
        } else { 
            document.getElementById('loader').classList.add('hide');
            M.toast({html: 'ล้มเหลว: ' + res.message}); 
        }
      })
      .catch(err => {
        btn.disabled = false; btn.innerText = "บันทึกข้อมูล";
        document.getElementById('loader').classList.add('hide');
        M.toast({html: 'เกิดข้อผิดพลาดในการเชื่อมต่อเซิร์ฟเวอร์'});
        console.error(err);
      });
    };

    function resetForm() {
      document.getElementById('form-title').innerText = "เพิ่มพนักงานใหม่";
      document.getElementById('empForm').reset();
      document.getElementById('empId').readOnly = false; 
      document.getElementById('isFavField').value = 'false';
      document.getElementById('currentImg').value = '';
      document.querySelector('.file-path').value = '';
      document.getElementById('btn-delete').style.display = 'none';
      M.updateTextFields();
    }

    function filterData() {
      const v = document.getElementById('search').value.toLowerCase();
      document.querySelectorAll('.contact-item').forEach(i => {
        const searchText = i.getAttribute('data-search') || '';
        i.style.display = searchText.includes(v) ? '' : 'none';
      });
    }
  </script>
</body>
</html>