<?php
declare(strict_types=1);

require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../inc/layout.php';

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

if (empty($_SESSION['user_id'])) {
    header("Location: ../index.html");
    exit;
}

$pdo = db();
if (!$pdo instanceof PDO) {
    http_response_code(500);
    exit('DB not ready');
}

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

if (!function_exists('h')) {
    function h($v): string
    {
        return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('fmt_date_view')) {
    function fmt_date_view(?string $date): string
    {
        $date = trim((string)$date);
        if ($date === '') {
            return '-';
        }

        $ts = strtotime($date);
        if ($ts === false) {
            return $date;
        }

        return date('Y-m-d', $ts);
    }
}

if (!function_exists('table_columns')) {
    function table_columns(PDO $pdo, string $table): array
    {
        $st = $pdo->prepare("
            SELECT COLUMN_NAME
            FROM INFORMATION_SCHEMA.COLUMNS
            WHERE TABLE_SCHEMA = DATABASE()
              AND TABLE_NAME = ?
        ");
        $st->execute([$table]);
        return $st->fetchAll(PDO::FETCH_COLUMN) ?: [];
    }
}

if (!function_exists('first_existing_column')) {
    function first_existing_column(array $columns, array $candidates): ?string
    {
        foreach ($candidates as $col) {
            if (in_array($col, $columns, true)) {
                return $col;
            }
        }
        return null;
    }
}

if (!function_exists('status_label_ar')) {
    function status_label_ar(?string $status): string
    {
        $status = trim((string)$status);

        return match ($status) {
            'draft', 'مسودة' => 'مسودة',
            'pending_review', 'under_review', 'قيد المراجعة' => 'قيد المراجعة',
            'active', 'ساري' => 'ساري',
            'signed', 'موقع', 'تم التوقيع' => 'موقع',
            'sent_for_sign', 'مرسل للتوقيع' => 'مرسل للتوقيع',
            'expired', 'منتهي' => 'منتهي',
            'cancelled', 'canceled', 'ملغي' => 'ملغي',
            default => $status !== '' ? $status : '-',
        };
    }
}

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) {
    exit('رقم العقد غير صحيح');
}

/* أسماء الأعمدة */
$employeeCols = table_columns($pdo, 'employees');
$typeCols     = table_columns($pdo, 'contract_types');
$contractCols = table_columns($pdo, 'contracts');

$employeeNameCol = in_array('full_name', $employeeCols, true) ? 'full_name' : 'name';
$typeNameCol     = in_array('contract_name', $typeCols, true) ? 'contract_name' : 'name';

$titleCol = first_existing_column($contractCols, [
    'title',
    'contract_name',
    'name',
    'subject'
]);

$contractNoCol = first_existing_column($contractCols, [
    'contract_no',
    'transaction_id',
    'contract_number',
    'reference_no'
]);

$contentHtmlCol = first_existing_column($contractCols, [
    'contract_html',
    'content_html',
    'html_content',
    'template_html',
    'body_html'
]);

$contentTextCol = first_existing_column($contractCols, [
    'contract_content',
    'content',
    'body',
    'description',
    'details',
    'contract_text',
    'text_content'
]);

$titleExpr = $titleCol ? "c.`{$titleCol}`" : "''";
$contractNoExpr = $contractNoCol ? "c.`{$contractNoCol}`" : "CAST(c.id AS CHAR)";
$contentHtmlExpr = $contentHtmlCol ? "c.`{$contentHtmlCol}`" : "NULL";
$contentTextExpr = $contentTextCol ? "c.`{$contentTextCol}`" : "NULL";

/* جلب العقد */
$stmt = $pdo->prepare("
    SELECT 
        c.*,
        {$titleExpr} AS contract_title_value,
        {$contractNoExpr} AS contract_no_value,
        {$contentHtmlExpr} AS contract_html_value,
        {$contentTextExpr} AS contract_text_value,
        cl.name AS client_name,
        cl.email AS client_email,
        cl.phone AS client_phone,
        e.`{$employeeNameCol}` AS lawyer_name,
        ct.`{$typeNameCol}` AS contract_type_name
    FROM contracts c
    LEFT JOIN clients cl ON cl.id = c.client_id
    LEFT JOIN employees e ON e.id = c.lawyer_id
    LEFT JOIN contract_types ct ON ct.id = c.contract_type_id
    WHERE c.id = ?
    LIMIT 1
");
$stmt->execute([$id]);
$contract = $stmt->fetch();

if (!$contract) {
    die("العقد غير موجود");
}

/* جلب المرفقات إذا كان الجدول موجود */
$attachments = [];
try {
    $tableExists = $pdo->query("
        SELECT COUNT(*)
        FROM information_schema.tables
        WHERE table_schema = DATABASE()
          AND table_name = 'contract_files'
    ")->fetchColumn();

    if ((int)$tableExists > 0) {
        $attStmt = $pdo->prepare("
            SELECT id, file_name, file_path, uploaded_at
            FROM contract_files
            WHERE contract_id = ?
            ORDER BY id DESC
        ");
        $attStmt->execute([$id]);
        $attachments = $attStmt->fetchAll();
    }
} catch (Throwable $e) {
    $attachments = [];
}

$titleValue = trim((string)($contract['contract_title_value'] ?? ''));
$contractNo = trim((string)($contract['contract_no_value'] ?? ''));
$transactionId = trim((string)($contract['transaction_id'] ?? ''));
$subject = trim((string)($contract['subject'] ?? ''));

$contentHtml = trim((string)($contract['contract_html_value'] ?? ''));
$contentText = trim((string)($contract['contract_text_value'] ?? ''));

$renderedContract = '';
if ($contentHtml !== '') {
    $renderedContract = $contentHtml;
} elseif ($contentText !== '') {
    $renderedContract = nl2br(h($contentText));
}

$statusLabel = status_label_ar($contract['status'] ?? '-');
$startDateValue = fmt_date_view($contract['start_date'] ?? '');
$endDateValue   = fmt_date_view($contract['end_date'] ?? '');

render_layout_start('عرض العقد');
?>

<style>
:root{
  --hlg-dark:#071a23;
  --hlg-dark-2:#0b2230;
  --hlg-teal:#0ea5b7;
  --hlg-teal-2:#0b7a8f;
  --hlg-line:rgba(255,255,255,.10);
  --hlg-line-soft:rgba(255,255,255,.06);
  --hlg-text:#ffffff;
  --hlg-muted:#9aa7ad;
  --hlg-card:rgba(255,255,255,.035);
  --hlg-card-2:rgba(255,255,255,.04);
  --hlg-shadow:0 18px 44px rgba(0,0,0,.20);
}

.contract-view-wrap{
  max-width:1280px;
  margin:auto;
  padding:30px 30px 40px;
  direction:rtl;
  font-family:'Tajawal',sans-serif;
}

.view-hero{
  position:relative;
  overflow:hidden;
  background:linear-gradient(135deg,#07202b 0%, #0a4450 55%, #0d6677 100%);
  border:1px solid rgba(255,255,255,.08);
  border-radius:26px;
  padding:26px 26px 22px;
  box-shadow:var(--hlg-shadow);
  margin-bottom:18px;
}

.view-hero::before{
  content:"";
  position:absolute;
  inset:auto auto -60px -50px;
  width:180px;
  height:180px;
  border-radius:50%;
  background:rgba(255,255,255,.05);
}

.view-hero::after{
  content:"";
  position:absolute;
  inset:-70px -40px auto auto;
  width:220px;
  height:220px;
  border-radius:50%;
  background:rgba(255,255,255,.04);
}

.view-hero-inner{
  position:relative;
  z-index:2;
  display:flex;
  justify-content:space-between;
  align-items:flex-start;
  gap:16px;
  flex-wrap:wrap;
}

.view-hero-title{
  margin:0 0 8px;
  color:#fff;
  font-size:32px;
  font-weight:800;
}

.view-hero-sub{
  margin:0;
  color:rgba(255,255,255,.85);
  line-height:1.9;
  font-size:14px;
}

.view-hero-actions{
  display:flex;
  gap:10px;
  flex-wrap:wrap;
}

.vbtn{
  display:inline-flex;
  align-items:center;
  justify-content:center;
  gap:8px;
  min-width:145px;
  height:46px;
  padding:0 18px;
  border-radius:14px;
  text-decoration:none;
  font-size:14px;
  font-weight:800;
  cursor:pointer;
  transition:.18s ease;
  border:none;
}

.vbtn:hover{
  transform:translateY(-1px);
}

.vbtn-primary{
  background:linear-gradient(135deg,var(--hlg-teal-2),var(--hlg-teal));
  color:#fff;
  border:1px solid rgba(255,255,255,.10);
  box-shadow:0 10px 24px rgba(14,165,183,.20);
}

.vbtn-light{
  background:rgba(255,255,255,.07);
  color:#fff;
  border:1px solid rgba(255,255,255,.12);
}

.vbtn-gold{
  background:linear-gradient(135deg,#d4af37,#f0c95c);
  color:#1b1b1b;
  border:1px solid rgba(255,255,255,.12);
}

.vbtn-print-mini{
  min-width:auto;
  height:40px;
  padding:0 14px;
  border-radius:12px;
  background:linear-gradient(135deg,var(--hlg-teal-2),var(--hlg-teal));
  color:#fff;
  border:1px solid rgba(255,255,255,.10);
  font-size:13px;
  font-weight:800;
  cursor:pointer;
}

.view-grid{
  display:grid;
  grid-template-columns:repeat(3, 1fr);
  gap:16px;
  margin-bottom:18px;
}

.view-box{
  background:var(--hlg-card);
  border:1px solid var(--hlg-line);
  border-radius:18px;
  padding:16px;
  box-shadow:var(--hlg-shadow);
}

.view-label{
  font-size:12px;
  color:var(--hlg-muted);
  margin-bottom:8px;
  font-weight:700;
}

.view-value{
  min-height:44px;
  color:#fff;
  font-size:15px;
  font-weight:800;
  line-height:1.9;
  word-break:break-word;
}

.view-card{
  background:var(--hlg-card);
  border:1px solid var(--hlg-line);
  border-radius:24px;
  box-shadow:var(--hlg-shadow);
  overflow:hidden;
  margin-bottom:18px;
}

.view-card-head{
  display:flex;
  justify-content:space-between;
  align-items:center;
  gap:14px;
  flex-wrap:wrap;
  padding:18px 20px;
  border-bottom:1px solid var(--hlg-line-soft);
  background:rgba(255,255,255,.03);
}

.view-card-head h2{
  margin:0;
  color:#fff;
  font-size:24px;
  font-weight:800;
}

.view-card-sub{
  margin-top:6px;
  color:var(--hlg-muted);
  font-size:13px;
}

.view-card-head-actions{
  display:flex;
  gap:8px;
  flex-wrap:wrap;
}

.view-card-body{
  padding:20px;
}

.content-wrap{
  background:rgba(255,255,255,.03);
  border:1px solid var(--hlg-line-soft);
  border-radius:20px;
  padding:18px;
}

.content-box{
  background:rgba(255,255,255,.04);
  border:1px solid var(--hlg-line);
  border-radius:18px;
  padding:30px 26px;
  min-height:260px;
  color:#fff;
  line-height:2.05;
  font-size:17px;
}

.content-box h1,
.content-box h2,
.content-box h3,
.content-box h4{
  color:#fff;
  text-align:center;
  margin-top:0;
}

.content-box p{
  margin:0 0 14px;
}

.content-empty{
  color:rgba(255,255,255,.70);
}

.attachments-box{
  margin-top:24px;
  padding:18px;
  border:1px solid var(--hlg-line);
  border-radius:18px;
  background:rgba(255,255,255,.03);
}

.attachments-title{
  margin:0 0 14px;
  color:#fff;
  font-size:18px;
  font-weight:800;
}

.attachments-empty{
  padding:14px;
  border-radius:12px;
  background:rgba(255,255,255,.04);
  color:rgba(255,255,255,.72);
  border:1px dashed rgba(255,255,255,.10);
}

.attachments-list{
  display:flex;
  flex-direction:column;
  gap:10px;
}

.attachment-item{
  display:flex;
  justify-content:space-between;
  align-items:center;
  gap:12px;
  padding:12px 14px;
  border:1px solid rgba(255,255,255,.08);
  border-radius:12px;
  background:rgba(255,255,255,.04);
}

.attachment-info{
  display:flex;
  flex-direction:column;
  gap:4px;
  min-width:0;
}

.attachment-name{
  color:#fff;
  font-weight:700;
  word-break:break-word;
}

.attachment-date{
  font-size:12px;
  color:rgba(255,255,255,.60);
}

.attachment-actions{
  display:flex;
  gap:8px;
  flex-wrap:wrap;
}

.attachment-btn{
  display:inline-flex;
  align-items:center;
  justify-content:center;
  padding:9px 14px;
  border-radius:10px;
  text-decoration:none;
  font-size:13px;
  font-weight:700;
  border:1px solid rgba(255,255,255,.12);
  background:rgba(255,255,255,.06);
  color:#fff;
}

.attachment-btn.open{
  background:linear-gradient(135deg,#0b7a8f,#0f9db5);
  border-color:rgba(255,255,255,.14);
}

@media (max-width: 980px){
  .contract-view-wrap{
    padding:18px 16px 30px;
  }

  .view-grid{
    grid-template-columns:1fr;
  }

  .view-hero-inner{
    flex-direction:column;
  }

  .attachment-item{
    flex-direction:column;
    align-items:flex-start;
  }

  .content-box{
    padding:22px 16px;
    font-size:16px;
  }
}
</style>

<script>
function openPrintWindow(title, bodyHtml) {
  const printWindow = window.open('', '_blank', 'width=1000,height=800');
  if (!printWindow) return;

  printWindow.document.open();
  printWindow.document.write(`
    <!doctype html>
    <html lang="ar" dir="rtl">
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>${title}</title>
      <style>
        @page{
          size:auto;
          margin:12mm;
        }
        html,body{
          margin:0;
          padding:0;
          background:#fff;
          color:#000;
          direction:rtl;
          font-family:Tajawal, Arial, sans-serif;
        }
        body{
          padding:0;
        }
        .print-wrap{
          width:100%;
        }
        .print-wrap *{
          box-sizing:border-box;
        }
        .print-title{
          font-size:24px;
          font-weight:800;
          margin:0 0 14px;
          color:#000;
        }
        .print-subtitle{
          font-size:13px;
          color:#333;
          line-height:1.9;
          margin-bottom:18px;
        }
        .meta-grid{
          display:grid;
          grid-template-columns:1fr 1fr;
          gap:12px;
          margin-bottom:20px;
        }
        .meta-box{
          border:1px solid #ddd;
          border-radius:10px;
          padding:10px 12px;
          background:#fff;
        }
        .meta-label{
          font-size:12px;
          color:#666;
          margin-bottom:6px;
          font-weight:700;
        }
        .meta-value{
          font-size:14px;
          color:#000;
          line-height:1.8;
          font-weight:700;
          word-break:break-word;
        }
        .section-box{
          border:1px solid #ddd;
          border-radius:12px;
          padding:18px;
          background:#fff;
          margin-top:16px;
        }
        .section-title{
          font-size:18px;
          font-weight:800;
          margin:0 0 12px;
          color:#000;
        }
        .print-content{
          font-size:15px;
          line-height:2;
          color:#000;
        }
        .print-content *{
          color:#000 !important;
          background:transparent !important;
          box-shadow:none !important;
          border-color:#ddd !important;
        }
        .print-content h1,
        .print-content h2,
        .print-content h3,
        .print-content h4{
          text-align:center;
          margin-top:0;
        }
        .print-content p{
          margin:0 0 12px;
        }
        .attachments-list{
          display:flex;
          flex-direction:column;
          gap:10px;
        }
        .attachment-item{
          border:1px solid #ddd;
          border-radius:10px;
          padding:10px 12px;
        }
        .attachment-name{
          font-weight:700;
          margin-bottom:4px;
        }
        .attachment-date{
          font-size:12px;
          color:#555;
        }
      </style>
    </head>
    <body>${bodyHtml}</body>
    </html>
  `);
  printWindow.document.close();
  printWindow.focus();

  setTimeout(() => {
    printWindow.print();
    printWindow.close();
  }, 450);
}

function printContractData() {
  const html = `
    <div class="print-wrap">
      <div class="print-title">بيانات العقد</div>
      <div class="print-subtitle">
        تم إنشاء هذه النسخة لغرض الطباعة من نظام إدارة العقود.
      </div>

      <div class="meta-grid">
        <div class="meta-box">
          <div class="meta-label">عنوان العقد</div>
          <div class="meta-value"><?= h($titleValue !== '' ? $titleValue : '-') ?></div>
        </div>

        <div class="meta-box">
          <div class="meta-label">رقم العقد</div>
          <div class="meta-value"><?= h($contractNo !== '' ? $contractNo : '-') ?></div>
        </div>

        <div class="meta-box">
          <div class="meta-label">رقم العملية</div>
          <div class="meta-value"><?= h($transactionId !== '' ? $transactionId : '-') ?></div>
        </div>

        <div class="meta-box">
          <div class="meta-label">الحالة</div>
          <div class="meta-value"><?= h($statusLabel) ?></div>
        </div>

        <div class="meta-box">
          <div class="meta-label">العميل</div>
          <div class="meta-value"><?= h($contract['client_name'] ?? '-') ?></div>
        </div>

        <div class="meta-box">
          <div class="meta-label">البريد الإلكتروني</div>
          <div class="meta-value"><?= h($contract['client_email'] ?? '-') ?></div>
        </div>

        <div class="meta-box">
          <div class="meta-label">الهاتف</div>
          <div class="meta-value"><?= h($contract['client_phone'] ?? '-') ?></div>
        </div>

        <div class="meta-box">
          <div class="meta-label">المحامي</div>
          <div class="meta-value"><?= h($contract['lawyer_name'] ?? '-') ?></div>
        </div>

        <div class="meta-box">
          <div class="meta-label">نوع العقد</div>
          <div class="meta-value"><?= h($contract['contract_type_name'] ?? '-') ?></div>
        </div>

        <div class="meta-box">
          <div class="meta-label">تاريخ البداية</div>
          <div class="meta-value"><?= h($startDateValue) ?></div>
        </div>

        <div class="meta-box">
          <div class="meta-label">تاريخ الانتهاء</div>
          <div class="meta-value"><?= h($endDateValue) ?></div>
        </div>

        <div class="meta-box">
          <div class="meta-label">تاريخ الطباعة</div>
          <div class="meta-value"><?= h(date('Y-m-d H:i')) ?></div>
        </div>
      </div>

      <?php if ($subject !== ''): ?>
      <div class="section-box">
        <div class="section-title">موضوع العقد</div>
        <div class="print-content"><?= nl2br(h($subject)) ?></div>
      </div>
      <?php endif; ?>

      <div class="section-box">
        <div class="section-title">مرفقات العقد</div>
        <?php if (!$attachments): ?>
          <div class="print-content">لا توجد مرفقات لهذا العقد.</div>
        <?php else: ?>
          <div class="attachments-list">
            <?php foreach ($attachments as $file): ?>
              <div class="attachment-item">
                <div class="attachment-name"><?= h($file['file_name'] ?? 'ملف مرفق') ?></div>
                <div class="attachment-date"><?= h($file['uploaded_at'] ?? '') ?></div>
              </div>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </div>
    </div>
  `;

  openPrintWindow('طباعة بيانات العقد', html);
}

function printContractText() {
  const contractHtml = <?= json_encode($renderedContract, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;

  const html = `
    <div class="print-wrap">
      <div class="print-title"><?= h($titleValue !== '' ? $titleValue : 'العقد') ?></div>
      <div class="print-subtitle">
        رقم العقد: <?= h($contractNo !== '' ? $contractNo : '-') ?><br>
        العميل: <?= h($contract['client_name'] ?? '-') ?><br>
        المحامي: <?= h($contract['lawyer_name'] ?? '-') ?><br>
        تاريخ الطباعة: <?= h(date('Y-m-d H:i')) ?>
      </div>

      <div class="section-box">
        <div class="section-title">نص العقد</div>
        <div class="print-content">
          ${contractHtml && contractHtml.trim() !== ''
            ? contractHtml
            : '<div>لا يوجد نص محفوظ لهذا العقد حاليًا.</div>'}
        </div>
      </div>
    </div>
  `;

  openPrintWindow('طباعة نص العقد', html);
}
</script>

<div class="contract-view-wrap">

  <div class="view-hero">
    <div class="view-hero-inner">
      <div>
        <h1 class="view-hero-title">عرض العقد</h1>
        <p class="view-hero-sub">استعراض بيانات العقد، مرفقاته، ونصه النهائي داخل النظام بشكل متوافق مع الواجهة الداكنة.</p>
      </div>

      <div class="view-hero-actions">
        <a href="sign/send.php?contract_id=<?= (int)$contract['id'] ?>" class="vbtn vbtn-gold">إرسال للتوقيع</a>
        <button type="button" class="vbtn vbtn-primary" onclick="printContractData()">طباعة البيانات</button>
        <a href="index.php" class="vbtn vbtn-light">رجوع</a>
      </div>
    </div>
  </div>

  <div class="view-grid">
    <div class="view-box">
      <div class="view-label">عنوان العقد</div>
      <div class="view-value"><?= h($titleValue !== '' ? $titleValue : '-') ?></div>
    </div>

    <div class="view-box">
      <div class="view-label">رقم العقد</div>
      <div class="view-value"><?= h($contractNo !== '' ? $contractNo : '-') ?></div>
    </div>

    <div class="view-box">
      <div class="view-label">رقم العملية</div>
      <div class="view-value"><?= h($transactionId !== '' ? $transactionId : '-') ?></div>
    </div>

    <div class="view-box">
      <div class="view-label">العميل</div>
      <div class="view-value"><?= h($contract['client_name'] ?? '-') ?></div>
    </div>

    <div class="view-box">
      <div class="view-label">المحامي</div>
      <div class="view-value"><?= h($contract['lawyer_name'] ?? '-') ?></div>
    </div>

    <div class="view-box">
      <div class="view-label">نوع العقد</div>
      <div class="view-value"><?= h($contract['contract_type_name'] ?? '-') ?></div>
    </div>

    <div class="view-box">
      <div class="view-label">الحالة</div>
      <div class="view-value"><?= h($statusLabel) ?></div>
    </div>

    <div class="view-box">
      <div class="view-label">تاريخ البداية</div>
      <div class="view-value"><?= h($startDateValue) ?></div>
    </div>

    <div class="view-box">
      <div class="view-label">تاريخ الانتهاء</div>
      <div class="view-value"><?= h($endDateValue) ?></div>
    </div>
  </div>

  <?php if ($subject !== ''): ?>
    <div class="view-card">
      <div class="view-card-head">
        <div>
          <h2>موضوع العقد</h2>
          <div class="view-card-sub">الوصف المختصر أو الغرض القانوني للعقد.</div>
        </div>
      </div>
      <div class="view-card-body">
        <div class="content-wrap">
          <div class="content-box"><?= nl2br(h($subject)) ?></div>
        </div>
      </div>
    </div>
  <?php endif; ?>

  <div class="view-card" id="contractTextCard">
    <div class="view-card-head">
      <div>
        <h2>نص العقد</h2>
        <div class="view-card-sub">إذا كان العقد مولدًا أو محفوظًا كنص داخلي فسيظهر هنا.</div>
      </div>

      <div class="view-card-head-actions">
        <button type="button" class="vbtn-print-mini" onclick="printContractText()">🖨 طباعة نص العقد</button>
      </div>
    </div>

    <div class="view-card-body">
      <div class="content-wrap">
        <div class="content-box">
          <?php if ($renderedContract !== ''): ?>
            <?= $renderedContract ?>
          <?php else: ?>
            <div class="content-empty">لا يوجد نص محفوظ لهذا العقد حاليًا.</div>
          <?php endif; ?>
        </div>
      </div>

      <div class="attachments-box">
        <h3 class="attachments-title">مرفقات العقد</h3>

        <?php if (!$attachments): ?>
          <div class="attachments-empty">لا توجد مرفقات لهذا العقد</div>
        <?php else: ?>
          <div class="attachments-list">
            <?php foreach ($attachments as $file): ?>
              <?php
                $filePath = trim((string)($file['file_path'] ?? ''));
                $fileUrl  = '../' . ltrim($filePath, '/');
              ?>
              <div class="attachment-item">
                <div class="attachment-info">
                  <div class="attachment-name"><?= h($file['file_name'] ?? 'ملف مرفق') ?></div>
                  <div class="attachment-date"><?= h($file['uploaded_at'] ?? '') ?></div>
                </div>

                <div class="attachment-actions">
                  <a class="attachment-btn open" href="<?= h($fileUrl) ?>" target="_blank" rel="noopener">
                    فتح المرفق
                  </a>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </div>
    </div>
  </div>

</div>

<?php render_layout_end(); ?>