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

// ── ثوابت الجلسات ───────────────────────────────────────────
$SESSION_TYPES = [
    'initial'      => ['label' => 'ابتدائية',     'class' => 'primary'],
    'continuation' => ['label' => 'استمرار',       'class' => 'info'],
    'judgment'     => ['label' => 'جلسة حكم',     'class' => 'gold'],
    'appeal'       => ['label' => 'استئناف',       'class' => 'warning'],
];
$SESSION_STATUS = [
    'scheduled'   => ['label' => 'مجدولة',        'class' => 'primary'],
    'in_progress' => ['label' => 'جارية',          'class' => 'warning'],
    'completed'   => ['label' => 'منتهية',         'class' => 'success'],
    'cancelled'   => ['label' => 'ملغاة',          'class' => 'secondary'],
];

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

    if ($_POST['action'] === 'update_status') {
        $newStatus = $_POST['status'] ?? '';
        if ($id && array_key_exists($newStatus, $SESSION_STATUS)) {
            $pdo->prepare("UPDATE sessions SET status=? WHERE id=?")->execute([$newStatus, $id]);
            // إذا انتهت الجلسة → حدّث حالة القضية إلى مؤجلة إن لم يكن هناك حكم
            if ($newStatus === 'completed') {
                $sess = $pdo->prepare("SELECT case_id,session_type FROM sessions WHERE id=?");
                $sess->execute([$id]);
                $s = $sess->fetch();
                if ($s && $s['session_type'] !== 'judgment') {
                    $pdo->prepare("UPDATE cases SET status='adjourned' WHERE id=? AND status='open'")->execute([$s['case_id']]);
                }
            }
            auditLog($user['id'], 'update_session_status', 'sessions', $id, "تغيير الحالة إلى $newStatus");
            echo json_encode(['ok' => true]);
        } else {
            echo json_encode(['ok' => false]);
        }
    } elseif ($_POST['action'] === 'delete') {
        if ($id) {
            $pdo->prepare("DELETE FROM sessions WHERE id=?")->execute([$id]);
            auditLog($user['id'], 'delete_session', 'sessions', $id, 'حذف جلسة');
            echo json_encode(['ok' => true]);
        }
    }
    exit;
}

// ── الفلاتر ──────────────────────────────────────────────────
$search  = trim($_GET['q']      ?? '');
$status  = $_GET['status']      ?? '';
$type    = $_GET['type']        ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to   = $_GET['date_to']   ?? '';
$view    = $_GET['view']        ?? 'list'; // list | calendar

$where = []; $params = [];
if ($search)    { $where[] = "(c.case_number LIKE ? OR c.title LIKE ? OR s.judge_name LIKE ? OR s.room LIKE ?)"; $p="%$search%"; $params=array_merge($params,[$p,$p,$p,$p]); }
if ($status)    { $where[] = "s.status = ?"; $params[] = $status; }
if ($type)      { $where[] = "s.session_type = ?"; $params[] = $type; }
if ($date_from) { $where[] = "DATE(s.session_date) >= ?"; $params[] = $date_from; }
if ($date_to)   { $where[] = "DATE(s.session_date) <= ?"; $params[] = $date_to; }
$whereSQL = $where ? 'WHERE '.implode(' AND ',$where) : '';

