// /js/manage-project.js

import { API, getAuthHeaders, ensureAuthenticated } from '/js/api-config.js';

// 인증 확인
ensureAuthenticated();

function createRow(item, cols, delHandler) {
  const tr = document.createElement('tr');
  cols.forEach(key => {
    const td = document.createElement('td');
    td.textContent = item[key];
    tr.appendChild(td);
  });
  const delBtn = document.createElement('button');
  delBtn.textContent = '삭제';
  delBtn.className = 'btn-delete';
  delBtn.onclick = () => delHandler(item);
  const td = document.createElement('td');
  td.appendChild(delBtn);
  tr.appendChild(td);
  return tr;
}

const projectForm = document.getElementById('projectForm');
projectForm?.addEventListener('submit', async e => {
  e.preventDefault();
  const body = {
    job_no: document.getElementById('job_no').value.trim(),
    project_name: document.getElementById('project_name').value.trim(),
    contract_date: document.getElementById('contract_date').value,
    due_date: document.getElementById('due_date').value,
    delivery_method: document.getElementById('delivery_method').value.trim(),
    site: document.getElementById('site').value.trim(),
    pm: document.getElementById('pm').value.trim()
  };

  if (!body.project_name || !body.job_no) {
    return alert('필수 항목을 입력하세요.');
  }

  try {
    const res = await fetch(`${API}/projects`, {
      method: 'POST',
      headers: getAuthHeaders(),
      body: JSON.stringify(body)
    });
    const result = await res.json();
    if (res.ok && result.success) {
      alert('✅ 등록 완료');
      projectForm.reset();
      loadProjects();
    } else {
      alert('❌ 실패: ' + (result.error || '알 수 없는 오류'));
    }
  } catch (err) {
    alert('🚨 서버 오류: ' + err.message);
  }
});

async function loadProjects() {
  const tbody = document.getElementById('projectTableBody');
  tbody.innerHTML = '<tr><td colspan="9">불러오는 중...</td></tr>';
  try {
    const res = await fetch(`${API}/projects`, {
      headers: getAuthHeaders()
    });
    
    if (!res.ok) {
      throw new Error(`HTTP error! status: ${res.status}`);
    }
    
    const list = await res.json();
    tbody.innerHTML = '';
    
    if (Array.isArray(list)) {
      list.forEach(item => {
        const row = createRow(item, [
          'project_id', 'job_no', 'project_name', 'contract_date',
          'due_date', 'delivery_method', 'site', 'pm'
        ], async p => {
          if (!confirm('삭제하시겠습니까?')) return;
          try {
            const delRes = await fetch(`${API}/projects/${p.project_id}`, {
              method: 'DELETE',
              headers: getAuthHeaders()
            });
            if (delRes.ok) {
              alert('✅ 삭제 완료');
              loadProjects();
            } else {
              alert('❌ 삭제 실패');
            }
          } catch (err) {
            alert('🚨 삭제 중 오류: ' + err.message);
          }
        });
        tbody.appendChild(row);
      });
    } else {
      tbody.innerHTML = '<tr><td colspan="9">데이터 형식 오류</td></tr>';
    }
  } catch (err) {
    tbody.innerHTML = '<tr><td colspan="9">로드 실패: ' + err.message + '</td></tr>';
  }
}

window.addEventListener('DOMContentLoaded', loadProjects);