<?php
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/rbac.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/layout.php';
require_once __DIR__ . '/../../includes/sidebar_helper.php';

requireLogin(); requireRole(ROLE_CLERK);
$GLOBALS['BASE_URL_CSS'] = BASE_URL . '/public/assets/css/main.css';
$user = currentUser(); $pdo = db();

// ── ثوابت أنواع الوثائق ───────────────────────────────────────
$DOC_TYPES = [
    'حكم'           => 'bi-file-earmark-text',
    'محضر'          => 'bi-journal-text',
    'طلب'           => 'bi-file-earmark-arrow-up',
    'استئناف'       => 'bi-arrow-left-right',
    'مذكرة دفاع'   => 'bi-file-earmark-richtext',
    'وثيقة رسمية'  => 'bi-file-earmark-check',
    'إشعار'        => 'bi-bell',
    'أخرى'         => 'bi-file-earmark',
];

// ── معالجة POST ───────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');
    $id = (int)($_POST['id'] ?? 0);

    if ($_POST['action'] === 'add') {
        $caseId  = (int)($_POST['case_id'] ?: 0) ?: null;
        $docType = trim($_POST['doc_type'] ?? '');
        $title   = trim($_POST['title']   ?? '');

        if (!$docType || !$title || empty($_FILES['doc_file']['name'])) {
            echo json_encode(['ok'=>false,'msg'=>'يرجى ملء جميع الحقول ورفع الملف']); exit;
        }

        $res = uploadFile($_FILES['doc_file'], 'clerk-docs');
        if (!$res['success']) { echo json_encode(['ok'=>false,'msg'=>$res['message']]); exit; }

        $fileSize = $_FILES['doc_file']['size'];
        $mimeType = $_FILES['doc_file']['type'];

        $pdo->prepare("INSERT INTO documents (case_id,user_id,doc_type,title,file_path,file_size,mime_type)
            VALUES (?,?,?,?,?,?,?)")
            ->execute([$caseId,$user['id'],$docType,$title,$res['path'],$fileSize,$mimeType]);
        auditLog($user['id'],'add_document','documents',$pdo->lastInsertId(),'رفع وثيقة: '.$title);
        echo json_encode(['ok'=>true]); exit;
    }

    if ($_POST['action'] === 'delete' && $id) {
        $pdo->prepare("DELETE FROM documents WHERE id=?")->execute([$id]);
        auditLog($user['id'],'delete_document','documents',$id,'حذف وثيقة');
        echo json_encode(['ok'=>true]); exit;
    }

    echo json_encode(['ok'=>false]); exit;
}

// ── الفلاتر ───────────────────────────────────────────────────
$search    = trim($_GET['q']      ?? '');
$doctype   = $_GET['doctype']     ?? '';
$case_id   = (int)($_GET['case_id'] ?? 0);
$date_from = $_GET['date_from']   ?? '';
$date_to   = $_GET['date_to']     ?? '';

$where = []; $params = [];
if ($search)    { $where[] = "(d.title LIKE ? OR d.doc_type LIKE ? OR c.case_number LIKE ?)"; $p="%$search%"; $params=array_merge($params,[$p,$p,$p]); }
if ($doctype)   { $where[] = "d.doc_type = ?"; $params[] = $doctype; }
if ($case_id)   { $where[] = "d.case_id = ?"; $params[] = $case_id; }
if ($date_from) { $where[] = "DATE(d.created_at) >= ?"; $params[] = $date_from; }
if ($date_to)   { $where[] = "DATE(d.created_at) <= ?"; $params[] = $date_to; }
$whereSQL = $where ? 'WHERE '.implode(' AND ',$where) : '';

