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

$sessionId = (int)($_GET['session_id'] ?? 0);
$sess = (function() use ($pdo,$sessionId) {
    $s = $pdo->prepare("SELECT s.*, c.case_number, c.title AS case_title, c.plaintiff, c.defendant FROM sessions s JOIN cases c ON s.case_id=c.id WHERE s.id=?");
    $s->execute([$sessionId]); return $s->fetch();
})();
if (!$sess) { header('Location: sessions.php'); exit; }

$existing = (function() use ($pdo,$sessionId) {
    $s = $pdo->prepare("SELECT * FROM session_minutes WHERE session_id=?");
    $s->execute([$sessionId]); return $s->fetch();
})();

$error = $success = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $decType = $_POST['decision_type'] ?? '';
    $content = $_POST['content']       ?? '';
    $newDate = $_POST['new_session_date'] ?? null;
    $judText = $_POST['judgment_text']    ?? null;
    $attendees = $_POST['attendees']    ?? '';

    if (!$decType || !$content) {
        $error = 'يرجى ملء محتوى المحضر ونوع القرار';
    } else {
        if ($existing) {
            $pdo->prepare("UPDATE session_minutes SET content=?,attendees=?,decision_type=?,new_session_date=?,judgment_text=?,updated_at=NOW() WHERE session_id=?")
                ->execute([$content,$attendees,$decType,$newDate?:null,$judText,$sessionId]);
        } else {
            $pdo->prepare("INSERT INTO session_minutes (session_id,content,attendees,decision_type,new_session_date,judgment_text,created_by) VALUES (?,?,?,?,?,?,?)")
                ->execute([$sessionId,$content,$attendees,$decType,$newDate?:null,$judText,$user['id']]);
        }

        // Update session status
        $pdo->prepare("UPDATE sessions SET status='completed' WHERE id=?")->execute([$sessionId]);

        // If adjourned, create new scheduled session
        if ($decType === 'adjournment' && $newDate) {
            $pdo->prepare("INSERT INTO sessions (case_id,session_number,session_date,room,judge_name,session_type,status,clerk_id) SELECT case_id,session_number+1,?,room,judge_name,'continuation','scheduled',clerk_id FROM sessions WHERE id=?")
                ->execute([$newDate, $sessionId]);
            // Notify lawyers
            $lawyerIds = $pdo->prepare("SELECT lawyer_id FROM case_lawyers WHERE case_id=?");
            $lawyerIds->execute([$sess['case_id']]);
            foreach ($lawyerIds->fetchAll() as $lid) {
                createNotification($lid['lawyer_id'],'session_adjourned','تأجيل جلسة',"تم تأجيل جلسة القضية {$sess['case_number']} إلى " . date('d/m/Y',strtotime($newDate)));
            }
        }

        // If judgment
        if ($decType === 'judgment' && $judText) {
            $pdo->prepare("UPDATE cases SET status='closed' WHERE id=?")->execute([$sess['case_id']]);
        }

        auditLog($user['id'],'write_minutes','session_minutes',$sessionId,'كتابة محضر جلسة');
        $success = 'تم حفظ المحضر بنجاح';
        $existing = (function() use ($pdo,$sessionId) { $s=$pdo->prepare("SELECT * FROM session_minutes WHERE session_id=?"); $s->execute([$sessionId]); return $s->fetch(); })();
    }
}

