<?php
// ============================================================
// clerk/cases/new.php - فتح ملف قضية جديدة
// ============================================================
require_once __DIR__ . '/../../config/db.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/functions.php';

define('BASE', '../../');
requireRole('clerk', '../../index.php');

$user = currentUser();
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title       = trim($_POST['title'] ?? '');
    $caseType    = $_POST['case_type'] ?? '';
    $plaintiff   = trim($_POST['plaintiff'] ?? '');
    $defendant   = trim($_POST['defendant'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $courtName   = trim($_POST['court_name'] ?? '');
    $courtType   = $_POST['court_type'] ?? 'primary';
    $filingDate  = $_POST['filing_date'] ?? date('Y-m-d');
    $plaintiffLawyerId = (int)($_POST['plaintiff_lawyer_id'] ?? 0);
    $defendantLawyerId = (int)($_POST['defendant_lawyer_id'] ?? 0);

    if (!$title)     $errors[] = 'عنوان القضية مطلوب';
    if (!$caseType)  $errors[] = 'نوع القضية مطلوب';
    if (!$plaintiff) $errors[] = 'اسم المدعي مطلوب';
    if (!$defendant) $errors[] = 'اسم المدعى عليه مطلوب';

    if (!$errors) {
        $caseNumber = generateCaseNumber($pdo, $caseType);
        $pdo->prepare("
            INSERT INTO cases (case_number, title, description, case_type, plaintiff, defendant,
                               plaintiff_lawyer_id, defendant_lawyer_id, assigned_clerk_id,
                               court_name, court_type, filing_date, stage, status)
            VALUES (?,?,?,?,?,?,?,?,?,?,?,?,'first_instance','active')
        ")->execute([
            $caseNumber, $title, $description, $caseType, $plaintiff, $defendant,
            $plaintiffLawyerId ?: null, $defendantLawyerId ?: null, $user['id'],
            $courtName, $courtType, $filingDate
        ]);

        $caseId = $pdo->lastInsertId();

        // Notify assigned lawyers
        foreach (array_filter([$plaintiffLawyerId, $defendantLawyerId]) as $lid) {
            sendNotification($pdo, $lid, 'قضية جديدة', "تم تسجيلك في قضية جديدة: $caseNumber — $title", 'info', $caseId, "../../lawyer/cases.php");
        }

        setFlash('success', "تم فتح ملف القضية بنجاح — رقم الملف: $caseNumber");
        header("Location: view.php?id=$caseId");
        exit;
    }
}

