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

// ── ثوابت الأحكام ─────────────────────────────────────────────
$JUDGMENT_TYPES = [
    'ibtidai' => ['label' => 'ابتدائي',  'class' => 'primary'],
    'istinaf' => ['label' => 'استئناف',  'class' => 'warning'],
    'naqd'    => ['label' => 'نقض',      'class' => 'danger'],
];
$JUDGMENT_STATUS = [
    'issued'   => ['label' => 'صادر',        'class' => 'success'],
    'appealed' => ['label' => 'مستأنف',      'class' => 'warning'],
    'final'    => ['label' => 'نهائي',       'class' => 'primary'],
    'cancelled'=> ['label' => 'ملغى',        'class' => 'secondary'],
];

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

    if ($_POST['action'] === 'add') {
        $caseId    = (int)$_POST['case_id'];
        $sessionId = (int)($_POST['session_id'] ?: 0) ?: null;
        $jNum      = trim($_POST['judgment_number'] ?? '');
        $jType     = $_POST['judgment_type'] ?? 'ibtidai';
        $content   = trim($_POST['content'] ?? '');
        $operative = trim($_POST['operative_part'] ?? '');
        $judge     = trim($_POST['judge_name'] ?? '');
        $jDate     = $_POST['judgment_date'] ?? date('Y-m-d');
        $isDefault = !empty($_POST['is_default']) ? 1 : 0;

        if ($caseId && $content && $operative) {
            $pdo->prepare("INSERT INTO judgments (case_id,session_id,judgment_number,judgment_type,content,operative_part,judge_name,judgment_date,is_default,status,created_by)
                VALUES (?,?,?,?,?,?,?,?,?,'issued',?)")
                ->execute([$caseId,$sessionId,$jNum?:null,$jType,$content,$operative,$judge?:null,$jDate,$isDefault,$user['id']]);
            auditLog($user['id'],'add_judgment','judgments',$pdo->lastInsertId(),'إضافة حكم جديد' . ($isDefault ? ' (غيابي)' : ' (حضوري)'));
            echo json_encode(['ok'=>true]);
        } else {
            echo json_encode(['ok'=>false,'msg'=>'يرجى ملء جميع الحقول المطلوبة']);
        }
        exit;
    }

    if ($_POST['action'] === 'update_status' && $id) {
        $newStatus = $_POST['status'] ?? '';
        if (array_key_exists($newStatus, $JUDGMENT_STATUS)) {
            $pdo->prepare("UPDATE judgments SET status=? WHERE id=?")->execute([$newStatus,$id]);
            auditLog($user['id'],'update_judgment_status','judgments',$id,"تغيير حالة الحكم إلى $newStatus");
            echo json_encode(['ok'=>true]);
        } else { echo json_encode(['ok'=>false]); }
        exit;
    }

    if ($_POST['action'] === 'delete' && $id) {
        $pdo->prepare("DELETE FROM judgments WHERE id=?")->execute([$id]);
        auditLog($user['id'],'delete_judgment','judgments',$id,'حذف حكم');
        echo json_encode(['ok'=>true]);
        exit;
    }
    echo json_encode(['ok'=>false]); exit;
}

// ── الفلاتر ───────────────────────────────────────────────────
$search   = trim($_GET['q']      ?? '');
$jtype    = $_GET['jtype']       ?? '';
$status   = $_GET['status']      ?? '';
$date_from = $_GET['date_from']  ?? '';
$date_to   = $_GET['date_to']    ?? '';

$where = []; $params = [];
if ($search)    { $where[] = "(c.case_number LIKE ? OR c.title LIKE ? OR j.judgment_number LIKE ? OR j.judge_name LIKE ?)"; $p="%$search%"; $params=array_merge($params,[$p,$p,$p,$p]); }
if ($jtype)     { $where[] = "j.judgment_type = ?"; $params[] = $jtype; }
if ($status)    { $where[] = "j.status = ?"; $params[] = $status; }
if ($date_from) { $where[] = "j.judgment_date >= ?"; $params[] = $date_from; }
if ($date_to)   { $where[] = "j.judgment_date <= ?"; $params[] = $date_to; }
$whereSQL = $where ? 'WHERE '.implode(' AND ',$where) : '';

