<?php
require_once __DIR__ . '/../includes/bootstrap.php';
requireLogin();

$beneficiary_id = (int)($_GET['beneficiary_id'] ?? 0);

// Filters for docs list (like beneficiaries page)
$filterTypeId  = (int)($_GET['type_id'] ?? 0);
$filterFileNo  = (int)($_GET['file_number'] ?? 0);
$q             = trim((string)($_GET['q'] ?? ''));

$types = $pdo->query("SELECT id, name_ar FROM beneficiary_types ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);

$prefName = '';
if ($beneficiary_id > 0) {
    $st = $pdo->prepare("SELECT full_name FROM beneficiaries WHERE id=?");
    $st->execute([$beneficiary_id]);
    $prefName = (string)($st->fetchColumn() ?: '');
}

$docTypes = [
    'id_card' => 'هوية',
    'birth_cert' => 'شهادة ميلاد',
    'father_death_cert' => 'شهادة وفاة الأب',
    'orphan_photo' => 'صورة اليتيم',
    'other_docs' => 'وثائق أخرى',
];

$sides = ['front' => 'وجه', 'back' => 'ظهر'];

$docs = (function() use ($pdo, $beneficiary_id, $filterTypeId, $filterFileNo, $q) {
    if ($beneficiary_id > 0) {
        $st = $pdo->prepare("
            SELECT bd.*, b.full_name, b.file_number, bt.name_ar AS beneficiary_type_name
            FROM beneficiary_documents bd
            JOIN beneficiaries b ON b.id = bd.beneficiary_id
            JOIN beneficiary_types bt ON bt.id = b.beneficiary_type_id
            WHERE bd.beneficiary_id=?
            ORDER BY bd.id DESC
            LIMIT 300
        ");
        $st->execute([$beneficiary_id]);
        return $st->fetchAll(PDO::FETCH_ASSOC);
    }

    $where = [];
    $params = [];

    if ($filterTypeId > 0) {
        $where[] = 'b.beneficiary_type_id = ?';
        $params[] = $filterTypeId;
    }
    if ($filterTypeId > 0 && $filterFileNo > 0) {
        $where[] = 'b.file_number = ?';
        $params[] = $filterFileNo;
    }
    if ($q !== '') {
        $where[] = '(b.full_name LIKE ? OR b.id_number LIKE ? OR b.phone LIKE ?)';
        $params[] = '%' . $q . '%';
        $params[] = '%' . $q . '%';
        $params[] = '%' . $q . '%';
    }

    $sqlWhere = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

    $st = $pdo->prepare("
        SELECT bd.*, b.full_name, b.file_number, bt.name_ar AS beneficiary_type_name
        FROM beneficiary_documents bd
        JOIN beneficiaries b ON b.id = bd.beneficiary_id
        JOIN beneficiary_types bt ON bt.id = b.beneficiary_type_id
        {$sqlWhere}
        ORDER BY bd.id DESC
        LIMIT 300
    ");
    $st->execute($params);
    return $st->fetchAll(PDO::FETCH_ASSOC);
})();
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="utf-8">
  <title>وثائق المنتفعين</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- Bootstrap 5 RTL (CSS + JS bundle) -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

  <style>
    body{background:#f6f8fb}
    .dropzone{border:2px dashed #c9d6ee;border-radius:16px;padding:18px;background:#fbfdff;text-align:center;transition:.15s;cursor:pointer;user-select:none}
    .dropzone.drag{border-color:#2d6cdf;background:#f1f7ff}
    .q-item{border:1px solid #e6ebf2;border-radius:16px;padding:12px;background:#fff}
    .thumb{width:86px;height:86px;border-radius:14px;border:1px solid #edf1f6;display:flex;align-items:center;justify-content:center;overflow:hidden;background:#f8fafc;flex:0 0 auto}
    .thumb img{width:100%;height:100%;object-fit:cover}
    .mono{font-family: ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace}
  </style>
</head>
<body>
<div class="container py-3">

  <div class="card shadow-sm border-0 mb-3">
    <div class="card-body d-flex justify-content-between align-items-start flex-wrap gap-2">
      <div>
        <h3 class="mb-1">وثائق المنتفعين</h3>
        <div class="text-muted">رفع/تعديل/استعراض — (موبايل/كمبيوتر)</div>
      </div>
      <div class="d-flex gap-2 flex-wrap">
        <a class="btn btn-outline-secondary" href="index.php">مركز الوثائق</a>
        <a class="btn btn-outline-secondary" href="<?= ORPHAN_PUBLIC_BASE ?>/admin/index.php">لوحة الإدارة</a>
        <?php if ($beneficiary_id > 0): ?>
          <span class="badge text-bg-primary align-self-center">
            المنتفع المحدد: <?= orphan_e($prefName) ?> (ID: <?= (int)$beneficiary_id ?>)
          </span>
          <a class="btn btn-outline-primary" href="document_viewer.php?beneficiary_id=<?= (int)$beneficiary_id ?>">استعراض</a>
        <?php endif; ?>
      </div>
    </div>
  </div>

  <!-- Filter like beneficiaries page -->
  <?php if ($beneficiary_id <= 0): ?>
  <div class="card shadow-sm border-0 mb-3">
    <div class="card-body">
      <h5 class="mb-3">فلترة قائمة الوثائق</h5>

      <form class="row g-3" method="get" action="beneficiary_documents.php">
        <div class="col-12 col-lg-4">
          <label class="form-label">نوع المستفيد</label>
          <select class="form-select" name="type_id" id="filterType">
            <option value="">— الكل —</option>
            <?php foreach ($types as $t): ?>
              <option value="<?= (int)$t['id'] ?>" <?= ($filterTypeId === (int)$t['id']) ? 'selected' : '' ?>>
                <?= orphan_e((string)$t['name_ar']) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="col-12 col-lg-3">
          <label class="form-label">رقم الملف</label>
          <input class="form-control" type="number" min="1" name="file_number" id="filterFileNo"
                 value="<?= $filterFileNo > 0 ? (int)$filterFileNo : '' ?>">
        </div>

        <div class="col-12 col-lg-5">
          <label class="form-label">بحث سريع (اسم/هوية/هاتف)</label>
          <input class="form-control" type="text" name="q" value="<?= orphan_e($q) ?>" placeholder="اكتب كلمة للبحث...">
        </div>

        <div class="col-12 d-flex gap-2 flex-wrap">
          <button class="btn btn-primary" type="submit">بحث</button>
          <a class="btn btn-outline-secondary" href="beneficiary_documents.php">مسح</a>
        </div>
      </form>
    </div>
  </div>
  <?php endif; ?>

  <!-- Upload target selection (works from documents admin panel) -->
  <?php if ($beneficiary_id <= 0): ?>
  <div class="card shadow-sm border-0 mb-3">
    <div class="card-body">
      <h5 class="mb-3">تحديد المنتفع لرفع الملفات</h5>
      <div class="row g-3">
        <div class="col-12 col-lg-6">
          <label class="form-label">نوع المستفيد *</label>
          <select id="benefType" class="form-select" required>
            <option value="">— اختر —</option>
            <?php foreach ($types as $t): ?>
              <option value="<?= (int)$t['id'] ?>"><?= orphan_e((string)$t['name_ar']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="col-12 col-lg-6">
          <label class="form-label">رقم الملف داخل النوع *</label>
          <input id="fileNo" type="number" min="1" class="form-control" required>
          <div class="form-text">يمكن تعبئته تلقائيًا إذا اخترت مستفيد من النتائج.</div>
        </div>

        <div class="col-12" id="benPickWrap" style="display:none;">
          <label class="form-label">اختر المستفيد (اختياري)</label>
          <input id="benSearch" class="form-control" placeholder="ابحث بالاسم/رقم الملف/الهوية..." style="margin-bottom:8px;">
          <select id="benPick" class="form-select">
            <option value="">— اختر من النتائج —</option>
          </select>
          <div class="form-text">عند اختيار المستفيد سيتم الرفع باستخدام beneficiary_id (الأدق).</div>
        </div>
      </div>
    </div>
  </div>
  <?php endif; ?>

  <!-- Upload -->
  <div class="card shadow-sm border-0 mb-3">
    <div class="card-body">
      <h5 class="mb-3">رفع الملفات</h5>

      <div id="drop" class="dropzone">
        <div class="fw-bold mb-1">اسحب الملفات هنا أو اضغط للاختيار</div>
        <div class="text-muted small">JPG/PNG/PDF — أقصى حجم: <?= (int)(ORPHAN_MAX_UPLOAD_BYTES / 1024 / 1024) ?>MB</div>

        <input id="fileInput" type="file" multiple accept="image/*,application/pdf" capture="environment" style="display:none">

        <div class="d-flex gap-2 justify-content-center flex-wrap mt-3">
          <button class="btn btn-primary" id="pickBtn" type="button">اختر ملفات</button>
          <button class="btn btn-outline-secondary" id="clearBtn" type="button">مسح القائمة</button>
        </div>
      </div>

      <div class="mt-3 d-grid gap-2">
        <div id="queue" class="d-grid gap-2"></div>

        <div class="d-flex gap-2 align-items-center flex-wrap">
          <button class="btn btn-success" id="uploadAllBtn" type="button">رفع الكل</button>
          <span class="text-muted" id="summary"></span>
        </div>
      </div>

    </div>
  </div>

  <!-- Docs table -->
  <div class="card shadow-sm border-0">
    <div class="card-body">
      <h5 class="mb-3">قائمة الوثائق الحالية</h5>

      <div class="table-responsive">
        <table class="table table-hover align-middle">
          <thead class="table-light">
            <tr>
              <th>#</th>
              <th>المنتفع</th>
              <th>نوع الوثيقة</th>
              <th>الجهة</th>
              <th>مشاركة (سريع)</th>
              <th>العنوان</th>
              <th>الاسم الأصلي</th>
              <th>تاريخ</th>
              <th>إجراءات</th>
            </tr>
          </thead>
          <tbody>
          <?php foreach ($docs as $d): ?>
            <tr
              data-id="<?= (int)$d['id'] ?>"
              data-doc_type="<?= orphan_e((string)$d['doc_type']) ?>"
              data-doc_side="<?= orphan_e((string)($d['doc_side'] ?? '')) ?>"
              data-is_shareable="<?= (int)($d['is_shareable'] ?? 0) ?>"
              data-title="<?= orphan_e((string)($d['title'] ?? '')) ?>"
            >
              <td class="mono"><?= (int)$d['id'] ?></td>
              <td style="white-space:normal">
                <?= orphan_e((string)$d['full_name']) ?>
                <div class="text-muted small">ملف: <?= (int)$d['file_number'] ?> — <?= orphan_e((string)$d['beneficiary_type_name']) ?></div>
              </td>
              <td><?= orphan_e($docTypes[$d['doc_type']] ?? (string)$d['doc_type']) ?></td>
              <td><?= orphan_e($sides[$d['doc_side']] ?? '—') ?></td>
              <td>
                <button type="button" class="btn btn-sm btn-outline-success btn-toggle-shareable">
                  <?= ((int)($d['is_shareable'] ?? 0) === 1) ? 'نعم (اضغط)' : 'لا (اضغط)' ?>
                </button>
              </td>
              <td><?= orphan_e((string)($d['title'] ?? '—')) ?></td>
              <td><?= orphan_e((string)$d['original_name']) ?></td>
              <td class="mono"><?= orphan_e((string)$d['created_at']) ?></td>
              <td>
                <div class="d-flex gap-2 flex-wrap">
                  <a class="btn btn-sm btn-outline-primary" href="document_download.php?id=<?= (int)$d['id'] ?>" target="_blank">عرض</a>
                  <button class="btn btn-sm btn-outline-secondary btn-edit" type="button">تعديل</button>
                  <form method="post" action="document_delete.php" style="margin:0">
                    <?= orphan_csrf_field() ?>
                    <input type="hidden" name="id" value="<?= (int)$d['id'] ?>">
                    <button class="btn btn-sm btn-outline-danger" type="submit" onclick="return confirm('حذف الوثيقة؟')">حذف</button>
                  </form>
                </div>
              </td>
            </tr>
          <?php endforeach; ?>
          <?php if (!$docs): ?>
            <tr><td colspan="9" class="text-muted">لا توجد وثائق.</td></tr>
          <?php endif; ?>
          </tbody>
        </table>
      </div>

    </div>
  </div>

</div>

<!-- Edit Modal -->
<div class="modal fade" id="editModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">تعديل بيانات الوثيقة</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="إغلاق"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" id="m_id">
        <div class="mb-3">
          <label class="form-label">نوع الوثيقة</label>
          <select id="m_doc_type" class="form-select">
            <?php foreach ($docTypes as $k => $v): ?>
              <option value="<?= orphan_e($k) ?>"><?= orphan_e($v) ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="mb-3">
          <label class="form-label">الجهة (للهوية فقط)</label>
          <select id="m_doc_side" class="form-select">
            <option value="">—</option>
            <option value="front">وجه</option>
            <option value="back">ظهر</option>
          </select>
        </div>

        <div class="mb-3">
          <label class="form-label">قابل للمشاركة</label>
          <select id="m_is_shareable" class="form-select">
            <option value="0">لا</option>
            <option value="1">نعم</option>
          </select>
        </div>

        <div class="mb-3">
          <label class="form-label">العنوان (اختياري)</label>
          <input id="m_title" class="form-control" type="text">
        </div>

        <div id="m_err" class="alert alert-danger d-none mb-0"></div>
        <div id="m_ok" class="alert alert-success d-none mb-0">تم الحفظ بنجاح.</div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-outline-secondary" type="button" data-bs-dismiss="modal">إغلاق</button>
        <button class="btn btn-primary" id="m_save" type="button">حفظ</button>
      </div>
    </div>
  </div>
</div>

<script>
(function(){
  // ensure bootstrap exists (fix your error)
  if (typeof bootstrap === 'undefined') {
    console.error('Bootstrap JS not loaded. Modal/edit will not work.');
  }

  const csrf = <?= json_encode(orphan_csrf_token(), JSON_UNESCAPED_UNICODE) ?>;
  const DOC_TYPES = <?= json_encode($docTypes, JSON_UNESCAPED_UNICODE) ?>;
  const BENEFICIARY_ID_LOCKED = <?= (int)$beneficiary_id ?>;

  const drop = document.getElementById('drop');
  const fileInput = document.getElementById('fileInput');
  const pickBtn = document.getElementById('pickBtn');
  const clearBtn = document.getElementById('clearBtn');
  const queueEl = document.getElementById('queue');
  const uploadAllBtn = document.getElementById('uploadAllBtn');
  const summary = document.getElementById('summary');

  const benType = document.getElementById('benefType');
  const fileNo = document.getElementById('fileNo');
  const benPickWrap = document.getElementById('benPickWrap');
  const benSearch = document.getElementById('benSearch');
  const benPick = document.getElementById('benPick');

  let selectedBeneficiaryId = 0;

  const state = { items: [] };

  function escapeHtml(s){ return String(s||'').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c])); }
  function bytesToKB(b){ return (b/1024).toFixed(1) + ' KB'; }
  function isPdf(file){ return (file.type||'').toLowerCase().includes('pdf') || file.name.toLowerCase().endsWith('.pdf'); }
  function defaultDocType(file){
    const n=(file.name||'').toLowerCase();
    if (n.includes('photo')) return 'orphan_photo';
    if (n.includes('birth')) return 'birth_cert';
    if (n.includes('death')) return 'father_death_cert';
    if (n.includes('id')) return 'id_card';
    return 'other_docs';
  }

  function ensureTargetSelected(){
    if (BENEFICIARY_ID_LOCKED > 0) return true;
    if (selectedBeneficiaryId > 0) return true;
    if (!benType || !fileNo) return false;
    if (!benType.value || !fileNo.value) {
      alert('اختر نوع المستفيد ثم أدخل رقم الملف أولاً.');
      return false;
    }
    return true;
  }

  function addFiles(files){
    if (!ensureTargetSelected()) return;

    [...files].forEach(file=>{
      const max = <?= (int)ORPHAN_MAX_UPLOAD_BYTES ?>;
      if (file.size > max) { state.items.push({file,status:'error',error:'حجم أكبر من المسموح',progress:0}); return; }

      const it={file,previewUrl:'',doc_type:defaultDocType(file),doc_side:'',is_shareable:0,title:'',progress:0,status:'queued',error:''};
      if (!isPdf(file) && (file.type||'').startsWith('image/')) it.previewUrl=URL.createObjectURL(file);
      state.items.push(it);
    });
    renderQueue();
  }

  function renderQueue(){
    queueEl.innerHTML='';
    let ok=0, err=0, queued=0, uploading=0;

    state.items.forEach(it=>{
      if (it.status==='done') ok++;
      else if (it.status==='error') err++;
      else if (it.status==='uploading') uploading++;
      else queued++;

      const wrap=document.createElement('div');
      wrap.className='q-item';

      const row=document.createElement('div');
      row.className='d-flex gap-3 align-items-start flex-wrap';

      const th=document.createElement('div');
      th.className='thumb';
      if (isPdf(it.file)) th.innerHTML='<span class="fw-bold text-danger">PDF</span>';
      else if (it.previewUrl){ const img=document.createElement('img'); img.src=it.previewUrl; th.appendChild(img); }
      else th.textContent='FILE';

      const body=document.createElement('div');
      body.className='flex-grow-1';
      body.innerHTML=`<div class="fw-bold">${escapeHtml(it.file.name)}</div><div class="text-muted small">${bytesToKB(it.file.size)}</div>`;

      const formRow=document.createElement('div');
      formRow.className='row g-2 mt-2';

      // doc type
      const col1=document.createElement('div'); col1.className='col-12 col-lg-3';
      col1.innerHTML='<label class="form-label small mb-1">نوع الوثيقة</label>';
      const sel=document.createElement('select'); sel.className='form-select';
      Object.keys(DOC_TYPES).forEach(k=>{ const o=document.createElement('option'); o.value=k; o.textContent=DOC_TYPES[k]; if (k===it.doc_type) o.selected=true; sel.appendChild(o); });
      sel.onchange=()=>{ it.doc_type=sel.value; renderQueue(); };
      col1.appendChild(sel);

      // side
      const col2=document.createElement('div'); col2.className='col-12 col-lg-3';
      col2.innerHTML='<label class="form-label small mb-1">الجهة (للهوية)</label>';
      const side=document.createElement('select'); side.className='form-select';
      side.innerHTML='<option value="">—</option><option value="front">وجه</option><option value="back">ظهر</option>';
      side.value=it.doc_side||''; side.onchange=()=>{ it.doc_side=side.value; };
      col2.appendChild(side);

      // share
      const col3=document.createElement('div'); col3.className='col-12 col-lg-2';
      col3.innerHTML='<label class="form-label small mb-1">مشاركة</label>';
      const share=document.createElement('select'); share.className='form-select';
      share.innerHTML='<option value="0">لا</option><option value="1">نعم</option>';
      share.value=String(it.is_shareable||0); share.onchange=()=>{ it.is_shareable=parseInt(share.value,10)||0; };
      col3.appendChild(share);

      // title
      const col4=document.createElement('div'); col4.className='col-12 col-lg-4';
      col4.innerHTML='<label class="form-label small mb-1">عنوان</label>';
      const title=document.createElement('input'); title.className='form-control'; title.value=it.title||'';
      title.oninput=()=>{ it.title=title.value; };
      col4.appendChild(title);

      formRow.appendChild(col1); formRow.appendChild(col2); formRow.appendChild(col3); formRow.appendChild(col4);

      const prog=document.createElement('div'); prog.className='progress mt-2'; prog.style.height='8px';
      const bar=document.createElement('div'); bar.className='progress-bar'; bar.style.width=(it.progress||0)+'%';
      prog.appendChild(bar);

      const actions=document.createElement('div');
      actions.className='d-flex gap-2 justify-content-end align-items-center flex-wrap mt-2';

      const st=document.createElement('div');
      st.className='small '+(it.status==='error'?'text-danger':'text-muted');
      st.textContent = it.status==='done'?'تم الرفع':(it.status==='uploading'?'جاري الرفع...':(it.status==='error'?'خطأ: '+it.error:'جاهز'));

      const upBtn=document.createElement('button');
      upBtn.type='button'; upBtn.className='btn btn-sm btn-outline-primary'; upBtn.textContent='رفع';
      upBtn.disabled=(it.status==='uploading'||it.status==='done');
      upBtn.onclick=()=>uploadOne(it);

      const rmBtn=document.createElement('button');
      rmBtn.type='button'; rmBtn.className='btn btn-sm btn-outline-secondary'; rmBtn.textContent='إزالة';
      rmBtn.disabled=(it.status==='uploading');
      rmBtn.onclick=()=>{ if (it.previewUrl) URL.revokeObjectURL(it.previewUrl); state.items = state.items.filter(x=>x!==it); renderQueue(); };

      actions.appendChild(st); actions.appendChild(upBtn); actions.appendChild(rmBtn);

      body.appendChild(formRow); body.appendChild(prog); body.appendChild(actions);

      row.appendChild(th); row.appendChild(body);
      wrap.appendChild(row);
      queueEl.appendChild(wrap);
    });

    summary.textContent = `الإجمالي: ${state.items.length} — جاهز: ${queued} — جارٍ: ${uploading} — تم: ${ok} — أخطاء: ${err}`;
  }

  function uploadOne(it){
    if (!ensureTargetSelected()) return;
    if (it.doc_type==='id_card' && !it.doc_side) { alert('اختر جهة الهوية (وجه/ظهر)'); return; }

    it.status='uploading'; it.error=''; it.progress=0; renderQueue();

    const fd=new FormData();
    fd.append('_orphan_csrf', csrf);

    if (BENEFICIARY_ID_LOCKED > 0) fd.append('beneficiary_id', String(BENEFICIARY_ID_LOCKED));
    else if (selectedBeneficiaryId > 0) fd.append('beneficiary_id', String(selectedBeneficiaryId));
    else {
      fd.append('beneficiary_type_id', String(benType.value));
      fd.append('file_number', String(fileNo.value));
    }

    fd.append('doc_type', it.doc_type);
    fd.append('doc_side', it.doc_side || '');
    fd.append('is_shareable', String(it.is_shareable||0));
    fd.append('title', it.title || '');
    fd.append('file', it.file, it.file.name);

    const xhr=new XMLHttpRequest();
    xhr.open('POST','document_upload_ajax.php',true);

    xhr.upload.onprogress=(e)=>{ if(!e.lengthComputable)return; it.progress=Math.round((e.loaded/e.total)*100); renderQueue(); };

    xhr.onreadystatechange=()=>{
      if(xhr.readyState!==4)return;
      if(xhr.status>=200 && xhr.status<300){
        let res=null; try{res=JSON.parse(xhr.responseText||'{}');}catch(e){}
        if(res && res.ok){ it.status='done'; it.progress=100; }
        else { it.status='error'; it.error=(res && res.error)?res.error:'فشل غير معروف'; }
      } else {
        it.status='error'; it.error=(xhr.responseText||('HTTP '+xhr.status)).slice(0,160);
      }
      renderQueue();
    };

    xhr.send(fd);
  }

  async function uploadAll(){
    for(const it of state.items){
      if(it.status==='queued' || it.status==='error'){
        uploadOne(it);
        await new Promise(r=>{
          const t=setInterval(()=>{ if(it.status!=='uploading'){clearInterval(t); r(true);} },250);
        });
      }
    }
    setTimeout(()=>location.reload(),700);
  }

  // drop events + click conflict fix
  ['dragenter','dragover'].forEach(evt=>drop.addEventListener(evt,(e)=>{e.preventDefault();e.stopPropagation();drop.classList.add('drag');}));
  ['dragleave','drop'].forEach(evt=>drop.addEventListener(evt,(e)=>{e.preventDefault();e.stopPropagation();drop.classList.remove('drag');}));
  drop.addEventListener('drop',(e)=>{const files=e.dataTransfer.files; if(files && files.length) addFiles(files);});

  drop.addEventListener('click',(e)=>{ if(e.target && (e.target.closest('button')||e.target.closest('input')||e.target.closest('select'))) return; fileInput.click(); });
  pickBtn.addEventListener('click',(e)=>{ e.stopPropagation(); fileInput.click(); });
  clearBtn.addEventListener('click',(e)=>{ e.stopPropagation(); state.items.forEach(it=>{ if(it.previewUrl) URL.revokeObjectURL(it.previewUrl);}); state.items=[]; renderQueue(); });
  fileInput.addEventListener('change',()=>{ if(fileInput.files) addFiles(fileInput.files); fileInput.value='';});
  uploadAllBtn.addEventListener('click',uploadAll);

  // beneficiary picker
  async function fetchBeneficiaries(typeId,q){
    const url='ajax_beneficiaries.php?type_id='+encodeURIComponent(String(typeId))+'&q='+encodeURIComponent(q||'');
    const res=await fetch(url,{credentials:'same-origin'});
    return res.json();
  }

  let benTimer=null;
  async function refreshBenList(){
    const tid=parseInt(benType?.value||'0',10);
    if(!tid || !benPick) return;
    const query=(benSearch?.value||'').trim();
    const data=await fetchBeneficiaries(tid, query);
    if(!data.ok) return;

    benPick.innerHTML='<option value="">— اختر من النتائج —</option>';
    data.data.forEach(r=>{
      const opt=document.createElement('option');
      opt.value=String(r.id);
      opt.textContent=`(${r.file_number}) ${r.full_name}`;
      opt.setAttribute('data-file', String(r.file_number));
      benPick.appendChild(opt);
    });
  }

  if(benType && benPickWrap){
    benType.addEventListener('change',()=>{
      selectedBeneficiaryId=0;
      const tid=parseInt(benType.value||'0',10);
      benPickWrap.style.display = tid ? '' : 'none';
      if(tid) refreshBenList();
    });
  }

  if(benSearch){
    benSearch.addEventListener('input',()=>{
      clearTimeout(benTimer);
      benTimer=setTimeout(refreshBenList,250);
    });
  }

  if(benPick && fileNo){
    benPick.addEventListener('change',()=>{
      selectedBeneficiaryId=parseInt(benPick.value||'0',10) || 0;
      const opt=benPick.options[benPick.selectedIndex];
      const f=opt ? (opt.getAttribute('data-file')||'') : '';
      if(f) fileNo.value=f;
    });
  }

  renderQueue();

  // modal edit + toggle
  const editModal = new bootstrap.Modal(document.getElementById('editModal'));
  const m_id=document.getElementById('m_id');
  const m_doc_type=document.getElementById('m_doc_type');
  const m_doc_side=document.getElementById('m_doc_side');
  const m_is_shareable=document.getElementById('m_is_shareable');
  const m_title=document.getElementById('m_title');
  const m_err=document.getElementById('m_err');
  const m_ok=document.getElementById('m_ok');
  const m_save=document.getElementById('m_save');

  function showErr(msg){ m_ok.classList.add('d-none'); m_err.classList.remove('d-none'); m_err.textContent=msg; }
  function showOk(){ m_err.classList.add('d-none'); m_ok.classList.remove('d-none'); }

  document.querySelectorAll('.btn-edit').forEach(btn=>{
    btn.addEventListener('click',()=>{
      const tr=btn.closest('tr');
      m_id.value=tr.dataset.id||'';
      m_doc_type.value=tr.dataset.doc_type||'other_docs';
      m_doc_side.value=tr.dataset.doc_side||'';
      m_is_shareable.value=tr.dataset.is_shareable||'0';
      m_title.value=tr.dataset.title||'';
      m_err.classList.add('d-none'); m_ok.classList.add('d-none');
      editModal.show();
    });
  });

  m_save.addEventListener('click', async ()=>{
    const payload=new URLSearchParams();
    payload.set('_orphan_csrf', csrf);
    payload.set('id', m_id.value);
    payload.set('doc_type', m_doc_type.value);
    payload.set('doc_side', m_doc_side.value);
    payload.set('is_shareable', m_is_shareable.value);
    payload.set('title', m_title.value);

    try{
      const res=await fetch('document_update_ajax.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},body:payload.toString(),credentials:'same-origin'});
      const j=await res.json();
      if(!j.ok){ showErr(j.error || 'فشل'); return; }
      showOk();
      setTimeout(()=>location.reload(),500);
    }catch(e){
      showErr('تعذر الاتصال بالسيرفر.');
    }
  });

  document.querySelectorAll('.btn-toggle-shareable').forEach(btn=>{
    btn.addEventListener('click', async ()=>{
      const tr=btn.closest('tr');
      const id=tr.dataset.id;
      const payload=new URLSearchParams();
      payload.set('_orphan_csrf', csrf);
      payload.set('id', id);

      btn.disabled=true;
      try{
        const res=await fetch('document_toggle_shareable_ajax.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},body:payload.toString(),credentials:'same-origin'});
        const j=await res.json();
        if(!j.ok){ alert(j.error || 'فشل'); btn.disabled=false; return; }
        const v = j.data && typeof j.data.is_shareable !== 'undefined' ? j.data.is_shareable : 0;
        tr.dataset.is_shareable=String(v);
        btn.textContent = v===1 ? 'نعم (اضغط)' : 'لا (اضغط)';
        btn.disabled=false;
      }catch(e){
        alert('تعذر الاتصال بالسيرفر.');
        btn.disabled=false;
      }
    });
  });

})();
</script>

</body>
</html>