$stmt = $pdo->prepare("
    SELECT d.*, c.case_number, c.title AS case_title,
           u.full_name AS uploader_name
    FROM documents d
    LEFT JOIN cases c ON d.case_id = c.id
    LEFT JOIN users u ON d.user_id = u.id
    $whereSQL
    ORDER BY d.created_at DESC
");
$stmt->execute($params);
$documents = $stmt->fetchAll();

// إحصائيات
$stats = $pdo->query("
    SELECT COUNT(*) AS total,
           COALESCE(SUM(file_size),0) AS total_size,
           COUNT(DISTINCT case_id) AS cases_count,
           COUNT(DISTINCT doc_type) AS types_count
    FROM documents
")->fetch();

// قائمة القضايا للفلتر والنموذج
$cases = $pdo->query("SELECT id, case_number, title FROM cases ORDER BY case_number")->fetchAll();

$notifCount = getUnreadNotifCount($user['id']);
renderHead('الوثائق');
?>
<div class="sidebar" id="sidebar"><?php buildSidebar('documents','clerk'); ?></div>
<div class="sidebar-overlay" id="sidebarOverlay"></div>
<div class="main-wrap">
<?php renderTopbar('إدارة الوثائق', $notifCount); ?>
<div class="page-content">

  <!-- إحصائيات -->
  <div class="row g-3 mb-4">
    <div class="col-6 col-md-3">
      <div class="panel p-3 text-center">
        <div style="font-size:28px;font-weight:800;color:var(--gold)"><?= $stats['total'] ?></div>
        <div style="font-size:12px;color:var(--text-muted)">إجمالي الوثائق</div>
      </div>
    </div>
    <div class="col-6 col-md-3">
      <div class="panel p-3 text-center">
        <div style="font-size:28px;font-weight:800;color:#0d6efd"><?= $stats['cases_count'] ?></div>
        <div style="font-size:12px;color:var(--text-muted)">قضايا مرتبطة</div>
      </div>
    </div>
    <div class="col-6 col-md-3">
      <div class="panel p-3 text-center">
        <div style="font-size:28px;font-weight:800;color:#198754"><?= $stats['types_count'] ?></div>
        <div style="font-size:12px;color:var(--text-muted)">أنواع مختلفة</div>
      </div>
    </div>
    <div class="col-6 col-md-3">
      <div class="panel p-3 text-center">
        <div style="font-size:28px;font-weight:800;color:var(--navy)"><?= round($stats['total_size']/1024/1024,1) ?> MB</div>
        <div style="font-size:12px;color:var(--text-muted)">حجم التخزين</div>
      </div>
    </div>
  </div>

  <!-- شريط الأدوات -->
  <div class="d-flex align-items-center justify-content-between mb-3 flex-wrap gap-3">
    <form method="GET" class="d-flex gap-2 flex-wrap align-items-center">
      <input type="text" name="q" class="form-control" placeholder="بحث بالعنوان / النوع / القضية..." value="<?= htmlspecialchars($search) ?>" style="width:240px">
      <select name="doctype" class="form-select" style="width:150px">
        <option value="">كل الأنواع</option>
        <?php foreach (array_keys($DOC_TYPES) as $dt): ?>
        <option value="<?= $dt ?>" <?= $doctype===$dt?'selected':'' ?>><?= $dt ?></option>
        <?php endforeach; ?>
      </select>
      <select name="case_id" class="form-select" style="width:180px">
        <option value="">كل القضايا</option>
        <?php foreach ($cases as $c): ?>
        <option value="<?= $c['id'] ?>" <?= $case_id===$c['id']?'selected':'' ?>><?= htmlspecialchars($c['case_number']) ?></option>
        <?php endforeach; ?>
      </select>
      <input type="date" name="date_from" class="form-control" value="<?= htmlspecialchars($date_from) ?>" style="width:145px">
      <input type="date" name="date_to"   class="form-control" value="<?= htmlspecialchars($date_to) ?>"   style="width:145px">
      <button class="btn btn-primary"><i class="bi bi-search"></i></button>
      <?php if ($search||$doctype||$case_id||$date_from||$date_to): ?>
      <a href="documents.php" class="btn btn-outline-secondary"><i class="bi bi-x"></i></a>
      <?php endif; ?>
    </form>
    <button class="btn btn-gold" onclick="showAddModal()">
      <i class="bi bi-upload"></i> رفع وثيقة
    </button>
  </div>

  <!-- الجدول -->
  <div class="panel">
    <?php if (empty($documents)): ?>
      <div class="empty-state py-5 text-center">
        <i class="bi bi-folder-x" style="font-size:48px;color:var(--text-muted)"></i>
        <h5 class="mt-3">لا توجد وثائق</h5>
        <p class="text-muted">لم يتم رفع أي وثائق بعد</p>
        <button class="btn btn-gold mt-2" onclick="showAddModal()"><i class="bi bi-upload"></i> رفع وثيقة</button>
      </div>
    <?php else: ?>
    <div class="table-responsive">
      <table class="table dt-table" id="docsTable">
        <thead><tr>
          <th>#</th>
          <th>العنوان</th>
          <th>النوع</th>
          <th>القضية</th>
          <th>الحجم</th>
          <th>رافع الوثيقة</th>
          <th>تاريخ الرفع</th>
          <th>الإجراءات</th>
        </tr></thead>
        <tbody>
        <?php foreach ($documents as $i => $d):
            $icon = $DOC_TYPES[$d['doc_type']] ?? 'bi-file-earmark';
            $sizeKB = $d['file_size'] ? round($d['file_size']/1024,1).' KB' : '—';
            $ext = strtolower(pathinfo($d['file_path'], PATHINFO_EXTENSION));
            $isPdf = $ext === 'pdf';
        ?>
        <tr>
          <td class="text-muted" style="font-size:12px"><?= $i+1 ?></td>
          <td>
            <div class="d-flex align-items-center gap-2">
              <i class="bi <?= $icon ?>" style="font-size:18px;color:var(--gold)"></i>
              <div>
                <div style="font-weight:600"><?= htmlspecialchars($d['title']) ?></div>
                <div style="font-size:11px;color:var(--text-muted)"><?= strtoupper($ext) ?></div>
              </div>
            </div>
          </td>
          <td><span class="badge" style="background:rgba(201,168,76,.15);color:var(--navy)"><?= htmlspecialchars($d['doc_type']) ?></span></td>
          <td>
            <?php if ($d['case_id']): ?>
            <a href="case-view.php?id=<?= $d['case_id'] ?>" class="text-navy fw-700 text-decoration-none" style="font-size:13px">
              <?= htmlspecialchars($d['case_number']) ?>
            </a>
            <?php else: ?>
            <span class="text-muted">—</span>
            <?php endif; ?>
          </td>
          <td style="font-size:13px"><?= $sizeKB ?></td>
          <td style="font-size:13px"><?= htmlspecialchars($d['uploader_name'] ?: '—') ?></td>
          <td style="white-space:nowrap;font-size:13px">
            <div><?= date('d/m/Y', strtotime($d['created_at'])) ?></div>
            <div style="font-size:11px;color:var(--text-muted)"><?= date('H:i', strtotime($d['created_at'])) ?></div>
          </td>
          <td>
            <div class="d-flex gap-1">
              <a href="<?= htmlspecialchars(BASE_URL.'/'.$d['file_path']) ?>" target="_blank"
                 class="action-btn" title="تحميل / عرض"><i class="bi bi-download"></i></a>
              <?php if ($d['case_id']): ?>
              <a href="case-view.php?id=<?= $d['case_id'] ?>" class="action-btn gold" title="عرض القضية"><i class="bi bi-folder2-open"></i></a>
              <?php endif; ?>
              <button class="action-btn danger" title="حذف" onclick="deleteDoc(<?= $d['id'] ?>)"><i class="bi bi-trash"></i></button>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <?php endif; ?>
  </div>

</div></div>

<!-- مودال رفع وثيقة -->
<div class="modal fade" id="addModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title font-amiri"><i class="bi bi-upload me-2"></i>رفع وثيقة جديدة</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div id="addMsg"></div>
        <div class="row g-3">
          <div class="col-12">
            <label class="form-label">عنوان الوثيقة <span class="text-danger">*</span></label>
            <input type="text" id="dd_title" class="form-control" placeholder="مثال: حكم ابتدائي بتاريخ 01/01/2025">
          </div>
          <div class="col-md-6">
            <label class="form-label">نوع الوثيقة <span class="text-danger">*</span></label>
            <select id="dd_doc_type" class="form-select">
              <option value="">اختر النوع...</option>
              <?php foreach (array_keys($DOC_TYPES) as $dt): ?>
              <option value="<?= $dt ?>"><?= $dt ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-md-6">
            <label class="form-label">القضية المرتبطة</label>
            <select id="dd_case_id" class="form-select">
              <option value="">— اختياري —</option>
              <?php foreach ($cases as $c): ?>
              <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['case_number']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-12">
            <label class="form-label">الملف <span class="text-danger">*</span></label>
            <input type="file" id="dd_file" class="form-control" accept=".pdf,.doc,.docx,.jpg,.jpeg,.png">
            <div class="form-text">الصيغ المقبولة: PDF, Word, صور. الحجم الأقصى: 10 MB</div>
          </div>
          <div id="uploadProgress" class="col-12" style="display:none">
            <div class="progress">
              <div class="progress-bar progress-bar-striped progress-bar-animated bg-gold"
                   style="width:100%;height:8px"></div>
            </div>
            <div class="text-center mt-2" style="font-size:13px;color:var(--text-muted)">جارٍ الرفع...</div>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
        <button class="btn btn-gold" id="submitBtn" onclick="submitDoc()"><i class="bi bi-upload"></i> رفع الوثيقة</button>
      </div>
    </div>
  </div>
</div>

<script>
let addModal;
document.addEventListener('DOMContentLoaded', () => {
  addModal = new bootstrap.Modal(document.getElementById('addModal'));
});
function showAddModal() { addModal.show(); }

function submitDoc() {
  const msg = document.getElementById('addMsg');
  const title = document.getElementById('dd_title').value.trim();
  const docType = document.getElementById('dd_doc_type').value;
  const file = document.getElementById('dd_file').files[0];
  if (!title || !docType || !file) {
    msg.innerHTML = '<div class="alert alert-danger py-2">يرجى ملء جميع الحقول المطلوبة ورفع ملف</div>';
    return;
  }
  if (file.size > 10 * 1024 * 1024) {
    msg.innerHTML = '<div class="alert alert-danger py-2">حجم الملف يتجاوز 10 MB</div>';
    return;
  }

  document.getElementById('uploadProgress').style.display = 'block';
  document.getElementById('submitBtn').disabled = true;

  const fd = new FormData();
  fd.append('action', 'add');
  fd.append('title', title);
  fd.append('doc_type', docType);
  fd.append('case_id', document.getElementById('dd_case_id').value);
  fd.append('doc_file', file);

  fetch('documents.php', { method: 'POST', body: fd })
    .then(r => r.json())
    .then(d => {
      document.getElementById('uploadProgress').style.display = 'none';
      document.getElementById('submitBtn').disabled = false;
      if (d.ok) { location.reload(); }
      else { msg.innerHTML = `<div class="alert alert-danger py-2">${d.msg||'حدث خطأ أثناء الرفع'}</div>`; }
    })
    .catch(() => {
      document.getElementById('uploadProgress').style.display = 'none';
      document.getElementById('submitBtn').disabled = false;
      msg.innerHTML = '<div class="alert alert-danger py-2">حدث خطأ في الاتصال</div>';
    });
}

function deleteDoc(id) {
  if (!confirm('هل تريد حذف هذه الوثيقة نهائياً؟')) return;
  fetch('documents.php', {
    method: 'POST',
    headers: {'Content-Type':'application/x-www-form-urlencoded'},
    body: `action=delete&id=${id}`
  }).then(r => r.json()).then(d => { if (d.ok) location.reload(); });
}
</script>

<?php renderFoot(); ?>