<?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, ROLE_ADMIN);
$GLOBALS['BASE_URL_CSS'] = BASE_URL . '/public/assets/css/main.css';
$user = currentUser(); $pdo = db();

$id   = (int)($_GET['id'] ?? 0);
$case = $pdo->prepare("SELECT c.*, ct.name AS court_name, ct.branch AS court_branch_label, ct.level AS court_level,
                              ct.wilaya_code, ct.daira, u.full_name AS clerk_name
                       FROM cases c
                       LEFT JOIN courts ct ON c.court_id=ct.id
                       LEFT JOIN users u ON c.clerk_id=u.id
                       WHERE c.id=?");
$case->execute([$id]); $case = $case->fetch();
if (!$case) { header('Location: cases.php'); exit; }

// وثائق القضية (تشمل وثيقة التأسيس + المرفقات)
$documents = (function() use ($pdo,$id) {
    $s = $pdo->prepare("SELECT * FROM documents WHERE case_id=? ORDER BY created_at ASC");
    $s->execute([$id]); return $s->fetchAll();
})();

$sessions  = $pdo->prepare("SELECT s.*, sm.decision_type, sm.new_session_date FROM sessions s LEFT JOIN session_minutes sm ON s.id=sm.session_id WHERE s.case_id=? ORDER BY s.session_date DESC")->execute([$id]) && false ?: (function() use ($pdo,$id) { $s=$pdo->prepare("SELECT s.*,sm.decision_type,sm.new_session_date FROM sessions s LEFT JOIN session_minutes sm ON s.id=sm.session_id WHERE s.case_id=? ORDER BY s.session_date DESC"); $s->execute([$id]); return $s->fetchAll(); })();
$judgments = (function() use ($pdo,$id) { $s=$pdo->prepare("SELECT * FROM judgments WHERE case_id=? ORDER BY judgment_date DESC"); $s->execute([$id]); return $s->fetchAll(); })();
$appeals   = (function() use ($pdo,$id) { $s=$pdo->prepare("SELECT * FROM appeals WHERE case_id=? ORDER BY created_at DESC"); $s->execute([$id]); return $s->fetchAll(); })();
$lawyers   = (function() use ($pdo,$id) { $s=$pdo->prepare("SELECT u.full_name,u.email,cl.role FROM case_lawyers cl JOIN users u ON cl.lawyer_id=u.id WHERE cl.case_id=?"); $s->execute([$id]); return $s->fetchAll(); })();

$notifCount = getUnreadNotifCount($user['id']);
$stageIndex = array_search($case['stage'], array_keys(STAGES));
$stages     = array_keys(STAGES);

renderHead('عرض القضية');
?>
<div class="sidebar" id="sidebar"><?php buildSidebar('cases','clerk'); ?></div>
<div class="sidebar-overlay" id="sidebarOverlay"></div>
<div class="main-wrap">
<?php renderTopbar('ملف القضية: ' . htmlspecialchars($case['case_number']), $notifCount); ?>
<div class="page-content">

<?php if ($_GET['msg']??'' === 'created'): ?>
<div class="alert alert-success alert-dismissible mb-3"><i class="bi bi-check-circle-fill me-2"></i> تم إنشاء القضية بنجاح! رقمها: <strong><?= htmlspecialchars($case['case_number']) ?></strong> <button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>

  <!-- Header card -->
  <div class="panel mb-3">
    <div class="panel-body">
      <div class="d-flex align-items-start justify-content-between gap-3 flex-wrap">
        <div>
          <div class="d-flex align-items-center gap-3 mb-2">
            <span class="badge bg-navy" style="font-size:13px;padding:6px 14px"><?= htmlspecialchars($case['case_number']) ?></span>
            <?php $st = CASE_STATUS[$case['status']] ?? ['label'=>$case['status'],'class'=>'secondary']; ?>
            <span class="badge bg-<?= $st['class'] ?>"><?= $st['label'] ?></span>
            <?php $prior=['low'=>['منخفضة','secondary'],'normal'=>['عادية','info'],'high'=>['مرتفعة','warning'],'urgent'=>['عاجلة','danger']][$case['priority']]??['عادية','secondary']; ?>
            <span class="badge bg-<?= $prior[1] ?>"><?= $prior[0] ?></span>
          </div>
          <h4 class="font-amiri fw-700 mb-1 text-navy"><?= htmlspecialchars($case['title']) ?></h4>
          <div style="font-size:13px;color:var(--text-muted)"><?= CASE_TYPES[$case['case_type']]??$case['case_type'] ?> &bull; <?= htmlspecialchars($case['court_name']??'غير محدد') ?></div>
        </div>
        <div class="d-flex gap-2 flex-wrap">
          <a href="case-edit.php?id=<?= $id ?>" class="btn btn-sm btn-outline-gold"><i class="bi bi-pencil"></i> تعديل</a>
          <a href="session-new.php?case_id=<?= $id ?>" class="btn btn-sm btn-primary"><i class="bi bi-calendar-plus"></i> جلسة جديدة</a>
          <a href="judgment-new.php?case_id=<?= $id ?>" class="btn btn-sm btn-gold"><i class="bi bi-award"></i> إصدار حكم</a>
          <button class="btn btn-sm btn-outline-secondary" onclick="printSection('caseDetail')"><i class="bi bi-printer"></i></button>
        </div>
      </div>

      <!-- Stage timeline -->
      <div class="stage-timeline mt-4">
        <?php foreach (STAGES as $stageKey => $stageLabel):
          $idx = array_search($stageKey, $stages);
          $cls = $idx < $stageIndex ? 'done' : ($idx === $stageIndex ? 'active' : '');
        ?>
        <div class="stage-step <?= $cls ?>">
          <div class="stage-dot">
            <?php if ($idx < $stageIndex): ?><i class="bi bi-check"></i>
            <?php elseif ($idx === $stageIndex): ?><i class="bi bi-record-circle"></i>
            <?php else: ?><?= $idx+1 ?><?php endif; ?>
          </div>
          <div class="stage-label"><?= $stageLabel ?></div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
  </div>

  <div class="row g-3" id="caseDetail">
    <!-- Info + lawyers -->
    <div class="col-lg-4">
      <div class="panel mb-3">
        <div class="panel-header"><div class="panel-title"><i class="bi bi-info-circle"></i> بيانات القضية</div></div>
        <div class="panel-body" style="font-size:14px">
          <div class="d-flex justify-content-between py-2 border-bottom"><span class="text-muted">المدعي</span><strong><?= htmlspecialchars($case['plaintiff']) ?></strong></div>
          <div class="d-flex justify-content-between py-2 border-bottom"><span class="text-muted">المدعى عليه</span><strong><?= htmlspecialchars($case['defendant']) ?></strong></div>
          <div class="d-flex justify-content-between py-2 border-bottom"><span class="text-muted">فرع القضاء</span><strong><?= COURT_BRANCHES[$case['court_branch'] ?? 'ordinary'] ?? '—' ?></strong></div>
          <?php if (!empty($case['court_level'])): ?>
          <div class="d-flex justify-content-between py-2 border-bottom"><span class="text-muted">درجة المحكمة</span><strong><?= COURT_LEVELS[$case['court_level']]['label'] ?? $case['court_level'] ?></strong></div>
          <?php endif; ?>
          <?php if (!empty($case['wilaya_code']) && isset(WILAYAS[$case['wilaya_code']])): ?>
          <div class="d-flex justify-content-between py-2 border-bottom"><span class="text-muted">الولاية</span><strong><?= WILAYAS[$case['wilaya_code']] ?></strong></div>
          <?php endif; ?>
          <div class="d-flex justify-content-between py-2 border-bottom"><span class="text-muted">تاريخ الإيداع</span><strong><?= date('d/m/Y',strtotime($case['filing_date'])) ?></strong></div>
          <div class="d-flex justify-content-between py-2 border-bottom"><span class="text-muted">أمين الضبط</span><strong><?= htmlspecialchars($case['clerk_name']) ?></strong></div>
          <?php if (!empty($case['foundation_doc_path'])): ?>
          <div class="d-flex justify-content-between py-2 border-bottom align-items-center">
            <span class="text-muted">وثيقة التأسيس</span>
            <a href="<?= BASE_URL ?>/public/assets/uploads/<?= htmlspecialchars($case['foundation_doc_path']) ?>"
               target="_blank" class="btn btn-sm btn-outline-gold">
              <i class="bi bi-file-earmark-text"></i> فتح العريضة
            </a>
          </div>
          <?php endif; ?>
          <?php if ($case['description']): ?>
          <div class="mt-3"><p class="text-muted mb-1" style="font-size:12px">الوصف / الموضوع</p><p style="font-size:13px"><?= nl2br(htmlspecialchars($case['description'])) ?></p></div>
          <?php endif; ?>
        </div>
      </div>
      <?php if ($lawyers): ?>
      <div class="panel">
        <div class="panel-header"><div class="panel-title"><i class="bi bi-person-badge"></i> المحامون</div></div>
        <?php foreach ($lawyers as $lw): ?>
        <div class="d-flex align-items-center gap-3 px-4 py-3 border-bottom">
          <div style="width:36px;height:36px;border-radius:50%;background:var(--gold-pale);display:flex;align-items:center;justify-content:center;color:var(--gold);font-weight:700"><?= mb_substr($lw['full_name'],0,1,'UTF-8') ?></div>
          <div><div style="font-size:13px;font-weight:600"><?= htmlspecialchars($lw['full_name']) ?></div><div style="font-size:11px;color:var(--text-muted)"><?= $lw['role']==='plaintiff_lawyer'?'محامي المدعي':'محامي المدعى عليه' ?></div></div>
        </div>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>
    </div>

    <!-- Sessions -->
    <div class="col-lg-8">
      <div class="panel mb-3">
        <div class="panel-header">
          <div class="panel-title"><i class="bi bi-calendar3"></i> الجلسات (<?= count($sessions) ?>)</div>
          <a href="session-new.php?case_id=<?= $id ?>" class="btn btn-sm btn-primary"><i class="bi bi-plus"></i> جلسة جديدة</a>
        </div>
        <?php if (empty($sessions)): ?>
        <div class="empty-state py-3"><i class="bi bi-calendar-x"></i><h5>لا توجد جلسات مسجلة</h5></div>
        <?php else: ?>
        <div class="table-responsive"><table class="table">
          <thead><tr><th>#</th><th>تاريخ الجلسة</th><th>النوع</th><th>القاضي</th><th>الحالة</th><th>القرار</th><th></th></tr></thead>
          <tbody>
          <?php foreach ($sessions as $i=>$s):
            $sType=['initial'=>'ابتدائية','continuation'=>'استمرار','judgment'=>'حكم','appeal'=>'استئناف'][$s['session_type']]??$s['session_type'];
            $sStat=['scheduled'=>['مجدولة','info'],'in_progress'=>['جارية','warning'],'completed'=>['منتهية','success'],'cancelled'=>['ملغاة','danger']][$s['status']]??[$s['status'],'secondary'];
            $dec=['adjournment'=>'تأجيل','judgment'=>'حكم','interlocutory'=>'تمهيدي','dismissal'=>'رفض'][$s['decision_type']??'']??'—';
          ?>
          <tr>
            <td><?= $i+1 ?></td>
            <td><strong><?= date('d/m/Y',strtotime($s['session_date'])) ?></strong><div style="font-size:11px;color:var(--gold)"><?= date('H:i',strtotime($s['session_date'])) ?></div></td>
            <td><?= $sType ?></td>
            <td style="font-size:13px"><?= htmlspecialchars($s['judge_name']??'—') ?></td>
            <td><span class="badge bg-<?= $sStat[1] ?>"><?= $sStat[0] ?></span></td>
            <td><?= $dec ?></td>
            <td>
              <div class="d-flex gap-1">
                <a href="session-minutes.php?session_id=<?= $s['id'] ?>" class="action-btn gold" title="المحضر"><i class="bi bi-journal-text"></i></a>
              </div>
            </td>
          </tr>
          <?php endforeach; ?>
          </tbody>
        </table></div>
        <?php endif; ?>
      </div>

      <!-- Judgments -->
      <?php if ($judgments): ?>
      <div class="panel mb-3">
        <div class="panel-header"><div class="panel-title"><i class="bi bi-award"></i> الأحكام (<?= count($judgments) ?>)</div></div>
        <div class="table-responsive"><table class="table">
          <thead><tr><th>رقم الحكم</th><th>نوع الحكم</th><th>تاريخ الإصدار</th><th>الحالة</th><th>منطوق الحكم</th></tr></thead>
          <tbody>
          <?php foreach ($judgments as $j):
            $jStat=['issued'=>['صادر','success'],'appealed'=>['مطعون فيه','warning'],'final'=>['نهائي','navy'],'cancelled'=>['ملغى','danger']][$j['status']]??[$j['status'],'secondary'];
          ?>
          <tr>
            <td><?= htmlspecialchars($j['judgment_number']??'—') ?></td>
            <td><?= STAGES[$j['judgment_type']]??$j['judgment_type'] ?></td>
            <td><?= date('d/m/Y',strtotime($j['judgment_date'])) ?></td>
            <td><span class="badge bg-<?= $jStat[1] ?>"><?= $jStat[0] ?></span></td>
            <td style="max-width:200px;font-size:12px"><?= htmlspecialchars(mb_substr($j['operative_part'],0,60,'UTF-8')) ?>...</td>
          </tr>
          <?php endforeach; ?>
          </tbody>
        </table></div>
      </div>
      <?php endif; ?>

      <!-- Documents -->
      <div class="panel mb-3">
        <div class="panel-header">
          <div class="panel-title"><i class="bi bi-files"></i> وثائق القضية (<?= count($documents) ?>)</div>
          <a href="documents.php?case=<?= $id ?>" class="btn btn-sm btn-outline-gold"><i class="bi bi-plus"></i> إضافة وثيقة</a>
        </div>
        <?php if (empty($documents)): ?>
        <div class="empty-state py-3"><i class="bi bi-file-earmark-x"></i><h6>لا توجد وثائق مرفقة</h6></div>
        <?php else: ?>
        <div class="table-responsive"><table class="table">
          <thead><tr><th>النوع</th><th>الاسم</th><th>تاريخ الرفع</th><th>الحجم</th><th></th></tr></thead>
          <tbody>
          <?php foreach ($documents as $d):
            $typeLabel = CASE_DOC_TYPES[$d['doc_type']] ?? $d['doc_type'];
            $isFoundation = ($d['doc_type'] === 'foundation');
            $sizeKb = $d['file_size'] ? round($d['file_size']/1024, 1) : null;
          ?>
          <tr>
            <td>
              <?php if ($isFoundation): ?>
                <span class="badge bg-gold" style="color:var(--navy)"><i class="bi bi-file-earmark-text"></i> <?= $typeLabel ?></span>
              <?php else: ?>
                <span class="badge bg-secondary"><?= htmlspecialchars($typeLabel) ?></span>
              <?php endif; ?>
            </td>
            <td><?= htmlspecialchars($d['title']) ?></td>
            <td style="font-size:12px"><?= date('d/m/Y H:i', strtotime($d['created_at'])) ?></td>
            <td style="font-size:12px"><?= $sizeKb ? "{$sizeKb} ك.ب" : '—' ?></td>
            <td>
              <a href="<?= BASE_URL ?>/public/assets/uploads/<?= htmlspecialchars($d['file_path']) ?>"
                 target="_blank" class="action-btn gold" title="فتح"><i class="bi bi-eye"></i></a>
            </td>
          </tr>
          <?php endforeach; ?>
          </tbody>
        </table></div>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div></div>
<?php renderFoot(); ?>
