<?php $__env->startSection('title', 'تعديل مستند — مراسلات'); ?>
<?php $__env->startSection('page-title', 'تعديل مستند'); ?>
<?php $__env->startSection('breadcrumb', 'رئيسي / المستندات / تعديل'); ?>

<?php $__env->startSection('styles'); ?>
<link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-lite.min.css" rel="stylesheet">
<style>
  :root{
    --teal:#00b09b;--teal-dk:#008f7a;--teal-lt:rgba(0,176,155,.10);--teal-glow:rgba(0,176,155,.20);
    --blue:#1a8fff;--blue-lt:rgba(26,143,255,.10);
    --red:#e74c3c;--red-lt:rgba(231,76,60,.10);
    --gold:#f5a623;--gold-lt:rgba(245,166,35,.10);
    --purple:#7c6fcd;--purple-lt:rgba(124,111,205,.10);
    --text:#2c3e50;--text-mid:#546e7a;--muted:#90a4ae;
    --border:#e0e7ef;--white:#fff;--bg:#f0f3f8;--input-bg:#f8fafc;
    --sh:0 2px 10px rgba(0,0,0,.07);--sh-md:0 4px 20px rgba(0,0,0,.09);
  }

  .breadcrumb-bar{display:flex;align-items:center;gap:6px;font-size:12px;color:var(--muted);margin-bottom:18px}
  .breadcrumb-bar a{color:var(--teal);text-decoration:none;font-weight:600}
  .pg-hdr{display:flex;align-items:center;justify-content:space-between;margin-bottom:22px;flex-wrap:wrap;gap:10px}
  .pg-hdr h1{font-size:20px;font-weight:900;color:var(--text)}
  .pg-hdr .sub{font-size:14.5px;color:var(--muted);margin-top:3px}

  .page-grid{display:grid;grid-template-columns:1fr 290px;gap:18px;align-items:start}

  /* cards */
  .form-card{background:var(--white);border:1px solid var(--border);border-radius:14px;overflow:hidden;box-shadow:var(--sh);animation:cIn .4s ease both;margin-bottom:18px}
  @keyframes cIn{from{opacity:0;transform:translateY(12px)}to{opacity:1;transform:translateY(0)}}
  .fc-hdr{display:flex;align-items:center;gap:12px;padding:18px 22px;border-bottom:1px solid var(--border);background:linear-gradient(90deg,rgba(245,166,35,.05),transparent)}
  .fc-icon{width:40px;height:40px;border-radius:10px;background:var(--gold-lt);display:flex;align-items:center;justify-content:center;font-size:19px;color:var(--gold);flex-shrink:0}
  .fc-icon.blue{background:var(--blue-lt);color:var(--blue)}
  .fc-title{font-size:15px;font-weight:800;color:var(--text)}
  .fc-sub{font-size:14.5px;color:var(--muted);margin-top:2px}
  .fc-body{padding:24px}

  /* current info */
  .current-info{display:flex;align-items:flex-start;gap:10px;background:var(--gold-lt);border:1px solid rgba(245,166,35,.3);border-radius:10px;padding:12px 14px;margin-bottom:20px;font-size:12.5px;color:#8a6200}
  .current-info i{font-size:16px;color:var(--gold);flex-shrink:0;margin-top:1px}
  .current-info strong{color:var(--text)}

  /* form rows */
  .form-row{display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:16px}
  .form-row.full{grid-template-columns:1fr}
  .fg{display:flex;flex-direction:column;gap:6px}
  .flbl{font-size:12.5px;font-weight:700;color:var(--text-mid);display:flex;align-items:center;gap:5px}
  .flbl i{font-size:14px;color:var(--muted)}
  .req{color:var(--red);margin-right:1px}

  .iw{position:relative}
  .iico{position:absolute;right:13px;top:50%;transform:translateY(-50%);color:var(--muted);display:flex;font-size:16px;pointer-events:none;transition:color .2s}
  .fc-input,.fc-select{width:100%;background:var(--input-bg);border:1.5px solid var(--border);border-radius:10px;padding:12px 42px 12px 14px;font-family:'Cairo',sans-serif;font-size:13.5px;color:var(--text);outline:none;direction:rtl;transition:border-color .2s,box-shadow .2s,background .2s;appearance:none;-webkit-appearance:none}
  .fc-input::placeholder{color:#b0bec5}
  .fc-input:focus,.fc-select:focus{border-color:var(--teal);background:var(--white);box-shadow:0 0 0 3px var(--teal-glow)}
  .fc-input:focus~.iico,.fc-select:focus~.iico{color:var(--teal)}
  .fc-input[readonly]{background:#f3f6fb;color:var(--muted);cursor:default}
  .fc-input[readonly]:focus{border-color:var(--border);box-shadow:none}
  .sel-arr{position:absolute;left:13px;top:50%;transform:translateY(-50%);color:var(--muted);font-size:14px;pointer-events:none}

  /* summernote */
  .note-editor.note-frame{border:1.5px solid var(--border)!important;border-radius:10px!important;overflow:hidden;font-family:'Cairo',sans-serif!important}
  .note-toolbar{background:#fafcff!important;border-bottom:1px solid var(--border)!important;padding:6px 8px!important}
  .note-editable{direction:rtl;text-align:right;font-family:'Cairo',sans-serif!important;font-size:13.5px!important;min-height:160px!important;padding:14px!important}
  .note-statusbar{background:#fafcff!important;border-top:1px solid var(--border)!important}

  /* attachments */
  .att-list{display:flex;flex-wrap:wrap;gap:8px;margin-bottom:12px}
  .att-chip{display:inline-flex;align-items:center;gap:7px;background:var(--bg);border:1px solid var(--border);border-radius:9px;padding:7px 12px;font-size:12.5px;color:var(--text-mid);text-decoration:none;transition:background .16s,border-color .16s}
  .att-chip:hover{background:#e8ecf4;border-color:#c8d0de;color:var(--text)}
  .att-chip i{font-size:15px;color:var(--teal)}
  .no-att{font-size:12.5px;color:var(--muted);display:flex;align-items:center;gap:6px;padding:8px 0}
  .no-att i{font-size:15px}

  /* file drop */
  .file-drop{border:2px dashed var(--border);border-radius:10px;padding:18px;text-align:center;background:var(--input-bg);cursor:pointer;transition:border-color .2s,background .2s;position:relative}
  .file-drop:hover{border-color:var(--teal);background:var(--teal-lt)}
  .file-drop input[type=file]{position:absolute;inset:0;opacity:0;cursor:pointer;width:100%;height:100%}
  .file-drop-icon{font-size:26px;color:var(--muted);margin-bottom:5px}
  .file-drop-text{font-size:12.5px;color:var(--muted)}
  .file-drop-text span{color:var(--teal);font-weight:700}
  .file-list{margin-top:8px;display:flex;flex-wrap:wrap;gap:6px}
  .file-chip{display:inline-flex;align-items:center;gap:5px;background:var(--teal-lt);color:var(--teal);padding:3px 10px;border-radius:20px;font-size:14.5px;font-weight:600}
/* ══ CUSTOM MULTI-SELECT (edit) ══ */
.ms-wrap{position:relative}
.ms-trigger{
  width:100%;min-height:46px;background:var(--input-bg);
  border:1.5px solid var(--border);border-radius:10px;
  padding:6px 42px 6px 10px;
  font-family:'Cairo',sans-serif;font-size:13px;color:var(--text);
  cursor:pointer;direction:rtl;text-align:right;
  display:flex;flex-wrap:wrap;align-items:center;gap:5px;
  transition:border-color .2s,box-shadow .2s,background .2s;
  user-select:none;
}
.ms-trigger:hover,.ms-trigger.open{border-color:var(--teal);background:var(--white);box-shadow:0 0 0 3px var(--teal-glow)}
.ms-trigger .placeholder{color:#b0bec5;font-size:13px;line-height:1}
.ms-caret{position:absolute;left:12px;top:50%;transform:translateY(-50%);color:var(--muted);font-size:14px;pointer-events:none;transition:transform .2s}
.ms-wrap.open .ms-caret{transform:translateY(-50%) rotate(180deg)}
.ms-chip{
  display:inline-flex;align-items:center;gap:5px;
  padding:3px 8px 3px 4px;border-radius:20px;
  font-size:11.5px;font-weight:700;line-height:1.3;
  max-width:160px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;
}
.ms-chip.user-chip{background:var(--teal-lt);color:var(--teal-dk)}
.ms-chip.group-chip{background:var(--purple-lt);color:var(--purple)}
.ms-chip .chip-remove{
  width:14px;height:14px;border-radius:50%;
  background:rgba(0,0,0,.12);color:inherit;
  display:flex;align-items:center;justify-content:center;
  font-size:9px;cursor:pointer;flex-shrink:0;
  transition:background .14s;
}
.ms-chip .chip-remove:hover{background:rgba(0,0,0,.25)}
.ms-dropdown{
  position:absolute;top:calc(100% + 6px);right:0;left:0;z-index:9999;
  background:var(--white);border:1.5px solid var(--border);border-radius:12px;
  box-shadow:0 8px 30px rgba(0,0,0,.12);
  overflow:hidden;display:none;flex-direction:column;
  animation:dropIn .18s ease;
}
@keyframes dropIn{from{opacity:0;transform:translateY(-6px)}to{opacity:1;transform:translateY(0)}}
.ms-dropdown.open{display:flex}
.ms-search-box{padding:10px 12px;border-bottom:1px solid var(--border);position:relative;flex-shrink:0}
.ms-search-input{
  width:100%;background:var(--bg);border:1.5px solid var(--border);border-radius:8px;
  padding:8px 34px 8px 10px;
  font-family:'Cairo',sans-serif;font-size:13px;color:var(--text);
  outline:none;direction:rtl;transition:border-color .16s;
}
.ms-search-input:focus{border-color:var(--teal)}
.ms-search-input::placeholder{color:#b0bec5}
.ms-search-inner-icon{position:absolute;right:22px;top:50%;transform:translateY(-50%);color:var(--muted);font-size:14px;pointer-events:none}
.ms-list{overflow-y:auto;padding:6px;max-height:260px}
.ms-group-label{display:flex;align-items:center;gap:8px;padding:8px 10px 5px;font-size:10.5px;font-weight:800;letter-spacing:.8px;color:var(--muted);text-transform:uppercase}
.ms-option{
  display:flex;align-items:center;gap:10px;
  padding:9px 10px;border-radius:8px;cursor:pointer;
  font-family:'Cairo',sans-serif;font-size:13px;color:var(--text-mid);
  transition:background .12s;user-select:none;
}
.ms-option:hover{background:var(--bg)}
.ms-option.selected{background:var(--teal-lt);color:var(--teal-dk)}
.ms-option.selected.group-opt{background:var(--purple-lt);color:var(--purple)}
.ms-option .opt-check{
  width:17px;height:17px;border-radius:4px;border:1.5px solid var(--border);
  display:flex;align-items:center;justify-content:center;
  flex-shrink:0;font-size:10px;color:transparent;
  transition:background .14s,border-color .14s,color .14s;
}
.ms-option.selected .opt-check{background:var(--teal);border-color:var(--teal);color:#fff}
.ms-option.selected.group-opt .opt-check{background:var(--purple);border-color:var(--purple);color:#fff}
.ms-option .opt-icon{width:28px;height:28px;border-radius:7px;display:flex;align-items:center;justify-content:center;font-size:13px;flex-shrink:0}
.user-opt .opt-icon{background:var(--teal-lt);color:var(--teal)}
.group-opt .opt-icon{background:var(--purple-lt);color:var(--purple)}
.ms-option .opt-name{flex:1;font-weight:600}
.ms-option .opt-type{font-size:10px;color:var(--muted);background:var(--bg);padding:1px 6px;border-radius:4px}
.ms-summary{padding:8px 12px;border-top:1px solid var(--border);font-size:11.5px;color:var(--muted);display:flex;align-items:center;justify-content:space-between;flex-shrink:0;background:#fafcff}
.ms-clear-all{color:var(--red);font-weight:700;cursor:pointer;font-size:11.5px;background:none;border:none;font-family:'Cairo',sans-serif;padding:0}
.ms-clear-all:hover{text-decoration:underline}
  /* recipient tabs */
  .rec-section{background:rgba(26,143,255,.04);border:1.5px solid rgba(26,143,255,.18);border-radius:12px;padding:18px}
  .rec-tabs{display:flex;gap:6px;margin-bottom:16px}
  .rec-tab{flex:1;padding:9px;background:var(--white);border:1.5px solid var(--border);border-radius:9px;text-align:center;font-family:'Cairo',sans-serif;font-size:13px;font-weight:700;color:var(--text-mid);cursor:pointer;transition:all .16s;display:flex;align-items:center;justify-content:center;gap:7px}
  .rec-tab:hover{border-color:var(--blue);color:var(--blue)}
  .rec-tab.active{background:var(--blue);border-color:var(--blue);color:#fff;box-shadow:0 3px 12px rgba(26,143,255,.28)}
  .rec-tab i{font-size:17px}
  .rec-panel{display:none}
  .rec-panel.active{display:block;animation:fadeUp .25s ease}
  @keyframes fadeUp{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:translateY(0)}}

  /* actions */
  .actions-bar{display:flex;align-items:center;justify-content:space-between;padding:16px 22px;border-top:1px solid var(--border);background:#fafcff;flex-wrap:wrap;gap:10px;border-radius:0 0 14px 14px}
  .actions-note{font-size:14.5px;color:var(--muted);display:flex;align-items:center;gap:5px}
  .actions-note i{color:var(--teal);font-size:14px}
  .actions-btns{display:flex;gap:10px}
  .btn-cancel{display:inline-flex;align-items:center;gap:6px;padding:10px 18px;background:var(--white);color:var(--text-mid);border:1.5px solid var(--border);border-radius:10px;font-family:'Cairo',sans-serif;font-size:13px;font-weight:600;cursor:pointer;text-decoration:none;transition:background .16s}
  .btn-cancel:hover{background:var(--bg)}
  .btn-save{display:inline-flex;align-items:center;gap:7px;padding:10px 22px;background:var(--gold);color:#fff;border:none;border-radius:10px;font-family:'Cairo',sans-serif;font-size:13.5px;font-weight:800;cursor:pointer;box-shadow:0 4px 14px rgba(245,166,35,.3);transition:background .16s,transform .14s;position:relative;overflow:hidden}
  .btn-save::after{content:'';position:absolute;inset:0;background:linear-gradient(180deg,rgba(255,255,255,.14) 0%,transparent 55%)}
  .btn-save:hover{background:#d4880a;transform:translateY(-1px)}

  /* side card */
  .side-card{background:var(--white);border:1px solid var(--border);border-radius:14px;overflow:hidden;box-shadow:var(--sh);animation:cIn .4s .1s ease both;position:sticky;top:80px}
  .side-hdr{padding:15px 18px;border-bottom:1px solid var(--border);background:linear-gradient(90deg,rgba(245,166,35,.05),transparent)}
  .side-title{font-size:13.5px;font-weight:800;color:var(--text);display:flex;align-items:center;gap:8px}
  .side-title i{color:var(--gold);font-size:16px}
  .side-body{padding:16px 18px}
  .meta-item{display:flex;align-items:flex-start;gap:10px;padding:9px 0;border-bottom:1px solid #f3f6fa}
  .meta-item:last-child{border-bottom:none}
  .meta-icon{width:32px;height:32px;border-radius:8px;background:var(--teal-lt);display:flex;align-items:center;justify-content:center;font-size:15px;color:var(--teal);flex-shrink:0}
  .meta-icon.gold{background:var(--gold-lt);color:var(--gold)}
  .meta-icon.blue{background:var(--blue-lt);color:var(--blue)}
  .meta-icon.purple{background:var(--purple-lt);color:var(--purple)}
  .meta-ml{font-size:14px;color:var(--muted);margin-bottom:2px}
  .meta-mv{font-size:13px;font-weight:700;color:var(--text)}

  @media(max-width:960px){.page-grid{grid-template-columns:1fr}.side-card{position:static}.form-row{grid-template-columns:1fr}}
</style>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>

<div class="breadcrumb-bar">
  <a href="<?php echo e(route('admin.dashboard')); ?>"><i class="las la-home"></i> الرئيسية</a>
  <i class="las la-angle-left" style="font-size:10px"></i>
  <a href="<?php echo e(route('documents.index')); ?>">المستندات</a>
  <i class="las la-angle-left" style="font-size:10px"></i>
  <span>تعديل: <?php echo e($document->document_number); ?></span>
</div>

<div class="pg-hdr">
  <div>
    <h1>تعديل مستند</h1>
    <div class="sub"><?php echo e($document->subject); ?> — تحديث بيانات المستند</div>
  </div>
</div>

<form method="POST" action="<?php echo e(route('documents.update', $document->id)); ?>" enctype="multipart/form-data" id="editForm">
<?php echo csrf_field(); ?>
<?php echo method_field('PUT'); ?>

<div class="page-grid">
  <div>

    <!-- ══ Card 1: بيانات المستند ══ -->
    <div class="form-card">
      <div class="fc-hdr">
        <div class="fc-icon"><i class="las la-file-alt"></i></div>
        <div>
          <div class="fc-title">بيانات المستند</div>
          <div class="fc-sub">تعديل المعلومات الأساسية للمستند</div>
        </div>
      </div>
      <div class="fc-body">

        <!-- current info -->
        <div class="current-info">
          <i class="las la-info-circle"></i>
          <span>تعديل المستند رقم: <strong><?php echo e($document->document_number); ?></strong> — أُنشئ بتاريخ <?php echo e(optional($document->created_at)->format('Y/m/d')); ?></span>
        </div>

        <!-- رقم التسجيل + تاريخ الإنشاء -->
        <div class="form-row">
          <div class="fg">
            <label class="flbl"><i class="las la-hashtag"></i> رقم التسجيل</label>
            <div class="iw">
              <input type="text" class="fc-input" value="<?php echo e($document->id); ?>" readonly>
              <span class="iico"><i class="las la-tag"></i></span>
            </div>
          </div>
          <div class="fg">
            <label class="flbl"><i class="las la-calendar"></i> تاريخ التسجيل</label>
            <div class="iw">
              <input type="date" name="date" class="fc-input"
                value="<?php echo e(optional($document->created_at)->format('Y-m-d')); ?>" readonly>
              <span class="iico"><i class="las la-calendar-check"></i></span>
            </div>
          </div>
        </div>

        <!-- رقم المستند + تاريخ المستند -->
        <div class="form-row">
          <div class="fg">
            <label class="flbl"><i class="las la-barcode"></i> رقم المستند <span class="req">*</span></label>
            <div class="iw">
              <input type="text" name="document_number" class="fc-input"
                placeholder="رقم المستند"
                value="<?php echo e(old('document_number', $document->document_number)); ?>" required>
              <span class="iico"><i class="las la-barcode"></i></span>
            </div>
          </div>
          <div class="fg">
            <label class="flbl"><i class="las la-calendar-alt"></i> تاريخ المستند <span class="req">*</span></label>
            <div class="iw">
            <input type="date" name="document_date" class="fc-input"
       value="<?php echo e(old('document_date', optional($document->document_date)->format('Y-m-d'))); ?>"
       required>
              <span class="iico"><i class="las la-calendar-alt"></i></span>
            </div>
          </div>
        </div>
<?php if($document->type === 'incoming'): ?>
  <div class="form-row">
    <div class="fg">
      <label class="flbl">
        <i class="las la-file-invoice"></i> رقم المستند الداخلي <span class="req">*</span>
      </label>
      <div class="iw">
        <input type="text" name="internal_document_number" class="fc-input"
          value="<?php echo e(old('internal_document_number', $document->internal_document_number)); ?>"
          required>
        <span class="iico"><i class="las la-file-invoice"></i></span>
      </div>
    </div>

    <div class="fg">
      <label class="flbl">
        <i class="las la-calendar-day"></i> تاريخ الاستناد <span class="req">*</span>
      </label>
      <div class="iw">
        <input type="date" name="reference_date" class="fc-input"
           value="<?php echo e(old('reference_date', optional($document->reference_date)->format('Y-m-d'))); ?>"
           required>
        <span class="iico"><i class="las la-calendar-day"></i></span>
      </div>
    </div>
  </div>
<?php endif; ?>
        <!-- عنوان المستند -->
        <div class="form-row full" style="margin-bottom:20px">
          <div class="fg">
            <label class="flbl"><i class="las la-heading"></i> عنوان المستند <span class="req">*</span></label>
            <div class="iw">
              <input type="text" name="subject" class="fc-input"
                placeholder="عنوان المستند"
                value="<?php echo e(old('subject', $document->subject)); ?>" required>
              <span class="iico"><i class="las la-heading"></i></span>
            </div>
          </div>
        </div>

        <!-- Summernote -->
        <div class="fg" style="margin-bottom:0">
          <label class="flbl"><i class="las la-align-right"></i> الموضوع / التفاصيل</label>
          <textarea name="content" class="summernote"><?php echo e(old('content', $document->content)); ?></textarea>
        </div>

      </div>
    </div>

    <!-- ══ Card 2: المرفقات ══ -->
    <div class="form-card">
      <div class="fc-hdr">
        <div class="fc-icon" style="background:var(--purple-lt);color:var(--purple)"><i class="las la-paperclip"></i></div>
        <div>
          <div class="fc-title">المرفقات</div>
          <div class="fc-sub">إدارة مرفقات المستند</div>
        </div>
      </div>
      <div class="fc-body">

        <!-- المرفقات الحالية -->
        <div class="fg" style="margin-bottom:18px">
          <label class="flbl"><i class="las la-folder-open"></i> المرفقات الحالية</label>
          <?php if(!empty($document->attachments)): ?>
            <div class="att-list">
              <?php $__currentLoopData = $document->attachments; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $file): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <a href="<?php echo e(asset($file['path'])); ?>" target="_blank" class="att-chip">
                  <i class="las la-file-download"></i>
                  <?php echo e($file['name']); ?>

                </a>
              <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </div>
          <?php else: ?>
            <div class="no-att">
              <i class="las la-folder-open"></i>
              لا توجد مرفقات حالية
            </div>
          <?php endif; ?>
        </div>

        <!-- إضافة مرفقات جديدة -->
        <div class="fg">
          <label class="flbl"><i class="las la-plus-circle"></i> إضافة مرفقات جديدة</label>
          <div class="file-drop" id="fileDrop">
            <input type="file" name="attachments[]" multiple id="fileInput" onchange="showFiles(this)">
            <div class="file-drop-icon"><i class="las la-cloud-upload-alt"></i></div>
            <div class="file-drop-text">اسحب الملفات هنا أو <span>اضغط للاختيار</span></div>
            <div style="font-size:14px;color:var(--muted);margin-top:3px">PDF, Word, Excel, صور — حتى 10MB</div>
          </div>
          <div class="file-list" id="fileList"></div>
        </div>

      </div>
    </div>

   <!-- ══ Card 3: المستلمون ══ -->
<div class="form-card">
  <div class="fc-hdr">
    <div class="fc-icon blue"><i class="las la-share-alt"></i></div>
    <div>
      <div class="fc-title">إرسال إلى</div>
      <div class="fc-sub">اختر مستخدمين أو أقسام — يمكن اختيار أكثر من واحد</div>
    </div>
  </div>
  <div class="fc-body">
    <div id="hiddenRecipients"></div>

    <div class="fg">
      <label class="flbl"><i class="las la-users"></i> المستلمون <span class="req">*</span></label>

      <div class="ms-wrap" id="msWrap">
        <div class="ms-trigger" id="msTrigger" onclick="toggleDropdown()">
          <span class="placeholder" id="msPlaceholder">ابحث أو اختر مستخدمين وأقسام...</span>
        </div>
        <i class="las la-angle-down ms-caret" id="msCaret"></i>

        <div class="ms-dropdown" id="msDropdown">
          <div class="ms-search-box">
            <input type="text" class="ms-search-input" id="msSearchInput"
              placeholder="ابحث بالاسم..." oninput="filterOptions(this.value)" autocomplete="off">
            <i class="las la-search ms-search-inner-icon"></i>
          </div>
          <div class="ms-list" id="msList">

            <div class="ms-group-label" data-group="users">
              <i class="las la-user" style="color:var(--teal)"></i> المستخدمون
            </div>
            <?php $__currentLoopData = $users; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $user): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
            <div class="ms-option user-opt"
                 data-type="user"
                 data-id="<?php echo e($user->id); ?>"
                 data-name="<?php echo e($user->name); ?>"
                 onclick="toggleOption(this)">
              <div class="opt-check"><i class="las la-check"></i></div>
              <div class="opt-icon"><i class="las la-user"></i></div>
              <span class="opt-name"><?php echo e($user->name); ?></span>
              <span class="opt-type">مستخدم</span>
            </div>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

            <div class="ms-group-label" data-group="groups" style="margin-top:6px">
              <i class="las la-layer-group" style="color:var(--purple)"></i> الأقسام
            </div>
            <?php $__currentLoopData = $groups; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $group): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
            <div class="ms-option group-opt"
                 data-type="group"
                 data-id="<?php echo e($group->id); ?>"
                 data-name="<?php echo e($group->name); ?>"
                 onclick="toggleOption(this)">
              <div class="opt-check"><i class="las la-check"></i></div>
              <div class="opt-icon"><i class="las la-layer-group"></i></div>
              <span class="opt-name"><?php echo e($group->name); ?></span>
              <span class="opt-type"><?php echo e($group->parent_id ? 'قسم فرعي' : 'قسم رئيسي'); ?></span>
            </div>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

          </div>
          <div class="ms-summary" id="msSummary" style="display:none">
            <span id="msSummaryText"></span>
            <button type="button" class="ms-clear-all" onclick="clearAll()">مسح الكل</button>
          </div>
        </div>
      </div>

    </div>
  </div>
</div>
    <!-- actions -->
    <div class="actions-bar" style="background:var(--white);border:1px solid var(--border);border-radius:14px;box-shadow:var(--sh)">
      <div class="actions-note">
        <i class="las la-info-circle"></i>
        الحقول المعلّمة بـ <span style="color:var(--red);font-weight:700;margin:0 2px">*</span> إلزامية
      </div>
      <div class="actions-btns">
        <a href="<?php echo e(route('documents.index')); ?>" class="btn-cancel">
          <i class="las la-times"></i> إلغاء
        </a>
        <button type="submit" class="btn-save">
          <i class="las la-save"></i> حفظ التعديلات
        </button>
      </div>
    </div>

  </div><!-- end main col -->

  <!-- ══ SIDE ══ -->
  <div class="side-card">
    <div class="side-hdr">
      <div class="side-title"><i class="las la-info-circle"></i> بيانات المستند الحالية</div>
    </div>
    <div class="side-body">

      <div class="meta-item">
        <div class="meta-icon"><i class="las la-hashtag"></i></div>
        <div><div class="meta-ml">رقم التسجيل</div><div class="meta-mv">#<?php echo e($document->id); ?></div></div>
      </div>

      <div class="meta-item">
        <div class="meta-icon gold"><i class="las la-barcode"></i></div>
        <div><div class="meta-ml">رقم المستند</div><div class="meta-mv"><?php echo e($document->document_number); ?></div></div>
      </div>

      <div class="meta-item">
        <div class="meta-icon blue"><i class="las la-calendar-alt"></i></div>
        <div><div class="meta-ml">تاريخ المستند</div><div class="meta-mv"><?php echo e(optional($document->document_date)->format('Y/m/d') ?? '—'); ?></div></div>
      </div>

      <div class="meta-item">
        <div class="meta-icon" style="background:rgba(124,111,205,.1);color:var(--purple)"><i class="las la-user"></i></div>
        <div><div class="meta-ml">المرسِل</div><div class="meta-mv"><?php echo e($document->sender->name ?? '—'); ?></div></div>
      </div>

      <div class="meta-item">
        <div class="meta-icon" style="background:var(--blue-lt);color:var(--blue)"><i class="las la-share-alt"></i></div>
        <div>
          <div class="meta-ml">المستلم الحالي</div>
          <div class="meta-mv">
            <?php if($document->receiverUser): ?>
              <span style="display:flex;align-items:center;gap:5px;font-size:12.5px">
                <i class="las la-user" style="color:var(--teal)"></i>
                <?php echo e($document->receiverUser->name); ?>

              </span>
            <?php elseif($document->receiverGroup): ?>
              <span style="display:flex;align-items:center;gap:5px;font-size:12.5px">
                <i class="las la-users" style="color:var(--purple)"></i>
                <?php echo e($document->receiverGroup->name); ?>

              </span>
            <?php else: ?>
              <span style="color:var(--muted)">—</span>
            <?php endif; ?>
          </div>
        </div>
      </div>

      <div class="meta-item">
        <div class="meta-icon"><i class="las la-calendar-plus"></i></div>
        <div><div class="meta-ml">تاريخ الإنشاء</div><div class="meta-mv"><?php echo e(optional($document->created_at)->format('Y/m/d')); ?></div></div>
      </div>

      <?php if(!empty($document->attachments)): ?>
      <div class="meta-item">
        <div class="meta-icon" style="background:var(--purple-lt);color:var(--purple)"><i class="las la-paperclip"></i></div>
        <div><div class="meta-ml">المرفقات</div><div class="meta-mv"><?php echo e(count($document->attachments)); ?> مرفق</div></div>
      </div>
      <?php endif; ?>

    </div>
  </div>

</div>
</form>

<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-lite.min.js"></script>
<script>

  // Summernote
  $(document).ready(function(){
    $('.summernote').summernote({
      placeholder:'اكتب تفاصيل المستند هنا...',
      tabsize:2, height:200,
      toolbar:[
        ['style',['bold','italic','underline','clear']],
        ['para',['ul','ol','paragraph']],
        ['table',['table']],
        ['insert',['link']],
        ['view',['fullscreen','codeview']]
      ],
      callbacks:{onInit:function(){$('.note-editable').attr('dir','rtl')}}
    });
  });

// ── القيم الحالية من الـ DB ──
const existingUsers  = <?php echo json_encode($existingUserIds ?? [], 15, 512) ?>;
const existingGroups = <?php echo json_encode($existingGroupIds ?? [], 15, 512) ?>;

// ── Multi-Select Logic ──
const selected = [];

window.addEventListener('DOMContentLoaded', function() {
  // تحميل القيم الحالية
  document.querySelectorAll('.ms-option').forEach(opt => {
    const type = opt.dataset.type;
    const id   = opt.dataset.id;
    const shouldSelect =
      (type === 'user'  && existingUsers.map(String).includes(String(id))) ||
      (type === 'group' && existingGroups.map(String).includes(String(id)));

    if (shouldSelect) {
      selected.push({ type, id, name: opt.dataset.name });
      opt.classList.add('selected');
    }
  });
  renderChips();
  updateSummary();
});

function toggleDropdown() {
  const dd = document.getElementById('msDropdown');
  const wrap = document.getElementById('msWrap');
  const trigger = document.getElementById('msTrigger');
  const isOpen = dd.classList.contains('open');
  if (isOpen) {
    dd.classList.remove('open');
    trigger.classList.remove('open');
    wrap.classList.remove('open');
  } else {
    dd.classList.add('open');
    trigger.classList.add('open');
    wrap.classList.add('open');
    document.getElementById('msSearchInput').focus();
  }
}

document.addEventListener('click', function(e) {
  const wrap = document.getElementById('msWrap');
  if (!wrap.contains(e.target)) {
    document.getElementById('msDropdown').classList.remove('open');
    document.getElementById('msTrigger').classList.remove('open');
    wrap.classList.remove('open');
  }
});

function toggleOption(el) {
  const type = el.dataset.type;
  const id   = el.dataset.id;
  const name = el.dataset.name;
  const idx  = selected.findIndex(s => s.type === type && s.id === id);
  if (idx === -1) {
    selected.push({type, id, name});
    el.classList.add('selected');
  } else {
    selected.splice(idx, 1);
    el.classList.remove('selected');
  }
  renderChips();
  updateSummary();
}

function renderChips() {
  const trigger = document.getElementById('msTrigger');
  const placeholder = document.getElementById('msPlaceholder');
  trigger.querySelectorAll('.ms-chip').forEach(c => c.remove());
  if (selected.length === 0) { placeholder.style.display = ''; return; }
  placeholder.style.display = 'none';
  selected.forEach(s => {
    const chip = document.createElement('span');
    chip.className = 'ms-chip ' + (s.type === 'user' ? 'user-chip' : 'group-chip');
    chip.innerHTML = `
      ${s.type === 'group' ? '<i class="las la-layer-group" style="font-size:11px"></i>' : ''}
      ${s.name}
      <span class="chip-remove" onclick="removeSelected('${s.type}','${s.id}',event)">✕</span>
    `;
    trigger.insertBefore(chip, trigger.querySelector('.placeholder'));
  });
}

function removeSelected(type, id, e) {
  e.stopPropagation();
  const idx = selected.findIndex(s => s.type === type && s.id === id);
  if (idx !== -1) selected.splice(idx, 1);
  const opt = document.querySelector(`.ms-option[data-type="${type}"][data-id="${id}"]`);
  if (opt) opt.classList.remove('selected');
  renderChips();
  updateSummary();
}

function clearAll() {
  selected.length = 0;
  document.querySelectorAll('.ms-option.selected').forEach(o => o.classList.remove('selected'));
  renderChips();
  updateSummary();
}

function updateSummary() {
  const summary = document.getElementById('msSummary');
  const txt = document.getElementById('msSummaryText');
  if (selected.length > 0) {
    summary.style.display = 'flex';
    const users  = selected.filter(s => s.type === 'user').length;
    const groups = selected.filter(s => s.type === 'group').length;
    let parts = [];
    if (users)  parts.push(users  + ' مستخدم');
    if (groups) parts.push(groups + ' قسم');
    txt.textContent = 'تم اختيار: ' + parts.join(' + ');
  } else {
    summary.style.display = 'none';
  }
}

function filterOptions(val) {
  const q = val.trim().toLowerCase();
  document.querySelectorAll('.ms-option').forEach(opt => {
    opt.style.display = (!q || opt.dataset.name.toLowerCase().includes(q)) ? '' : 'none';
  });
  ['users','groups'].forEach(g => {
    const label = document.querySelector(`.ms-group-label[data-group="${g}"]`);
    const opts  = document.querySelectorAll(`.ms-option[data-type="${g === 'users' ? 'user' : 'group'}"]`);
    if (label) label.style.display = [...opts].some(o => o.style.display !== 'none') ? '' : 'none';
  });
}

// Inject hidden inputs on submit
document.getElementById('editForm').addEventListener('submit', function(e) {
  if (selected.length === 0) {
    e.preventDefault();
    alert('يرجى اختيار مستلم واحد على الأقل');
    return;
  }
  const container = document.getElementById('hiddenRecipients');
  container.innerHTML = '';
  selected.forEach(s => {
    const input = document.createElement('input');
    input.type  = 'hidden';
    input.name  = s.type === 'user' ? 'to_user_ids[]' : 'to_group_ids[]';
    input.value = s.id;
    container.appendChild(input);
  });
});
  // File display
  function showFiles(input) {
    const list = document.getElementById('fileList');
    list.innerHTML = '';
    const icons = {pdf:'📄',doc:'📝',docx:'📝',xls:'📊',xlsx:'📊',jpg:'🖼️',jpeg:'🖼️',png:'🖼️'};
    Array.from(input.files).forEach(f => {
      const ext = f.name.split('.').pop().toLowerCase();
      list.innerHTML += `<span class="file-chip">${icons[ext]||'📎'} ${f.name}</span>`;
    });
  }
</script>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('admin.layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /home/gamcoiraq/sctl.gamcoiraq.com/resources/views/admin/documents/edit.blade.php ENDPATH**/ ?>