$notifCount = getUnreadNotifCount($user['id']);
renderHead('محضر الجلسة');
?>
<div class="sidebar" id="sidebar"><?php buildSidebar('minutes','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="case-view.php?id=<?= $sess['case_id'] ?>" 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>

  <!-- Session info bar -->
  <div class="panel mb-3">
    <div class="panel-body">
      <div class="row g-3">
        <div class="col-md-3"><p class="text-muted mb-1" style="font-size:12px">رقم القضية</p><strong><?= htmlspecialchars($sess['case_number']) ?></strong></div>
        <div class="col-md-4"><p class="text-muted mb-1" style="font-size:12px">الأطراف</p><strong><?= htmlspecialchars($sess['plaintiff']) ?> ضد <?= htmlspecialchars($sess['defendant']) ?></strong></div>
        <div class="col-md-2"><p class="text-muted mb-1" style="font-size:12px">تاريخ الجلسة</p><strong><?= date('d/m/Y H:i',strtotime($sess['session_date'])) ?></strong></div>
        <div class="col-md-2"><p class="text-muted mb-1" style="font-size:12px">القاضي</p><strong><?= htmlspecialchars($sess['judge_name']??'غير محدد') ?></strong></div>
      </div>
    </div>
  </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; ?>
  <?php if ($success): ?><div class="alert alert-success mb-3"><i class="bi bi-check-circle-fill me-2"></i><?= htmlspecialchars($success) ?></div><?php endif; ?>

  <form method="POST" id="minutesForm">
    <div class="row g-3">
      <div class="col-lg-8">
        <div class="panel mb-3">
          <div class="panel-body">
            <p class="form-section-title"><i class="bi bi-journal-text"></i> محتوى المحضر</p>
            <div class="mb-3">
              <label class="form-label">الحضور والغياب</label>
              <textarea name="attendees" class="form-control" rows="3" placeholder="أدخل أسماء الحاضرين من أطراف القضية ومحاميهم..."><?= htmlspecialchars($existing['attendees']??'') ?></textarea>
            </div>
            <div class="mb-3">
              <label class="form-label">محتوى المحضر <span class="text-danger">*</span></label>
              <textarea name="content" class="form-control" rows="10" placeholder="أدخل تفاصيل ما جرى في الجلسة، المرافعات، الطلبات، الوقائع..." required><?= htmlspecialchars($existing['content']??'') ?></textarea>
            </div>
          </div>
        </div>
      </div>

      <div class="col-lg-4">
        <div class="panel mb-3">
          <div class="panel-body">
            <p class="form-section-title"><i class="bi bi-gavel"></i> قرار الجلسة</p>
            <div class="mb-3">
              <label class="form-label">نوع القرار <span class="text-danger">*</span></label>
              <select name="decision_type" class="form-select" id="decisionType" required>
                <option value="">اختر نوع القرار</option>
                <option value="adjournment"  <?= ($existing['decision_type']??'')==='adjournment'?'selected':'' ?>>تأجيل الجلسة</option>
                <option value="judgment"     <?= ($existing['decision_type']??'')==='judgment'?'selected':'' ?>>إصدار حكم</option>
                <option value="interlocutory"<?= ($existing['decision_type']??'')==='interlocutory'?'selected':'' ?>>قرار تمهيدي</option>
                <option value="dismissal"    <?= ($existing['decision_type']??'')==='dismissal'?'selected':'' ?>>رفض الدعوى</option>
              </select>
            </div>

            <!-- Adjournment date -->
            <div id="adjournSection" style="display:none" class="mb-3">
              <label class="form-label">التاريخ الجديد للجلسة <span class="text-danger">*</span></label>
              <input type="datetime-local" name="new_session_date" class="form-control" value="<?= $existing['new_session_date']??'' ?>">
            </div>

            <!-- Judgment text -->
            <div id="judgmentSection" style="display:none" class="mb-3">
              <label class="form-label">منطوق الحكم <span class="text-danger">*</span></label>
              <textarea name="judgment_text" class="form-control" rows="5" placeholder="أدخل منطوق الحكم كاملاً..."><?= htmlspecialchars($existing['judgment_text']??'') ?></textarea>
            </div>

            <div class="d-grid gap-2 mt-4">
              <button type="submit" class="btn btn-gold btn-lg"><i class="bi bi-save"></i> حفظ المحضر</button>
              <?php if ($existing && $existing['finalized'] == 0): ?>
              <button type="button" class="btn btn-primary" onclick="finalizeMinutes()"><i class="bi bi-lock"></i> اعتماد المحضر نهائياً</button>
              <?php endif; ?>
              <button type="button" class="btn btn-outline-secondary" onclick="printSection('minutesForm')"><i class="bi bi-printer"></i> طباعة</button>
            </div>
          </div>
        </div>

        <?php if ($existing && $existing['finalized']): ?>
        <div class="alert alert-navy mt-2" style="font-size:13px">
          <i class="bi bi-lock-fill me-2 text-gold"></i> تم اعتماد هذا المحضر نهائياً ولا يمكن تعديله.
        </div>
        <?php endif; ?>
      </div>
    </div>
  </form>
</div></div>

<script>
const decSel = document.getElementById('decisionType');
const adjSec = document.getElementById('adjournSection');
const judSec = document.getElementById('judgmentSection');

function updateDecisionSections() {
  const v = decSel.value;
  adjSec.style.display = v === 'adjournment' ? 'block' : 'none';
  judSec.style.display = (v === 'judgment' || v === 'dismissal') ? 'block' : 'none';
}
decSel.addEventListener('change', updateDecisionSections);
updateDecisionSections();

function finalizeMinutes() {
  if (confirm('هل أنت متأكد من اعتماد المحضر نهائياً؟ لن يمكن تعديله بعد ذلك.')) {
    fetch(window.APP_BASE + '/api/finalize-minutes.php?session_id=<?= $sessionId ?>')
      .then(r => r.json())
      .then(d => { if(d.success) location.reload(); });
  }
}
</script>
<?php renderFoot(); ?>
