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

$preselectedCase = (int)($_GET['case_id'] ?? 0);
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $caseId = (int)$_POST['case_id'];
    $sessionDate = $_POST['session_date'];
    $room = $_POST['room'] ?? '';
    $judgeName = $_POST['judge_name'] ?? '';
    $sessionType = $_POST['session_type'] ?? 'initial';

    if (!$caseId || !$sessionDate) {
        $error = 'يرجى اختيار القضية وتاريخ الجلسة';
    } else {
        // Get session count for this case
        $cnt = $pdo->prepare("SELECT COUNT(*) FROM sessions WHERE case_id=?");
        $cnt->execute([$caseId]);
        $sessNum = (int)$cnt->fetchColumn() + 1;

        $pdo->prepare("INSERT INTO sessions (case_id,session_number,session_date,room,judge_name,session_type,status,clerk_id) VALUES (?,?,?,?,?,?,'scheduled',?)")
            ->execute([$caseId,$sessNum,$sessionDate,$room,$judgeName,$sessionType,$user['id']]);
        $sessId = $pdo->lastInsertId();

        // Update case status
        $pdo->prepare("UPDATE cases SET status='open' WHERE id=?")->execute([$caseId]);

        // Notify assigned lawyers
        $lawyers = $pdo->prepare("SELECT lawyer_id FROM case_lawyers WHERE case_id=?");
        $lawyers->execute([$caseId]);
        $caseData = $pdo->prepare("SELECT case_number FROM cases WHERE id=?");
        $caseData->execute([$caseId]);
        $caseRow = $caseData->fetch();
        foreach ($lawyers->fetchAll() as $lId) {
            createNotification($lId['lawyer_id'],'session_scheduled','جلسة مجدولة',"تم تحديد جلسة جديدة للقضية {$caseRow['case_number']} بتاريخ " . date('d/m/Y H:i',strtotime($sessionDate)));
        }

        auditLog($user['id'],'create_session','sessions',$sessId,'إنشاء جلسة');
        header("Location: case-view.php?id=$caseId&msg=session_created");
        exit;
    }
}

$cases = $pdo->query("SELECT id,case_number,title FROM cases WHERE status IN ('open','adjourned') ORDER BY case_number")->fetchAll();
$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="d-flex align-items-center gap-3 mb-4">
    <a href="sessions.php" class="btn btn-outline-secondary btn-sm"><i class="bi bi-arrow-right"></i> رجوع</a>
    <h5 class="font-amiri fw-700 mb-0 text-navy">جدولة جلسة جديدة</h5>
  </div>
  <?php if ($error): ?><div class="alert alert-danger mb-3"><i class="bi bi-exclamation-triangle-fill me-2"></i><?= htmlspecialchars($error) ?></div><?php endif; ?>

  <div class="row justify-content-center">
    <div class="col-lg-7">
      <div class="panel">
        <div class="panel-body">
          <p class="form-section-title"><i class="bi bi-calendar-plus"></i> بيانات الجلسة</p>
          <form method="POST">
            <div class="mb-3">
              <label class="form-label">القضية <span class="text-danger">*</span></label>
              <select name="case_id" class="form-select" required>
                <option value="">اختر القضية</option>
                <?php foreach ($cases as $c): ?>
                <option value="<?= $c['id'] ?>" <?= $preselectedCase===$c['id']?'selected':'' ?>>[<?= htmlspecialchars($c['case_number']) ?>] <?= htmlspecialchars($c['title']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="row g-3 mb-3">
              <div class="col-md-6">
                <label class="form-label">تاريخ ووقت الجلسة <span class="text-danger">*</span></label>
                <input type="datetime-local" name="session_date" class="form-control" required>
              </div>
              <div class="col-md-6">
                <label class="form-label">نوع الجلسة</label>
                <select name="session_type" class="form-select">
                  <option value="initial">ابتدائية</option>
                  <option value="continuation">استمرار</option>
                  <option value="judgment">جلسة حكم</option>
                  <option value="appeal">استئناف</option>
                </select>
              </div>
              <div class="col-md-6">
                <label class="form-label">القاعة / الغرفة</label>
                <input type="text" name="room" class="form-control" placeholder="مثل: قاعة 5">
              </div>
              <div class="col-md-6">
                <label class="form-label">اسم القاضي</label>
                <input type="text" name="judge_name" class="form-control" placeholder="اسم القاضي المترئس">
              </div>
            </div>
            <div class="alert alert-gold mb-3" style="font-size:13px">
              <i class="bi bi-info-circle me-2"></i>سيتم إشعار المحامين المرتبطين بالقضية تلقائياً بموعد الجلسة.
            </div>
            <div class="d-grid gap-2">
              <button type="submit" class="btn btn-gold btn-lg"><i class="bi bi-calendar-check"></i> جدولة الجلسة</button>
              <a href="sessions.php" class="btn btn-outline-secondary">إلغاء</a>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</div></div>
<?php renderFoot(); ?>
