{# 경로/파일: realcom-nas-ui/templates/share.html #}
{% extends "base.html" %}
{% block title %}공유폴더 접근 제어{% endblock %}

{% block content %}
<style>
  .table { background: #fff; border-radius: 7px; box-shadow: 0 2px 6px #eef2f5; }
  th, td { vertical-align: middle !important; }
  .btn-sm { font-size: 0.97em; }
  input[type="text"] { width: 140px; padding: 5px 7px; border: 1px solid #d3dbe6; border-radius: 4px; }
  .input-group { display: flex; gap: 7px; align-items: center; }
  .input-group input[type="text"] { flex:1; min-width:0; }
  tr:nth-child(even) { background: #f8fafc; }
  th { background: #f3f6fa !important; font-weight:600; }
  .user-label { display: inline-block; margin-right: 15px; margin-bottom: 5px; }
  .permission-allow { color: #1976d2; font-weight: 500;}
  .permission-deny { color: #aaa;}
  .alert { padding: 8px 16px; border-radius: 6px; font-size: 1em; margin-bottom: 18px;}
  .alert-success { background: #e9f6ec; color: #257a3e; border: 1px solid #b3e1c2;}
  .alert-danger { background: #fff0f0; color: #a72323; border: 1px solid #fac8c8;}
  .helpbox {
    background: #f8fbff;
    border: 1px solid #dbeafe;
    color: #1e3a8a;
    border-radius: 10px;
    padding: 12px 14px;
    margin: 14px 0 18px;
    line-height: 1.5;
    font-size: 14px;
  }
  .helpbox b { color: #0f172a; }
  .muted { color:#64748b; font-size: 12.5px; }
  .note { color:#334155; font-size: 13px; margin-top: 6px; }
  .path-pill {
    display:inline-block;
    font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
    background:#f1f5f9;
    border:1px solid #e2e8f0;
    padding:2px 8px;
    border-radius:999px;
    font-size: 12px;
    color:#0f172a;
  }
  .inline { display:flex; gap:10px; align-items:center; flex-wrap:wrap; }
  .checkbox { display:flex; gap:6px; align-items:center; }
  .small-input { width: 220px; }
  .danger-hint { color:#b91c1c; font-size: 12.5px; }

  /* ✅ 자동 규칙명 프리뷰 */
  .name-preview {
    display:flex; align-items:center; gap:8px; flex-wrap:wrap;
    margin-top:6px;
  }
  .name-preview .label {
    font-size:12.5px; color:#475569;
  }

  /* 모달 */
  .modal {
    display: none;
    background: rgba(0,0,0,0.35);
    position: fixed;
    top: 0; left: 0; right: 0; bottom: 0;
    z-index: 1050;
  }
  .modal-dialog {
    max-width: 560px;
    margin: 7% auto;
    background: #fff;
    border-radius: 10px;
    padding: 18px;
    box-shadow: 0 4px 14px rgba(0,0,0,0.3);
    max-height: 70vh;
    overflow-y: auto;
  }
  .modal-header {
    font-weight: 700;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .modal-header .btn-close {
    cursor: pointer;
    border: none;
    background: transparent;
    font-size: 1.2em;
    font-weight: bold;
  }
  .modal-body ul {
    list-style: none;
    padding-left: 0;
    margin: 0;
    max-height: 52vh;
    overflow-y: auto;
  }
  .modal-body ul li {
    margin-bottom: 6px;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 6px 8px;
    border-radius: 6px;
  }
  .modal-body ul li:hover { background: #e6f0ff; }
  .modal-body ul li input[type="radio"] { margin: 0 6px 0 0; }
  .modal-footer {
    display:flex;
    justify-content: flex-end;
    gap: 8px;
    margin-top: 12px;
  }
</style>

<h2 class="mt-4 mb-2" style="font-weight:800;">공유폴더 접근 제어</h2>

<div class="helpbox">
  <b>이 화면은 디스크/마운트 화면이 아닙니다.</b><br>
  이미 마운트된 저장장치에서 <b>“어떤 폴더를 누구에게 열어줄지”</b>만 정합니다.<br>
  <span class="muted">※ 여기서 설정해도 디스크가 삭제/포맷/언마운트 되지 않습니다.</span>
</div>

{% with messages = get_flashed_messages(with_categories=true) %}
  {% if messages %}
    {% for category, message in messages %}
      <div class="alert alert-{{ 'success' if category=='success' else 'danger' }}">
        {{ message }}
      </div>
    {% endfor %}
  {% endif %}
{% endwith %}

<!-- 1) 마운트된 저장장치 목록 -->
<div class="mb-3">
  <h5 style="font-weight:700; margin: 6px 0 10px;">연결된 저장장치 목록 (마운트된 것만)</h5>
  <div class="muted">“채우기”는 아래 경로칸에 마운트 경로를 복사해줍니다.</div>

  <table class="table table-bordered align-middle mt-2 mb-0">
    <thead>
      <tr>
        <th style="width:32%;">디바이스</th>
        <th>마운트 경로</th>
        <th style="width:260px;">설명</th>
        <th style="width:120px;">경로 채우기</th>
      </tr>
    </thead>
    <tbody>
      {% if mounts and mounts|length > 0 %}
        {% for mount in mounts %}
        <tr>
          <td><span class="path-pill">{{ mount.device }}</span></td>
          <td><span class="path-pill">{{ mount.path }}</span></td>
          <td class="muted">{{ mount.info or '-' }}</td>
          <td class="text-center">
            <button type="button"
                    class="btn btn-outline-secondary btn-sm fill-path-btn"
                    data-path="{{ mount.path }}">
              채우기
            </button>
          </td>
        </tr>
        {% endfor %}
      {% else %}
        <tr>
          <td colspan="4" class="text-center text-muted">마운트된 저장장치가 없습니다.</td>
        </tr>
      {% endif %}
    </tbody>
  </table>

  <div class="note">
    ※ 여기 버튼은 “경로 입력 보조”일 뿐이고 마운트/언마운트랑 무관합니다.
  </div>
</div>

<hr class="my-4">

<!-- 2) 규칙 추가 -->
<h5 style="font-weight:800; margin: 6px 0 10px;">폴더 접근 규칙 추가</h5>
<div class="muted mb-2">
  1) 위에서 <b>채우기</b> → 2) <b>폴더 선택</b> 또는 경로 직접 입력 → 3) 사용자 체크 → 4) <b>규칙 추가</b><br>
  <span class="danger-hint">※ “규칙 추가”는 폴더를 만드는 버튼이 아님. (폴더 생성은 아래 체크를 켰을 때만)</span>
</div>

<form method="post" class="mb-3" autocomplete="off" id="addRuleForm">
  <input type="hidden" name="action" value="add">

  <!-- ✅ 서버가 'name' 혹은 'share_name'을 요구해도 자동으로 채워서 보냄 -->
  <input type="hidden" name="name" id="rule-name-hidden" value="">
  <input type="hidden" name="share_name" id="rule-share-name-hidden" value="">

  <table class="table table-bordered align-middle mb-2">
    <thead>
      <tr>
        <th style="width:44%;">경로</th>
        <th style="width:26%;">(선택) 폴더 생성</th>
        <th>허용 사용자</th>
        <th style="width:110px;"></th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>
          <div class="input-group">
            <input type="text" name="path" id="rule-path" placeholder="/mnt/storage/..." required class="small-input">
            <button type="button" class="btn btn-outline-primary btn-sm" onclick="openFolderPicker()">폴더 선택</button>
            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="clearRulePath()">초기화</button>
          </div>
          <div class="muted mt-1">허용 경로 예) <span class="path-pill">/mnt/storage/팀폴더</span>, <span class="path-pill">/mnt/usb1/업무</span></div>

          <!-- ✅ 자동 규칙명 프리뷰 -->
          <div class="name-preview">
            <span class="label">자동 규칙명:</span>
            <span class="path-pill" id="ruleNamePreview">-</span>
            <span class="muted">(사용자가 안 써도 됨)</span>
          </div>
        </td>

        <td>
          <div class="inline">
            <label class="checkbox">
              <input type="checkbox" id="create-folder" name="create_folder" value="1">
              폴더를 새로 만들기
            </label>
            <input type="text" id="new-folder-name" name="new_folder_name" placeholder="새 폴더명 (예: teamA)" disabled>
          </div>
          <div class="muted mt-1">체크 OFF면 폴더 생성 절대 안 함</div>
        </td>

        <td>
          {% if users and users|length > 0 %}
            {% for user in users %}
              <label class="user-label">
                <input type="checkbox" name="allowed_users" value="{{ user }}">
                <span class="permission-allow">{{ user }}</span>
              </label>
            {% endfor %}
            <div class="muted mt-1">체크된 사용자만 접근 가능</div>
          {% else %}
            <span style="color:#aaa;">등록된 사용자가 없습니다.</span>
          {% endif %}
        </td>

        <td class="text-center">
          <button type="submit" class="btn btn-success btn-sm px-3">규칙 추가</button>
        </td>
      </tr>
    </tbody>
  </table>
</form>

<hr class="my-4">

<!-- 3) 기존 규칙 목록 -->
<h5 style="font-weight:800; margin: 6px 0 10px;">기존 접근 규칙</h5>
<div class="muted mb-2">삭제해도 실제 폴더/데이터는 지워지지 않고, <b>접근 제한 규칙만</b> 삭제됩니다.</div>

{% if shares and shares|length > 0 %}
<form method="post" autocomplete="off" id="updateRulesForm">
  <input type="hidden" name="action" value="update">

  <table class="table table-bordered align-middle">
    <thead>
      <tr>
        <th style="width:18%;">규칙명</th>
        <th>경로</th>
        <th>허용 사용자</th>
        <th style="width:170px;">관리</th>
      </tr>
    </thead>
    <tbody>
    {% for share in shares %}
      <tr>
        <td><b>{{ share.name }}</b></td>
        <td><span title="{{ share.path }}" class="path-pill">{{ share.path }}</span></td>
        <td>
          {% if users and users|length > 0 %}
            {% for user in users %}
              <label class="user-label">
                <input type="checkbox" name="allowed_users_{{ share.name }}" value="{{ user }}"
                       {% if user in share.allowed_users %}checked{% endif %}>
                <span class="{% if user in share.allowed_users %}permission-allow{% else %}permission-deny{% endif %}">
                  {{ user }}
                </span>
              </label>
            {% endfor %}
          {% else %}
            <span style="color:#aaa;">등록된 사용자가 없습니다.</span>
          {% endif %}
        </td>
        <td>
          <button type="button" class="btn btn-outline-primary btn-sm me-1 edit-rule-btn" data-name="{{ share.name }}">수정</button>
          <button type="submit" name="remove" value="{{ share.name }}"
                  class="btn btn-outline-danger btn-sm me-1"
                  onclick="return confirm('규칙 {{ share.name }} 을(를) 삭제하시겠습니까?\\n(폴더/데이터는 삭제되지 않습니다)');">
            삭제
          </button>
          <a href="{{ url_for('share_browse', share_name=share.name) }}"
             class="btn btn-outline-info btn-sm"
             title="파일탐색기 바로가기">
            탐색기
          </a>
        </td>
      </tr>
    {% endfor %}
    </tbody>
  </table>
</form>
{% else %}
  <div class="text-center text-muted my-4">등록된 접근 규칙이 없습니다.</div>
{% endif %}

<!-- 폴더 선택 모달 -->
<div class="modal" tabindex="-1" id="folderPickerModal">
  <div class="modal-dialog">
    <div class="modal-header">
      <div>
        폴더 선택
        <div class="muted">현재 기준 경로: <span class="path-pill" id="pickerBasePath">-</span></div>
      </div>
      <button type="button" class="btn-close" aria-label="닫기" onclick="closeFolderPicker()">&times;</button>
    </div>

    <div class="modal-body">
      <ul id="folder-list"></ul>
    </div>

    <div class="modal-footer">
      <button type="button" class="btn btn-outline-secondary btn-sm" onclick="closeFolderPicker()">닫기</button>
      <button type="button" class="btn btn-primary btn-sm" id="folderPickerConfirmBtn">선택 적용</button>
    </div>
  </div>
</div>

<script>
  const rulePathInput = document.getElementById('rule-path');

  // "채우기" 버튼: 마운트 경로 복사
  document.querySelectorAll('.fill-path-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      const p = btn.dataset.path || '';
      rulePathInput.value = (p || '').replace(/\/+$/, '');
      refreshAutoRuleNamePreview();
      document.getElementById('addRuleForm').scrollIntoView({ behavior: 'smooth', block: 'start' });
    });
  });

  function clearRulePath(){
    rulePathInput.value = '';
    refreshAutoRuleNamePreview();
  }

  // 폴더 생성 체크박스: 입력 활성/비활성
  const createCb = document.getElementById('create-folder');
  const folderNameInput = document.getElementById('new-folder-name');
  createCb.addEventListener('change', () => {
    folderNameInput.disabled = !createCb.checked;
    if (!createCb.checked) folderNameInput.value = '';
    refreshAutoRuleNamePreview();
  });

  rulePathInput.addEventListener('input', refreshAutoRuleNamePreview);
  folderNameInput.addEventListener('input', refreshAutoRuleNamePreview);

  // ✅ 규칙명 자동 생성
  function _sanitizeName(s){
    s = String(s || '').trim();
    s = s.replace(/\/+/g, '-');
    s = s.replace(/\s+/g, '-');
    s = s.replace(/[^0-9A-Za-z가-힣._-]+/g, '-');
    s = s.replace(/-+/g, '-').replace(/^[-.]+|[-.]+$/g, '');
    return s.slice(0, 64);
  }

  function _baseNameFromPath(p){
    p = String(p || '').trim().replace(/\/+$/, '');
    if (!p) return '';
    const parts = p.split('/').filter(Boolean);
    return parts.length ? parts[parts.length - 1] : '';
  }

  function computeAutoRuleName(){
    // 폴더 생성 체크 ON이면 new_folder_name 우선
    const createOn = !!createCb.checked;
    const newName = String(folderNameInput.value || '').trim();
    if (createOn && newName) return _sanitizeName(newName);

    // 아니면 path 마지막 폴더명
    const base = _baseNameFromPath(rulePathInput.value);
    if (base) return _sanitizeName(base);

    // 그래도 없으면 타임스탬프
    return 'share-' + Date.now();
  }

  function refreshAutoRuleNamePreview(){
    const nm = computeAutoRuleName();
    document.getElementById('ruleNamePreview').textContent = nm || '-';
  }

  // 규칙 수정(권한 업데이트)
  document.querySelectorAll('.edit-rule-btn').forEach(btn => {
    btn.addEventListener('click', async (e) => {
      e.preventDefault();
      const shareName = btn.dataset.name;
      const checkboxes = document.querySelectorAll(`input[name="allowed_users_${shareName}"]`);
      const allowedUsers = [];
      checkboxes.forEach(chk => { if (chk.checked) allowedUsers.push(chk.value); });

      try {
        const res = await fetch('/share/update_permissions', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ share_name: shareName, allowed_users: allowedUsers })
        });
        const data = await res.json();
        if (data.status === 'success') {
          alert('권한이 변경되었습니다.');
          location.reload();
        } else {
          alert('권한 변경 실패: ' + (data.message || '서버 오류'));
        }
      } catch {
        alert('권한 변경 실패: 네트워크 오류');
      }
    });
  });

  // 폴더 선택 모달
  let currentPath = '';
  let selectedPath = '';

  function openFolderPicker() {
    const base = (rulePathInput.value || '').trim();
    if (!base) {
      alert('먼저 위에서 "채우기"로 기본 경로를 넣거나, /mnt/storage/... 형태로 경로를 입력한 다음 폴더 선택을 누르세요.');
      return;
    }
    currentPath = base.replace(/\/+$/, '');
    if (!currentPath.startsWith('/')) currentPath = '/' + currentPath;
    selectedPath = currentPath;

    document.getElementById('pickerBasePath').innerText = currentPath || '-';
    document.getElementById('folderPickerModal').style.display = 'block';
    document.body.classList.add('modal-open');

    loadFolders(currentPath);
  }

  function closeFolderPicker() {
    document.getElementById('folderPickerModal').style.display = 'none';
    document.body.classList.remove('modal-open');
  }

  function _safeParent(path) {
    const p = (path || '/').replace(/\/+$/, '');
    if (p === '/' || p === '') return '/';
    const parts = p.split('/').filter(Boolean);
    parts.pop();
    const parent = '/' + parts.join('/');
    return parent || '/';
  }

  function _joinPath(a, b){
    const aa = (a || '').replace(/\/+$/, '');
    const bb = (b || '').replace(/^\/+/, '');
    return (aa ? aa : '/') + '/' + bb;
  }

  function loadFolders(path) {
    document.getElementById('pickerBasePath').innerText = path || '-';
    const folderList = document.getElementById('folder-list');
    folderList.innerHTML = `<li class="muted">불러오는 중...</li>`;

    fetch(`/share/list_folders?path=${encodeURIComponent(path)}`)
      .then(res => res.json())
      .then(folders => {
        currentPath = path;
        folderList.innerHTML = '';

        const parentPath = _safeParent(path);
        if (path !== '/' && path !== '' && parentPath !== path) {
          const liUp = document.createElement('li');
          liUp.innerHTML = `<a href="#" style="text-decoration:none; font-weight:700;">.. (상위 폴더)</a>`;
          liUp.querySelector('a').onclick = (e) => {
            e.preventDefault();
            loadFolders(parentPath);
          };
          folderList.appendChild(liUp);
        }

        if (!folders || folders.length === 0) {
          const liEmpty = document.createElement('li');
          liEmpty.className = 'muted';
          liEmpty.innerText = '하위 폴더가 없습니다.';
          folderList.appendChild(liEmpty);
          return;
        }

        folders = folders.filter(x => x && x !== '.' && x !== '..');

        folders.forEach(folder => {
          const fullPath = _joinPath(path, folder).replace(/\/+$/, '');
          const li = document.createElement('li');

          const radio = document.createElement('input');
          radio.type = 'radio';
          radio.name = 'folder_pick';
          radio.value = fullPath;
          radio.checked = (fullPath === selectedPath);
          radio.addEventListener('change', () => { selectedPath = fullPath; });

          const label = document.createElement('span');
          label.innerText = folder;
          label.style.flex = '1';
          label.style.userSelect = 'none';

          const openBtn = document.createElement('a');
          openBtn.href = '#';
          openBtn.innerText = '열기';
          openBtn.style.marginLeft = 'auto';
          openBtn.style.textDecoration = 'none';
          openBtn.onclick = (ev) => {
            ev.preventDefault();
            ev.stopPropagation();
            selectedPath = fullPath;
            loadFolders(fullPath);
          };

          li.appendChild(radio);
          li.appendChild(label);
          li.appendChild(openBtn);

          li.addEventListener('click', (ev) => {
            if (ev.target.tagName.toLowerCase() === 'a') return;
            radio.checked = true;
            selectedPath = fullPath;
          });

          folderList.appendChild(li);
        });
      })
      .catch(() => {
        folderList.innerHTML = `<li class="muted">폴더 목록 로드 실패</li>`;
      });
  }

  document.getElementById('folderPickerConfirmBtn').addEventListener('click', () => {
    if (selectedPath) rulePathInput.value = selectedPath;
    refreshAutoRuleNamePreview();
    closeFolderPicker();
  });

  // ✅ 제출 직전에 hidden 규칙명 채워서 전송
  document.getElementById('addRuleForm').addEventListener('submit', () => {
    const nm = computeAutoRuleName();
    document.getElementById('rule-name-hidden').value = nm;
    document.getElementById('rule-share-name-hidden').value = nm;

    setTimeout(() => {
      rulePathInput.value = '';
      createCb.checked = false;
      folderNameInput.disabled = true;
      folderNameInput.value = '';
      document.querySelectorAll('#addRuleForm input[type="checkbox"][name="allowed_users"]').forEach(cb => cb.checked = false);
      refreshAutoRuleNamePreview();
    }, 250);
  });

  // 초기 프리뷰
  refreshAutoRuleNamePreview();
</script>

{% endblock %}