$stmt = $pdo->prepare("
    SELECT s.*, c.case_number, c.title AS case_title, c.case_type,
           u.full_name AS clerk_name
    FROM sessions s
    LEFT JOIN cases c ON s.case_id = c.id
    LEFT JOIN users u ON s.clerk_id = u.id
    $whereSQL
    ORDER BY s.session_date DESC
");
$stmt->execute($params);
$sessions = $stmt->fetchAll();

// إحصائيات سريعة
$stats = $pdo->query("
    SELECT
        COUNT(*) AS total,
        SUM(status='scheduled')   AS scheduled,
        SUM(status='completed')   AS completed,
        SUM(status='in_progress') AS in_progress,
        SUM(DATE(session_date)=CURDATE()) AS today
    FROM sessions
")->fetch();

$notifCount = getUnreadNotifCount($user['id']);
renderHead('الجلسات');
?>
<div class="sidebar" id="sidebar"><?php buildSidebar('sessions','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['scheduled'] ?></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['completed'] ?></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)"><?= $stats['today'] ?></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">
    <div class="d-flex gap-2 flex-wrap">
      <form method="GET" class="d-flex gap-2 flex-wrap align-items-center">
        <input type="hidden" name="view" value="<?= htmlspecialchars($view) ?>">
        <input type="text" name="q" class="form-control" placeholder="بحث برقم القضية / القاضي / القاعة..." value="<?= htmlspecialchars($search) ?>" style="width:250px">
        <select name="status" class="form-select" style="width:130px">
          <option value="">كل الحالات</option>
          <?php foreach ($SESSION_STATUS as $k=>$v): ?>
          <option value="<?= $k ?>" <?= $status===$k?'selected':'' ?>><?= $v['label'] ?></option>
          <?php endforeach; ?>
        </select>
        <select name="type" class="form-select" style="width:130px">
          <option value="">كل الأنواع</option>
          <?php foreach ($SESSION_TYPES as $k=>$v): ?>
          <option value="<?= $k ?>" <?= $type===$k?'selected':'' ?>><?= $v['label'] ?></option>
          <?php endforeach; ?>
        </select>
        <input type="date" name="date_from" class="form-control" value="<?= htmlspecialchars($date_from) ?>" style="width:145px" title="من تاريخ">
        <input type="date" name="date_to"   class="form-control" value="<?= htmlspecialchars($date_to) ?>"   style="width:145px" title="إلى تاريخ">
        <button class="btn btn-primary"><i class="bi bi-search"></i></button>
        <?php if ($search||$status||$type||$date_from||$date_to): ?>
        <a href="sessions.php" class="btn btn-outline-secondary"><i class="bi bi-x"></i></a>
        <?php endif; ?>
      </form>
    </div>
    <div class="d-flex gap-2">
      <button class="btn btn-outline-gold btn-sm" onclick="exportTableExcel('sessionsTable','قائمة_الجلسات')">
        <i class="bi bi-file-excel"></i> Excel
      </button>
      <a href="session-new.php" class="btn btn-gold">
        <i class="bi bi-calendar-plus"></i> جلسة جديدة
      </a>
    </div>
  </div>

  <!-- الجدول -->
  <div class="panel">
    <?php if (empty($sessions)): ?>
      <div class="empty-state py-5 text-center">
        <i class="bi bi-calendar-x" style="font-size:48px;color:var(--text-muted)"></i>
        <h5 class="mt-3">لا توجد جلسات</h5>
        <p class="text-muted">لم يتم العثور على جلسات بهذه المعايير</p>
        <a href="session-new.php" class="btn btn-gold mt-2"><i class="bi bi-calendar-plus"></i> إضافة جلسة</a>
      </div>
    <?php else: ?>
    <div class="table-responsive">
      <table class="table dt-table" id="sessionsTable">
        <thead><tr>
          <th>#</th>
          <th>رقم القضية</th>
          <th>عنوان القضية</th>
          <th>نوع الجلسة</th>
          <th>التاريخ والوقت</th>
          <th>القاضي</th>
          <th>القاعة</th>
          <th>الحالة</th>
          <th>الإجراءات</th>
        </tr></thead>
        <tbody>
        <?php foreach ($sessions as $s):
            $st  = $SESSION_STATUS[$s['status']]  ?? ['label'=>$s['status'], 'class'=>'secondary'];
            $tp  = $SESSION_TYPES[$s['session_type']] ?? ['label'=>$s['session_type'], 'class'=>'secondary'];
            $isToday = date('Y-m-d', strtotime($s['session_date'])) === date('Y-m-d');
        ?>
        <tr <?= $isToday ? 'style="background:rgba(201,168,76,.06)"' : '' ?>>
          <td class="text-muted" style="font-size:12px"><?= $s['session_number'] ?></td>
          <td>
            <a href="case-view.php?id=<?= $s['case_id'] ?>" class="text-navy fw-700 text-decoration-none">
              <?= htmlspecialchars($s['case_number']) ?>
            </a>
            <?php if ($isToday): ?><span class="badge bg-danger ms-1" style="font-size:10px">اليوم</span><?php endif; ?>
          </td>
          <td style="max-width:200px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis">
            <?= htmlspecialchars($s['case_title']) ?>
          </td>
          <td><span class="badge bg-<?= $tp['class'] ?>"><?= $tp['label'] ?></span></td>
          <td style="white-space:nowrap">
            <div style="font-weight:600"><?= date('d/m/Y', strtotime($s['session_date'])) ?></div>
            <div style="font-size:12px;color:var(--text-muted)"><?= date('H:i', strtotime($s['session_date'])) ?></div>
          </td>
          <td><?= htmlspecialchars($s['judge_name'] ?: '—') ?></td>
          <td><?= htmlspecialchars($s['room'] ?: '—') ?></td>
          <td>
            <select class="form-select form-select-sm status-select"
                    data-id="<?= $s['id'] ?>"
                    style="width:110px;font-size:12px"
                    onchange="updateStatus(this)">
              <?php foreach ($SESSION_STATUS as $k=>$v): ?>
              <option value="<?= $k ?>" <?= $s['status']===$k?'selected':'' ?>><?= $v['label'] ?></option>
              <?php endforeach; ?>
            </select>
          </td>
          <td>
            <div class="d-flex gap-1">
              <a href="case-view.php?id=<?= $s['case_id'] ?>" class="action-btn" title="عرض القضية"><i class="bi bi-eye"></i></a>
              <a href="session-minutes.php?session_id=<?= $s['id'] ?>" class="action-btn gold" title="تحرير المحضر"><i class="bi bi-journal-text"></i></a>
              <button class="action-btn danger" title="حذف" onclick="deleteSession(<?= $s['id'] ?>)"><i class="bi bi-trash"></i></button>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <?php endif; ?>
  </div>

</div></div>

<script>
function updateStatus(sel) {
  const id = sel.dataset.id;
  const status = sel.value;
  fetch('sessions.php', {
    method: 'POST',
    headers: {'Content-Type':'application/x-www-form-urlencoded'},
    body: `action=update_status&id=${id}&status=${status}`
  })
  .then(r => r.json())
  .then(d => {
    if (!d.ok) { alert('حدث خطأ أثناء التحديث'); sel.value = sel.dataset.prev; }
  });
}

document.querySelectorAll('.status-select').forEach(s => {
  s.dataset.prev = s.value;
  s.addEventListener('focus', function(){ this.dataset.prev = this.value; });
});

function deleteSession(id) {
  if (!confirm('هل تريد حذف هذه الجلسة نهائياً؟')) return;
  fetch('sessions.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(); ?>