$stmt = $pdo->prepare("
    SELECT j.*, c.case_number, c.title AS case_title, c.case_type,
           u.full_name AS creator_name
    FROM judgments j
    JOIN cases c ON j.case_id = c.id
    JOIN users u ON j.created_by = u.id
    $whereSQL
    ORDER BY j.judgment_date DESC, j.created_at DESC
");
$stmt->execute($params);
$judgments = $stmt->fetchAll();

// إحصائيات
$stats = $pdo->query("
    SELECT COUNT(*) AS total,
           SUM(status='issued')   AS issued,
           SUM(status='appealed') AS appealed,
           SUM(status='final')    AS final_count
    FROM judgments
")->fetch();

// قائمة القضايا للنموذج
$cases = $pdo->query("SELECT id, case_number, title FROM cases WHERE status NOT IN ('archived') ORDER BY case_number")->fetchAll();

$notifCount = getUnreadNotifCount($user['id']);
renderHead('الأحكام');
?>
<div class="sidebar" id="sidebar"><?php buildSidebar('judgments','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:#198754"><?= $stats['issued'] ?></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:#ffc107"><?= $stats['appealed'] ?></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['final_count'] ?></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">
    <form method="GET" class="d-flex gap-2 flex-wrap align-items-center">
      <input type="text" name="q" class="form-control" placeholder="بحث برقم الحكم / القضية / القاضي..." value="<?= htmlspecialchars($search) ?>" style="width:260px">
      <select name="jtype" class="form-select" style="width:130px">
        <option value="">كل الأنواع</option>
        <?php foreach ($JUDGMENT_TYPES as $k=>$v): ?>
        <option value="<?= $k ?>" <?= $jtype===$k?'selected':'' ?>><?= $v['label'] ?></option>
        <?php endforeach; ?>
      </select>
      <select name="status" class="form-select" style="width:130px">
        <option value="">كل الحالات</option>
        <?php foreach ($JUDGMENT_STATUS as $k=>$v): ?>
        <option value="<?= $k ?>" <?= $status===$k?'selected':'' ?>><?= $v['label'] ?></option>
        <?php endforeach; ?>
      </select>
      <input type="date" name="date_from" class="form-control" value="<?= htmlspecialchars($date_from) ?>" style="width:145px">
      <input type="date" name="date_to"   class="form-control" value="<?= htmlspecialchars($date_to) ?>"   style="width:145px">
      <button class="btn btn-primary"><i class="bi bi-search"></i></button>
      <?php if ($search||$jtype||$status||$date_from||$date_to): ?>
      <a href="judgments.php" class="btn btn-outline-secondary"><i class="bi bi-x"></i></a>
      <?php endif; ?>
    </form>
    <div class="d-flex gap-2">
      <button class="btn btn-outline-gold btn-sm" onclick="exportTableExcel('judgmentsTable','قائمة_الأحكام')">
        <i class="bi bi-file-excel"></i> Excel
      </button>
      <button class="btn btn-gold" onclick="showAddModal()">
        <i class="bi bi-plus-circle"></i> إضافة حكم
      </button>
    </div>
  </div>

  <!-- الجدول -->
  <div class="panel">
    <?php if (empty($judgments)): ?>
      <div class="empty-state py-5 text-center">
        <i class="bi bi-file-earmark-x" style="font-size:48px;color:var(--text-muted)"></i>
        <h5 class="mt-3">لا توجد أحكام</h5>
        <p class="text-muted">لم يتم تسجيل أي أحكام بعد</p>
        <button class="btn btn-gold mt-2" onclick="showAddModal()"><i class="bi bi-plus-circle"></i> إضافة حكم</button>
      </div>
    <?php else: ?>
    <div class="table-responsive">
      <table class="table dt-table" id="judgmentsTable">
        <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 ($judgments as $j):
            $jt = $JUDGMENT_TYPES[$j['judgment_type']]  ?? ['label'=>$j['judgment_type'],'class'=>'secondary'];
            $js = $JUDGMENT_STATUS[$j['status']]        ?? ['label'=>$j['status'],'class'=>'secondary'];
        ?>
        <tr>
          <td class="fw-700 text-navy"><?= htmlspecialchars($j['judgment_number'] ?: '—') ?></td>
          <td>
            <a href="case-view.php?id=<?= $j['case_id'] ?>" class="text-navy fw-700 text-decoration-none">
              <?= htmlspecialchars($j['case_number']) ?>
            </a>
          </td>
          <td style="max-width:180px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis">
            <?= htmlspecialchars($j['case_title']) ?>
          </td>
          <td><span class="badge bg-<?= $jt['class'] ?>"><?= $jt['label'] ?></span></td>
          <td style="white-space:nowrap"><?= date('d/m/Y', strtotime($j['judgment_date'])) ?></td>
          <td><?= htmlspecialchars($j['judge_name'] ?: '—') ?></td>
          <td style="max-width:200px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;font-size:13px">
            <?= htmlspecialchars(mb_substr($j['operative_part'],0,60,'UTF-8')) ?>...
          </td>
          <td>
            <select class="form-select form-select-sm status-sel" data-id="<?= $j['id'] ?>"
                    style="width:110px;font-size:12px" onchange="updateJudgmentStatus(this)">
              <?php foreach ($JUDGMENT_STATUS as $k=>$v): ?>
              <option value="<?= $k ?>" <?= $j['status']===$k?'selected':'' ?>><?= $v['label'] ?></option>
              <?php endforeach; ?>
            </select>
          </td>
          <td>
            <div class="d-flex gap-1">
              <button class="action-btn" title="عرض التفاصيل"
                      onclick='showDetail(<?= json_encode(['num'=>$j['judgment_number'],'type'=>$jt['label'],'date'=>date("d/m/Y",strtotime($j["judgment_date"])),'judge'=>$j["judge_name"],'content'=>$j["content"],'operative'=>$j["operative_part"],'case'=>$j["case_number"]]) ?>)'>
                <i class="bi bi-eye"></i>
              </button>
              <a href="case-view.php?id=<?= $j['case_id'] ?>" class="action-btn gold" title="عرض القضية"><i class="bi bi-folder2-open"></i></a>
              <button class="action-btn danger" title="حذف" onclick="deleteJudgment(<?= $j['id'] ?>)"><i class="bi bi-trash"></i></button>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <?php endif; ?>
  </div>

</div></div>

<!-- مودال إضافة حكم -->
<div class="modal fade" id="addModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title font-amiri"><i class="bi bi-file-earmark-text me-2"></i>إضافة حكم جديد</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div id="addMsg"></div>
        <div class="row g-3">
          <div class="col-md-6">
            <label class="form-label">القضية <span class="text-danger">*</span></label>
            <select id="ac_case_id" class="form-select" onchange="loadSessions(this.value)">
              <option value="">اختر القضية...</option>
              <?php foreach ($cases as $c): ?>
              <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['case_number'].' - '.mb_substr($c['title'],0,40,'UTF-8')) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-md-6">
            <label class="form-label">الجلسة المرتبطة</label>
            <select id="ac_session_id" class="form-select">
              <option value="">— اختياري —</option>
            </select>
          </div>
          <div class="col-md-6">
            <label class="form-label">رقم الحكم</label>
            <input type="text" id="ac_judgment_number" class="form-control" placeholder="مثال: ح-2025/001">
          </div>
          <div class="col-md-6">
            <label class="form-label">نوع الحكم</label>
            <select id="ac_judgment_type" class="form-select">
              <?php foreach ($JUDGMENT_TYPES as $k=>$v): ?>
              <option value="<?= $k ?>"><?= $v['label'] ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-md-6">
            <label class="form-label">تاريخ الحكم <span class="text-danger">*</span></label>
            <input type="date" id="ac_judgment_date" class="form-control" value="<?= date('Y-m-d') ?>">
          </div>
          <div class="col-md-6">
            <label class="form-label">اسم القاضي</label>
            <input type="text" id="ac_judge_name" class="form-control" placeholder="اسم القاضي المصدر للحكم">
          </div>
          <div class="col-md-6">
            <label class="form-label d-block">طبيعة الحكم <span class="text-danger">*</span></label>
            <div class="form-check form-check-inline">
              <input type="radio" id="ac_jdef_no" name="ac_is_default" value="0" class="form-check-input" checked>
              <label class="form-check-label" for="ac_jdef_no">حضوري</label>
            </div>
            <div class="form-check form-check-inline">
              <input type="radio" id="ac_jdef_yes" name="ac_is_default" value="1" class="form-check-input">
              <label class="form-check-label" for="ac_jdef_yes">غيابي</label>
            </div>
            <small class="text-muted d-block" style="font-size:11px">الحكم الغيابي وحده يقبل المعارضة.</small>
          </div>
          <div class="col-12">
            <label class="form-label">منطوق الحكم <span class="text-danger">*</span></label>
            <textarea id="ac_operative_part" class="form-control" rows="3" placeholder="أدخل منطوق الحكم..."></textarea>
          </div>
          <div class="col-12">
            <label class="form-label">محتوى الحكم كاملاً <span class="text-danger">*</span></label>
            <textarea id="ac_content" class="form-control" rows="5" placeholder="أدخل نص الحكم كاملاً..."></textarea>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
        <button class="btn btn-gold" onclick="submitJudgment()"><i class="bi bi-save"></i> حفظ الحكم</button>
      </div>
    </div>
  </div>
</div>

<!-- مودال التفاصيل -->
<div class="modal fade" id="detailModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title font-amiri"><i class="bi bi-file-earmark-text me-2"></i>تفاصيل الحكم</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body" id="detailBody"></div>
    </div>
  </div>
</div>

<script>
let addModal, detailModal;
document.addEventListener('DOMContentLoaded', () => {
  addModal    = new bootstrap.Modal(document.getElementById('addModal'));
  detailModal = new bootstrap.Modal(document.getElementById('detailModal'));
});

function showAddModal() { addModal.show(); }

function loadSessions(caseId) {
  const sel = document.getElementById('ac_session_id');
  sel.innerHTML = '<option value="">— اختياري —</option>';
  if (!caseId) return;
  fetch('sessions.php?case_filter='+caseId)
    .then(() => {
      fetch('judgments.php?ajax_sessions='+caseId)
        .then(r => r.json())
        .then(data => {
          data.forEach(s => {
            const o = document.createElement('option');
            o.value = s.id;
            o.textContent = `جلسة ${s.session_number} — ${s.session_date}`;
            sel.appendChild(o);
          });
        }).catch(() => {});
    });
  // Fallback: direct query via inline endpoint
  fetch(`judgments.php?ajax_sessions=${caseId}`)
    .then(r => r.json())
    .then(data => {
      sel.innerHTML = '<option value="">— اختياري —</option>';
      data.forEach(s => {
        const o = document.createElement('option');
        o.value = s.id;
        o.textContent = `جلسة ${s.session_number} — ${s.session_date.substring(0,10)}`;
        sel.appendChild(o);
      });
    }).catch(() => {});
}

function submitJudgment() {
  const msg = document.getElementById('addMsg');
  const caseId = document.getElementById('ac_case_id').value;
  const content = document.getElementById('ac_content').value.trim();
  const operative = document.getElementById('ac_operative_part').value.trim();
  if (!caseId || !content || !operative) {
    msg.innerHTML = '<div class="alert alert-danger py-2">يرجى ملء جميع الحقول المطلوبة</div>';
    return;
  }
  const isDef = document.querySelector('input[name="ac_is_default"]:checked');
  const body = new URLSearchParams({
    action: 'add',
    case_id: caseId,
    session_id: document.getElementById('ac_session_id').value,
    judgment_number: document.getElementById('ac_judgment_number').value,
    judgment_type: document.getElementById('ac_judgment_type').value,
    judgment_date: document.getElementById('ac_judgment_date').value,
    judge_name: document.getElementById('ac_judge_name').value,
    is_default: isDef ? isDef.value : '0',
    operative_part: operative,
    content: content
  });
  fetch('judgments.php', { method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body })
    .then(r => r.json())
    .then(d => {
      if (d.ok) { location.reload(); }
      else { msg.innerHTML = `<div class="alert alert-danger py-2">${d.msg||'حدث خطأ'}</div>`; }
    });
}

function updateJudgmentStatus(sel) {
  const prev = sel.dataset.prev;
  fetch('judgments.php', {
    method:'POST',
    headers:{'Content-Type':'application/x-www-form-urlencoded'},
    body: `action=update_status&id=${sel.dataset.id}&status=${sel.value}`
  }).then(r=>r.json()).then(d => { if (!d.ok) sel.value = prev; });
}
document.querySelectorAll('.status-sel').forEach(s => {
  s.dataset.prev = s.value;
  s.addEventListener('focus', function(){ this.dataset.prev = this.value; });
});

function deleteJudgment(id) {
  if (!confirm('هل تريد حذف هذا الحكم نهائياً؟')) return;
  fetch('judgments.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(); });
}

function showDetail(d) {
  document.getElementById('detailBody').innerHTML = `
    <div class="row g-3">
      <div class="col-md-6"><strong>رقم القضية:</strong> ${d.case}</div>
      <div class="col-md-6"><strong>رقم الحكم:</strong> ${d.num||'—'}</div>
      <div class="col-md-6"><strong>نوع الحكم:</strong> ${d.type}</div>
      <div class="col-md-6"><strong>تاريخ الحكم:</strong> ${d.date}</div>
      <div class="col-md-6"><strong>القاضي:</strong> ${d.judge||'—'}</div>
      <div class="col-12"><strong>منطوق الحكم:</strong>
        <div class="panel p-3 mt-2" style="background:rgba(201,168,76,.05);border-radius:8px;white-space:pre-wrap">${d.operative}</div>
      </div>
      <div class="col-12"><strong>نص الحكم:</strong>
        <div class="panel p-3 mt-2" style="border-radius:8px;white-space:pre-wrap;max-height:300px;overflow-y:auto">${d.content}</div>
      </div>
    </div>`;
  detailModal.show();
}
</script>

<?php
// AJAX endpoint لتحميل الجلسات
if (isset($_GET['ajax_sessions'])) {
    header('Content-Type: application/json');
    $cid = (int)$_GET['ajax_sessions'];
    $rows = $pdo->prepare("SELECT id, session_number, session_date FROM sessions WHERE case_id=? ORDER BY session_date");
    $rows->execute([$cid]);
    echo json_encode($rows->fetchAll());
    exit;
}
renderFoot();
?>