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

$error = $success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $required = ['title','case_type','plaintiff','defendant','filing_date'];
    $missing  = array_filter($required, fn($f) => empty($_POST[$f]));
    if ($missing) {
        $error = 'يرجى ملء جميع الحقول الإلزامية';
    } else {
        $caseNum = generateCaseNumber();
        $pdo->prepare("INSERT INTO cases (case_number,title,case_type,plaintiff,defendant,description,stage,status,court_id,clerk_id,priority,filing_date) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)")
            ->execute([
                $caseNum,
                $_POST['title'],
                $_POST['case_type'],
                $_POST['plaintiff'],
                $_POST['defendant'],
                $_POST['description'] ?? '',
                $_POST['stage'] ?? 'ibtidai',
                'open',
                $_POST['court_id'] ?: null,
                $user['id'],
                $_POST['priority'] ?? 'normal',
                $_POST['filing_date'],
            ]);
        $caseId = $pdo->lastInsertId();
        auditLog($user['id'], 'create_case', 'cases', $caseId, 'إنشاء قضية ' . $caseNum);
        header("Location: case-view.php?id=$caseId&msg=created");
        exit;
    }
}

$courts = $pdo->query("SELECT * FROM courts ORDER BY name")->fetchAll();
$notifCount = getUnreadNotifCount($user['id']);
renderHead('قضية جديدة');
?>
<div class="sidebar" id="sidebar"><?php buildSidebar('cases','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="cases.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; ?>

  <form method="POST">
    <div class="row g-3">
      <!-- Right column: main info -->
      <div class="col-lg-8">
        <div class="panel mb-3">
          <div class="panel-body">
            <p class="form-section-title"><i class="bi bi-folder2-open"></i> بيانات القضية</p>
            <div class="row g-3">
              <div class="col-12">
                <label class="form-label">عنوان القضية <span class="text-danger">*</span></label>
                <input type="text" name="title" class="form-control" value="<?= htmlspecialchars($_POST['title']??'') ?>" placeholder="أدخل عنوان وصفي للقضية" required>
              </div>
              <div class="col-md-6">
                <label class="form-label">نوع القضية <span class="text-danger">*</span></label>
                <select name="case_type" class="form-select" required>
                  <option value="">اختر النوع</option>
                  <?php foreach (CASE_TYPES as $k=>$v): ?>
                  <option value="<?= $k ?>" <?= ($_POST['case_type']??'')===$k?'selected':'' ?>><?= $v ?></option>
                  <?php endforeach; ?>
                </select>
              </div>
              <div class="col-md-6">
                <label class="form-label">تاريخ الإيداع <span class="text-danger">*</span></label>
                <input type="date" name="filing_date" class="form-control" value="<?= $_POST['filing_date'] ?? date('Y-m-d') ?>" required>
              </div>
              <div class="col-md-6">
                <label class="form-label">المدعي / المشتكي <span class="text-danger">*</span></label>
                <input type="text" name="plaintiff" class="form-control" value="<?= htmlspecialchars($_POST['plaintiff']??'') ?>" required>
              </div>
              <div class="col-md-6">
                <label class="form-label">المدعى عليه <span class="text-danger">*</span></label>
                <input type="text" name="defendant" class="form-control" value="<?= htmlspecialchars($_POST['defendant']??'') ?>" required>
              </div>
              <div class="col-12">
                <label class="form-label">وصف القضية / الموضوع</label>
                <textarea name="description" class="form-control" rows="4" placeholder="ملخص موضوع القضية..."><?= htmlspecialchars($_POST['description']??'') ?></textarea>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Left column: settings -->
      <div class="col-lg-4">
        <div class="panel mb-3">
          <div class="panel-body">
            <p class="form-section-title"><i class="bi bi-sliders"></i> الإعدادات</p>
            <div class="mb-3">
              <label class="form-label">مرحلة القضية</label>
              <select name="stage" class="form-select">
                <?php foreach (STAGES as $k=>$v): ?>
                <option value="<?= $k ?>" <?= ($_POST['stage']??'ibtidai')===$k?'selected':'' ?>><?= $v ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="mb-3">
              <label class="form-label">الأولوية</label>
              <select name="priority" class="form-select">
                <option value="low"    <?= ($_POST['priority']??'')==='low'?'selected':'' ?>>منخفضة</option>
                <option value="normal" <?= ($_POST['priority']??'normal')==='normal'?'selected':'' ?>>عادية</option>
                <option value="high"   <?= ($_POST['priority']??'')==='high'?'selected':'' ?>>مرتفعة</option>
                <option value="urgent" <?= ($_POST['priority']??'')==='urgent'?'selected':'' ?>>عاجلة</option>
              </select>
            </div>
            <div class="mb-3">
              <label class="form-label">المحكمة</label>
              <select name="court_id" class="form-select">
                <option value="">لم تُحدد</option>
                <?php foreach ($courts as $court): ?>
                <option value="<?= $court['id'] ?>" <?= ($_POST['court_id']??'')==$court['id']?'selected':'' ?>><?= htmlspecialchars($court['name']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>
        </div>

        <div class="alert alert-gold" style="font-size:13px">
          <i class="bi bi-info-circle me-2"></i>
          سيُولَّد رقم القضية تلقائياً عند الحفظ بالتنسيق: <strong>QD-YYYY-XXXX</strong>
        </div>

        <div class="d-grid gap-2 mt-3">
          <button type="submit" class="btn btn-gold btn-lg"><i class="bi bi-save"></i> حفظ القضية</button>
          <a href="cases.php" class="btn btn-outline-secondary">إلغاء</a>
        </div>
      </div>
    </div>
  </form>
</div></div>
<?php renderFoot(); ?>
