<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");  
if(!isset($_SESSION["level"]) || $_SESSION["level"]>5) {
	sleep(1);
	header("Location:" . $WebSite . "login/login_form.php"); 
	exit;
}
include $_SERVER['DOCUMENT_ROOT'] . '/load_header.php'; 
?>

<style>
/* 기본 폰트 크기 12px로 전체 적용 */
#fullscreenModal * {
  font-size: 12px !important;
}

/* 모달 전체를 강제로 화면에 맞춤 */
#fullscreenModal .modal-dialog {
  width: 1920px !important;
  max-width: 1920px !important;
  height: 1080px !important;
  margin: 0 !important;
  padding: 0 !important;
}

#fullscreenModal .modal-content {
  height: 100vh;
  border-radius: 0;
  border: none;
}

/* 스크롤 충돌 방지 */
body.modal-open {
  overflow: hidden;
}

#fullscreenModal .form-control {
  padding: 2px 4px !important;
  height: auto !important;
  font-size: 12px !important;
}

#fullscreenModal table td,
#fullscreenModal table th {
  padding: 4px !important;
  vertical-align: middle;
  font-size: 12px !important;
}

#fullscreenModal .btn {
  padding: 2px 8px;
  font-size: 12px;
}

#fullscreenModal .modal-body {
  padding: 8px;
}

#fullscreenModal .modal-header,
#fullscreenModal .modal-footer {
  padding: 6px 10px;
}

#fullscreenModal .row > [class^="col"] {
  margin-bottom: 4px;
}
</style>

<!-- 버튼 -->
<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#fullscreenModal">전체화면 모달 열기</button>

<!-- 전체화면 모달 -->
<div class="modal fade" id="fullscreenModal" tabindex="-1" aria-labelledby="fullscreenModalLabel"
     data-bs-backdrop="static" data-bs-keyboard="false" aria-hidden="true">
  <div class="modal-dialog modal-fullscreen">
    <div class="modal-content">
      <div class="modal-header bg-dark text-white">
        <h5 class="modal-title" id="fullscreenModalLabel">발주 내역 + 가격 입력</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>

      <div class="modal-body">
        <div class="row h-100">
          <!-- 왼쪽: 발주 내역 -->
          <div class="col-6 border-end pe-3 overflow-auto">
            <h6 class="mb-3">📋 발주 내역</h6>
            <table class="table table-bordered table-sm text-center">
              <thead class="table-light">
                <tr>
                  <th>번호</th>
                  <th>품목명</th>
                  <th>수량</th>
                  <th>단가</th>
                </tr>
              </thead>
              <tbody>
                <tr><td>1</td><td>기판</td><td>3</td><td>50,000</td></tr>
                <tr><td>2</td><td>운송료</td><td>1</td><td>6,000</td></tr>
                <!-- 필요 시 반복 -->
              </tbody>
            </table>
          </div>

          <!-- 오른쪽: 가격 입력 -->
          <div class="col-6 ps-3">
            <h6 class="mb-3">💰 가격 입력</h6>
            <form>
              <div class="row g-2 mb-2">
                <div class="col-6">
                  <label class="form-label">일자</label>
                  <input type="date" class="form-control form-control-sm">
                </div>
                <div class="col-6">
                  <label class="form-label">거래처</label>
                  <input type="text" class="form-control form-control-sm">
                </div>
              </div>
              <button type="button" class="btn btn-sm btn-outline-primary add-row-account">+ 행추가</button>
              <table class="table table-bordered table-sm text-center" id="accountList">
                <thead class="table-secondary">
                    <tr>                
                        <th>일련번호</th>
                        <th>품목코드</th>
                        <th>품목명</th>
                        <th>규격</th>
                        <th>수량</th>
                        <th>단가</th>
                        <th>공급가액</th>
                        <th>부가세</th>
                        <th>적요</th>
                    </tr>
                    </thead>
                <tbody id="accountListBody">
                    <!-- 동적 행이 여기에 생성됨 -->
                </tbody>
                <tfoot class="table-light fw-bold">
                    <tr>
                    <td colspan="7" class="text-end">합계</td>
                    <td id="sumQty">0</td>
                    <td id="sumTotal">0</td>
                    </tr>
                </tfoot>
                </table>
            </form>
          </div>
        </div>
      </div>

      <div class="modal-footer justify-content-between">
        <span class="text-muted">총합계: 171,600</span>
        <div>
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">닫기</button>
          <button type="button" class="btn btn-primary">저장</button>
        </div>
      </div>
    </div>
  </div>
</div>


<script>
// 페이지 로딩
$(document).ready(function(){	
    var loader = document.getElementById('loadingOverlay');
    loader.style.display = 'none';
});
</script>