// Get approved lawyers
$lawyers = $pdo->query("
    SELECT u.id, u.full_name, lp.bar_number, lp.specialization
    FROM users u JOIN lawyer_profiles lp ON lp.user_id = u.id
    WHERE lp.verification_status = 'approved'
    ORDER BY u.full_name
")->fetchAll();

$flash = getFlash();
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>فتح قضية جديدة</title>
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700;800&family=Amiri:wght@400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="../../assets/css/style.css">
<script>const BASE_URL = '../../';</script>
</head>
<body>
<?php require_once __DIR__ . '/../../includes/sidebar.php'; ?>

<div class="main-content">
  <div class="page-header">
    <div>
      <div class="breadcrumb">
        <a href="../index.php">الرئيسية</a> <span>›</span>
        <a href="index.php">القضايا</a> <span>›</span>
        <span>قضية جديدة</span>
      </div>
      <div class="page-title">
        <div class="title-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg></div>
        فتح ملف قضية جديدة
      </div>
    </div>
  </div>

  <div class="page-body fade-in">
    <?php if ($errors): ?>
    <div class="alert alert-danger">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="18" height="18"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
      <div><?php foreach ($errors as $e): ?><div>• <?= clean($e) ?></div><?php endforeach; ?></div>
    </div>
    <?php endif; ?>

    <form method="POST" style="max-width:800px;">
      <input type="hidden" name="csrf_token" value="<?= getCsrfToken() ?>">

      <!-- Section 1: Basic Info -->
      <div class="card" style="margin-bottom:20px;">
        <div class="card-header">
          <div class="card-title">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
            معلومات القضية الأساسية
          </div>
        </div>
        <div class="card-body">
          <div class="form-group">
            <label class="form-label">عنوان القضية <span class="required">*</span></label>
            <input type="text" name="title" class="form-control"
                   value="<?= clean($_POST['title'] ?? '') ?>"
                   placeholder="مثال: قضية استحقاق عقاري / نزاع تجاري..." required>
          </div>

          <div class="form-row cols-2">
            <div class="form-group">
              <label class="form-label">نوع القضية <span class="required">*</span></label>
              <select name="case_type" class="form-control" required>
                <option value="">-- اختر نوع القضية --</option>
                <option value="civil" <?= ($_POST['case_type']??'')==='civil'?'selected':'' ?>>مدنية</option>
                <option value="criminal" <?= ($_POST['case_type']??'')==='criminal'?'selected':'' ?>>جزائية</option>
                <option value="commercial" <?= ($_POST['case_type']??'')==='commercial'?'selected':'' ?>>تجارية</option>
                <option value="administrative" <?= ($_POST['case_type']??'')==='administrative'?'selected':'' ?>>إدارية</option>
                <option value="family" <?= ($_POST['case_type']??'')==='family'?'selected':'' ?>>شؤون أسرة</option>
              </select>
            </div>
            <div class="form-group">
              <label class="form-label">تاريخ إيداع الملف <span class="required">*</span></label>
              <input type="date" name="filing_date" class="form-control"
                     value="<?= clean($_POST['filing_date'] ?? date('Y-m-d')) ?>">
            </div>
          </div>

          <div class="form-group">
            <label class="form-label">وصف القضية</label>
            <textarea name="description" class="form-control" rows="3"
                      placeholder="تفاصيل وملابسات القضية..."><?= clean($_POST['description'] ?? '') ?></textarea>
          </div>
        </div>
      </div>

      <!-- Section 2: Parties -->
      <div class="card" style="margin-bottom:20px;">
        <div class="card-header">
          <div class="card-title">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75"/></svg>
            أطراف القضية
          </div>
        </div>
        <div class="card-body">
          <div class="form-row cols-2">
            <div class="form-group">
              <label class="form-label">المدعي (الطرف الأول) <span class="required">*</span></label>
              <input type="text" name="plaintiff" class="form-control"
                     value="<?= clean($_POST['plaintiff'] ?? '') ?>"
                     placeholder="الاسم الكامل أو اسم الشركة" required>
            </div>
            <div class="form-group">
              <label class="form-label">المدعى عليه (الطرف الثاني) <span class="required">*</span></label>
              <input type="text" name="defendant" class="form-control"
                     value="<?= clean($_POST['defendant'] ?? '') ?>"
                     placeholder="الاسم الكامل أو اسم الشركة" required>
            </div>
          </div>

          <div class="form-row cols-2">
            <div class="form-group">
              <label class="form-label">محامي المدعي</label>
              <select name="plaintiff_lawyer_id" class="form-control">
                <option value="">-- بدون محامٍ --</option>
                <?php foreach ($lawyers as $l): ?>
                <option value="<?= $l['id'] ?>" <?= ($_POST['plaintiff_lawyer_id']??'')==$l['id']?'selected':'' ?>>
                  <?= clean($l['full_name']) ?> <?= $l['bar_number'] ? "({$l['bar_number']})" : '' ?>
                </option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="form-group">
              <label class="form-label">محامي المدعى عليه</label>
              <select name="defendant_lawyer_id" class="form-control">
                <option value="">-- بدون محامٍ --</option>
                <?php foreach ($lawyers as $l): ?>
                <option value="<?= $l['id'] ?>" <?= ($_POST['defendant_lawyer_id']??'')==$l['id']?'selected':'' ?>>
                  <?= clean($l['full_name']) ?> <?= $l['bar_number'] ? "({$l['bar_number']})" : '' ?>
                </option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>
        </div>
      </div>

      <!-- Section 3: Court Info -->
      <div class="card" style="margin-bottom:24px;">
        <div class="card-header">
          <div class="card-title">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>
            معلومات المحكمة
          </div>
        </div>
        <div class="card-body">
          <div class="form-row cols-2">
            <div class="form-group">
              <label class="form-label">اسم المحكمة</label>
              <input type="text" name="court_name" class="form-control"
                     value="<?= clean($_POST['court_name'] ?? '') ?>"
                     placeholder="مثال: المحكمة الابتدائية بتلمسان">
            </div>
            <div class="form-group">
              <label class="form-label">درجة المحكمة</label>
              <select name="court_type" class="form-control">
                <option value="primary" <?= ($_POST['court_type']??'primary')==='primary'?'selected':'' ?>>ابتدائية</option>
                <option value="appeal" <?= ($_POST['court_type']??'')==='appeal'?'selected':'' ?>>استئناف</option>
                <option value="supreme" <?= ($_POST['court_type']??'')==='supreme'?'selected':'' ?>>عليا / نقض</option>
              </select>
            </div>
          </div>
        </div>
      </div>

      <!-- Actions -->
      <div style="display:flex;gap:12px;">
        <button type="submit" class="btn btn-gold">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><path d="M19 21H5a2 2 0 01-2-2V5a2 2 0 012-2h11l5 5v11a2 2 0 01-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>
          حفظ وفتح الملف
        </button>
        <a href="index.php" class="btn btn-outline">إلغاء</a>
      </div>
    </form>
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/feather-icons/4.29.1/feather.min.js"></script>
<script src="../../assets/js/app.js"></script>
</body>
</html>
