<?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();

// Lawyer profile status
$profile = (function() use ($pdo,$user) {
    $s = $pdo->prepare("SELECT * FROM lawyer_profiles WHERE user_id=?");
    $s->execute([$user['id']]); return $s->fetch();
})();

$myCases = (function() use ($pdo,$user) {
    $s = $pdo->prepare("SELECT c.*,ct.name AS court_name FROM cases c JOIN case_lawyers cl ON c.id=cl.case_id LEFT JOIN courts ct ON c.court_id=ct.id WHERE cl.lawyer_id=? ORDER BY c.created_at DESC");
    $s->execute([$user['id']]); return $s->fetchAll();
})();

$upcomingSessions = (function() use ($pdo,$user) {
    $s = $pdo->prepare("SELECT s.*,c.case_number,c.title AS case_title FROM sessions s JOIN cases c ON s.case_id=c.id JOIN case_lawyers cl ON c.id=cl.case_id WHERE cl.lawyer_id=? AND s.session_date>=NOW() AND s.status='scheduled' ORDER BY s.session_date ASC LIMIT 5");
    $s->execute([$user['id']]); return $s->fetchAll();
})();

$notifCount = getUnreadNotifCount($user['id']);
renderHead('لوحة المحامي');
?>
<div class="sidebar" id="sidebar"><?php buildSidebar('dashboard','lawyer'); ?></div>
<div class="sidebar-overlay" id="sidebarOverlay"></div>
<div class="main-wrap">
<?php renderTopbar('لوحة المحامي', $notifCount); ?>
<div class="page-content">

  <!-- Profile status banner -->
  <?php if ($profile && $profile['review_status'] !== 'approved'): ?>
  <div class="alert <?= $profile['review_status']==='rejected' ? 'alert-danger' : 'alert-gold' ?> mb-4 d-flex align-items-center gap-3">
    <i class="bi <?= $profile['review_status']==='rejected' ? 'bi-x-octagon-fill' : 'bi-hourglass-split' ?>" style="font-size:22px"></i>
    <div>
      <?php if ($profile['review_status']==='rejected'): ?>
      <strong>تم رفض وثائقك.</strong> السبب: <?= htmlspecialchars($profile['rejection_reason']??'غير محدد') ?>.<br>
      <a href="documents.php" class="btn btn-sm btn-danger mt-2"><i class="bi bi-upload"></i> إعادة رفع الوثائق</a>
      <?php else: ?>
      <strong>حسابك قيد المراجعة.</strong> تم تقديم وثائقك وننتظر موافقة المدير. سيتم إشعارك فور اتخاذ القرار.
      <?php endif; ?>
    </div>
  </div>
  <?php elseif (!$profile || !$profile['professional_card']): ?>
  <div class="alert alert-gold mb-4 d-flex align-items-center gap-3">
    <i class="bi bi-file-earmark-arrow-up" style="font-size:22px"></i>
    <div><strong>يرجى رفع وثائقك المهنية</strong> للحصول على الوصول الكامل للمنصة.<br>
    <a href="documents.php" class="btn btn-sm btn-gold mt-2"><i class="bi bi-upload"></i> رفع الوثائق الآن</a></div>
  </div>
  <?php endif; ?>

  <div class="d-flex align-items-center justify-content-between mb-4">
    <h4 class="font-amiri fw-700 mb-0 text-navy">مرحباً، <?= htmlspecialchars($user['name']) ?> 👋</h4>
  </div>

  <div class="row g-3 mb-4">
    <div class="col-6"><div class="stat-card">
      <div class="stat-icon navy"><i class="bi bi-folder2-open"></i></div>
      <div class="stat-body"><div class="stat-value"><?= count($myCases) ?></div><div class="stat-label">قضاياي</div></div>
    </div></div>
    <div class="col-6"><div class="stat-card">
      <div class="stat-icon gold"><i class="bi bi-calendar3"></i></div>
      <div class="stat-body"><div class="stat-value"><?= count($upcomingSessions) ?></div><div class="stat-label">جلسات قادمة</div></div>
    </div></div>
  </div>

  <div class="row g-3">
    <div class="col-lg-6">
      <div class="panel">
        <div class="panel-header"><div class="panel-title"><i class="bi bi-calendar3"></i> جلساتي القادمة</div></div>
        <?php if (empty($upcomingSessions)): ?>
        <div class="empty-state py-4"><i class="bi bi-calendar-x"></i><h5>لا توجد جلسات قادمة</h5></div>
        <?php else: foreach ($upcomingSessions as $s): ?>
        <div class="d-flex align-items-center gap-3 px-4 py-3 border-bottom">
          <div style="width:44px;height:44px;border-radius:10px;background:var(--navy);display:flex;flex-direction:column;align-items:center;justify-content:center;flex-shrink:0">
            <span style="font-size:16px;font-weight:800;color:var(--gold);line-height:1"><?= date('d',strtotime($s['session_date'])) ?></span>
            <span style="font-size:10px;color:rgba(255,255,255,.6)"><?= date('M',strtotime($s['session_date'])) ?></span>
          </div>
          <div style="flex:1;min-width:0">
            <div class="fw-600" style="font-size:13px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis"><?= htmlspecialchars($s['case_title']) ?></div>
            <div style="font-size:11px;color:var(--text-muted)"><?= htmlspecialchars($s['case_number']) ?> &bull; <?= date('H:i',strtotime($s['session_date'])) ?></div>
          </div>
        </div>
        <?php endforeach; endif; ?>
      </div>
    </div>
    <div class="col-lg-6">
      <div class="panel">
        <div class="panel-header"><div class="panel-title"><i class="bi bi-folder2"></i> قضاياي</div><a href="my-cases.php" class="btn btn-sm btn-outline-gold">الكل</a></div>
        <?php if (empty($myCases)): ?>
        <div class="empty-state py-4"><i class="bi bi-folder-x"></i><h5>لا توجد قضايا مسندة إليك</h5></div>
        <?php else: foreach (array_slice($myCases,0,6) as $c):
          $st = CASE_STATUS[$c['status']] ?? ['label'=>$c['status'],'class'=>'secondary'];
        ?>
        <div class="d-flex align-items-center gap-3 px-4 py-3 border-bottom">
          <div style="width:36px;height:36px;border-radius:8px;background:var(--gold-pale);display:flex;align-items:center;justify-content:center;flex-shrink:0"><i class="bi bi-folder2-open text-gold"></i></div>
          <div style="flex:1;min-width:0">
            <div class="fw-600" style="font-size:13px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis"><?= htmlspecialchars($c['title']) ?></div>
            <div style="font-size:11px;color:var(--text-muted)"><?= htmlspecialchars($c['case_number']) ?></div>
          </div>
          <span class="badge bg-<?= $st['class'] ?>"><?= $st['label'] ?></span>
        </div>
        <?php endforeach; endif; ?>
      </div>
    </div>
  </div>
</div></div>
<?php renderFoot(); ?>