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

$id = (int)($_GET['id'] ?? 0);
// قيد الوصول: المحامي يطّلع فقط على القضايا المسندة إليه
requireCaseAccess($id);

$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
                       FROM cases c
                       LEFT JOIN courts ct ON c.court_id=ct.id
                       WHERE c.id=?");
$case->execute([$id]); $case = $case->fetch();
if (!$case) { header('Location: my-cases.php'); exit; }

$sessions  = (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(); })();
$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(); })();

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

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

  <div class="alert alert-info d-flex align-items-center gap-2 mb-3" style="font-size:13px">
    <i class="bi bi-shield-check"></i>
    أنت تطّلع على هذه القضية بصفتك طرفاً مسنداً إليها. للاطلاع للقراءة فقط.
    <a href="my-cases.php" class="ms-auto btn btn-sm btn-outline-secondary"><i class="bi bi-arrow-right"></i> قضاياي</a>
  </div>

  <!-- 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>
          </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; <?= COURT_BRANCHES[$case['court_branch'] ?? 'ordinary'] ?? '' ?>
            &bull; <?= htmlspecialchars($case['court_name'] ?? 'غير محددة') ?>
          </div>
        </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">
    <!-- بيانات القضية + المحامون -->
    <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>
          <?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>

    <!-- الجلسات + الأحكام + الوثائق -->
    <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></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></tr></thead>
          <tbody>
          <?php foreach ($sessions as $i=>$s):
            $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> <span style="font-size:11px;color:var(--gold)"><?= date('H:i',strtotime($s['session_date'])) ?></span></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>
          </tr>
          <?php endforeach; ?>
          </tbody>
        </table></div>
        <?php endif; ?>
      </div>

      <?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>
              <?php if (!empty($j['is_default'])): ?>
                <span class="badge bg-info">غيابي</span>
              <?php else: ?>
                <span class="badge bg-secondary">حضوري</span>
              <?php endif; ?>
            </td>
            <td><span class="badge bg-<?= $jStat[1] ?>"><?= $jStat[0] ?></span></td>
          </tr>
          <?php endforeach; ?>
          </tbody>
        </table></div>
      </div>
      <?php endif; ?>

      <div class="panel mb-3">
        <div class="panel-header"><div class="panel-title"><i class="bi bi-files"></i> الوثائق (<?= count($documents) ?>)</div></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></tr></thead>
          <tbody>
          <?php foreach ($documents as $d):
            $typeLabel = CASE_DOC_TYPES[$d['doc_type']] ?? $d['doc_type'];
            $isFoundation = ($d['doc_type'] === 'foundation');
          ?>
          <tr>
            <td>
              <?php if ($isFoundation): ?>
                <span class="badge bg-gold" style="color:var(--navy)"><?= $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', strtotime($d['created_at'])) ?></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(); ?>