<script>
// 모달 드래그 기능 추가
document.addEventListener('DOMContentLoaded', () => {
  const modal = document.querySelector('#fullscreenModal .modal-dialog');
  const header = document.querySelector('#fullscreenModal .modal-header');

  let isDragging = false;
  let offsetX = 0;
  let offsetY = 0;

  header.addEventListener('mousedown', (e) => {
    isDragging = true;
    offsetX = e.clientX - modal.offsetLeft;
    offsetY = e.clientY - modal.offsetTop;
    modal.style.position = 'absolute';
    modal.style.margin = 0;
    modal.style.zIndex = 1055;
  });

  document.addEventListener('mousemove', (e) => {
    if (isDragging) {
      modal.style.left = `${e.clientX - offsetX}px`;
      modal.style.top = `${e.clientY - offsetY}px`;
    }
  });

  document.addEventListener('mouseup', () => {
    isDragging = false;
  });
});


function updateTableSums() {
  let sumQty = 0;
  let sumVAT = 0;
  let sumTotal = 0;

  $('#accountListBody tr').each(function () {
    const qty = parseFloat($(this).find('input[name="col4[]"]').val()) || 0;
    const vat = parseFloat($(this).find('input[name="colVAT[]"]').val()) || 0;
    const supply = parseFloat($(this).find('input[name="col6[]"]').val()) || 0;

    sumQty += qty;
    sumVAT += vat;
    sumTotal += supply + vat;
  });

  $('#sumQty').text(sumQty.toLocaleString());
  $('#sumVAT').text(sumVAT.toLocaleString());
  $('#sumTotal').text(sumTotal.toLocaleString());
}


$(document).on('input', '#accountListBody input', function () {
  updateTableSums();
});

function addRow_Account(
  tableBody = $('#accountListBody'),
  afterRow = null,
  rowData = {}
) {
  rowData = Object.assign({ col7: '1' }, rowData);  

  const fields = [
  { name: 'col1' },                 // 품목코드
  { name: 'col2' },                 // 품목명
  { name: 'col3' },                 // 규격
  { name: 'col4' },                 // 수량
  { name: 'col5' },                 // 단가
  { name: 'col6' },                 // 공급가액
  { name: 'colVAT' },              // 부가세
  { name: 'col7' }                  // 적요
];

  const options = {    
  };

  createCommonRow(tableBody, fields, options, rowData, afterRow);
  updateTableSums(); // 추가 후 합계 갱신
}

$(document).ready(function () {
  // .add-row-account 클릭 시 행 추가
  $('.add-row-account').on('click', function () {
    addRow_Account($('#accountListBody'));
    alertToast('행추가');
  });
});


function createCommonRow(tableBody, fields, selectOptions = {}, rowData = {}, afterRow = null) {
  let newRow = $('<tr>');

  newRow.append('<td class="text-center">' +
    '<div class="d-flex justify-content-center align-items-center">' +
    '<span class="serial-number me-2"></span>' +
    '<button type="button" class="btn btn-outline-dark btn-sm viewNoBtn me-1 add-row-account" style="border:0px;">+</button>' +
    '<button type="button" class="btn btn-outline-danger btn-sm viewNoBtn me-1 remove-row-generic" style="border:0px;">-</button>' +
    '<button type="button" class="btn btn-outline-secondary btn-sm viewNoBtn copy-row-generic" style="border:0px;"><i class="bi bi-files"></i></button>' +
    '</div></td>');

  fields.forEach(field => {
    if (field.type === 'select') {
      newRow.append(`<td class="text-center">${createSelect(field.name, selectOptions[field.name] || [], rowData[field.name] || '')}</td>`);
    } else {
      newRow.append(`<td class="text-center">${createInput(field.name, rowData[field.name] || '')}</td>`);
    }
  });

  if (afterRow && afterRow.length) {
    afterRow.after(newRow);
  } else {
    tableBody.append(newRow);
  }

  updateSerialNumbers(tableBody);
}

function createSelect(name, options, selectedValue = '') {
  let html = `<select name="${name}[]" class="form-select form-select-sm text-center ${name}" style="height:30px; font-size:0.75rem;">`;
  html += `<option value="(없음)">(없음)</option>`;
  options.forEach(opt => {
    html += `<option value="${opt}"${opt === selectedValue ? ' selected' : ''}>${opt}</option>`;
  });
  html += '</select>';
  return html;
}

function createInput(name, value = '', type = 'text') {
  return `<input type="${type}" name="${name}[]" class="form-control form-control-sm text-center" autocomplete="off" value="${value}" style="height:30px; font-size:0.75rem;">`;
}

function updateSerialNumbers(tableBody) {
  tableBody.find('tr').each(function (index) {
    $(this).find('.serial-number').text(index + 1);
  });
}


</script>
