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

// ── ثوابت الطعون (تشمل المعارضة) ──────────────────────────────
// نستورد التعريفات من constants.php (RECOURSE_TYPES) لتفادي التكرار
$APPEAL_TYPES = [];
foreach (RECOURSE_TYPES as $k => $v) {
    $APPEAL_TYPES[$k] = ['label' => $v['label'], 'class' => $v['class']];
}
$APPEAL_STATUS = [
    'filed'        => ['label' => 'مقدم',          'class' => 'primary'],
    'under_review' => ['label' => 'قيد الدراسة',   'class' => 'info'],
    'decided'      => ['label' => 'تم الفصل',      'class' => 'success'],
    'rejected'     => ['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'];
        $judgmentId = (int)$_POST['judgment_id'];
        $aType      = $_POST['appeal_type']  ?? 'istinaf';
        $aDate      = $_POST['appeal_date']  ?? date('Y-m-d');
        $appellant  = trim($_POST['appellant'] ?? '');
        $grounds    = trim($_POST['grounds']   ?? '');

        // قيد قانوني: المعارضة لا تُقبل إلا ضد حكم غيابي
        if ($aType === 'opposition') {
            $j = $pdo->prepare("SELECT is_default FROM judgments WHERE id = ?");
            $j->execute([$judgmentId]);
            $isDefault = (int)$j->fetchColumn();
            if (!$isDefault) {
                echo json_encode(['ok'=>false, 'msg'=>'المعارضة لا تُقبل إلا ضد حكم غيابي. تحقق من خانة "حكم غيابي" في الحكم المعني.']);
                exit;
            }
        }

        if ($caseId && $judgmentId && $appellant) {
            // جلب تاريخ الحكم ونوع القضية لحساب الأجل
            $jrow = $pdo->prepare("SELECT j.judgment_date, c.case_type FROM judgments j JOIN cases c ON c.id=j.case_id WHERE j.id=?");
            $jrow->execute([$judgmentId]);
            $jdata = $jrow->fetch();
            $deadline = $jdata ? computeRecourseDeadline($aType, $jdata['judgment_date'], $jdata['case_type']) : null;

            $pdo->prepare("INSERT INTO appeals (case_id,judgment_id,appeal_type,appeal_date,deadline_date,appellant,grounds,status,created_by)
                VALUES (?,?,?,?,?,?,?,'filed',?)")
                ->execute([$caseId,$judgmentId,$aType,$aDate,$deadline,$appellant,$grounds?:null,$user['id']]);
            $pdo->prepare("UPDATE judgments SET status='appealed' WHERE id=?")->execute([$judgmentId]);
            $pdo->prepare("UPDATE cases SET status='appealed' WHERE id=?")->execute([$caseId]);
            $auditMsg = ($aType === 'opposition') ? 'تسجيل معارضة' : 'تسجيل طعن (' . ($APPEAL_TYPES[$aType]['label'] ?? $aType) . ')';
            auditLog($user['id'], ($aType === 'opposition' ? 'add_opposition' : 'add_appeal'), 'appeals', $pdo->lastInsertId(), $auditMsg);
            echo json_encode(['ok'=>true]);
        } else {
            echo json_encode(['ok'=>false,'msg'=>'يرجى ملء جميع الحقول المطلوبة']);
        }
        exit;
    }

    if ($_POST['action'] === 'update_status' && $id) {
        $newStatus = $_POST['status'] ?? '';
        $result    = trim($_POST['result'] ?? '');
        if (array_key_exists($newStatus, $APPEAL_STATUS)) {
            $decidedAt = $newStatus === 'decided' ? date('Y-m-d') : null;
            $pdo->prepare("UPDATE appeals SET status=?, result=?, decided_at=? WHERE id=?")
                ->execute([$newStatus, $result?:null, $decidedAt, $id]);
            auditLog($user['id'],'update_appeal_status','appeals',$id,"تغيير حالة الطعن إلى $newStatus");
            echo json_encode(['ok'=>true]);
        } else { echo json_encode(['ok'=>false]); }
        exit;
    }

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

// AJAX: جلب أحكام القضية مع علم الغيابي
if (isset($_GET['ajax_judgments'])) {
    header('Content-Type: application/json');
    $cid = (int)$_GET['ajax_judgments'];
    $rows = $pdo->prepare("SELECT id, COALESCE(judgment_number,CONCAT('حكم #',id)) AS label, judgment_date, is_default FROM judgments WHERE case_id=? ORDER BY judgment_date DESC");
    $rows->execute([$cid]);
    echo json_encode($rows->fetchAll(), JSON_UNESCAPED_UNICODE);
    exit;
}

// ── الفلاتر ───────────────────────────────────────────────────
$search    = trim($_GET['q']     ?? '');
$atype     = $_GET['atype']      ?? '';
$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 a.appellant LIKE ?)"; $p="%$search%"; $params=array_merge($params,[$p,$p,$p]); }
if ($atype)     { $where[] = "a.appeal_type = ?"; $params[] = $atype; }
if ($status)    { $where[] = "a.status = ?"; $params[] = $status; }
if ($date_from) { $where[] = "a.appeal_date >= ?"; $params[] = $date_from; }
if ($date_to)   { $where[] = "a.appeal_date <= ?"; $params[] = $date_to; }
$whereSQL = $where ? 'WHERE '.implode(' AND ',$where) : '';

$stmt = $pdo->prepare("
    SELECT a.*, c.case_number, c.title AS case_title,
           COALESCE(j.judgment_number, CONCAT('حكم #',j.id)) AS judgment_label,
           u.full_name AS creator_name
    FROM appeals a
    JOIN cases c    ON a.case_id = c.id
    JOIN judgments j ON a.judgment_id = j.id
    JOIN users u    ON a.created_by = u.id
    $whereSQL
    ORDER BY a.appeal_date DESC, a.created_at DESC
");
$stmt->execute($params);
$appeals = $stmt->fetchAll();

// إحصائيات
$stats = $pdo->query("
    SELECT COUNT(*) AS total,
           SUM(status='filed')        AS filed,
           SUM(status='under_review') AS under_review,
           SUM(status='decided')      AS decided
    FROM appeals
")->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('appeals','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:#0d6efd"><?= $stats['filed'] ?></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:#0dcaf0"><?= $stats['under_review'] ?></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['decided'] ?></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:250px">
      <select name="atype" class="form-select" style="width:130px">
        <option value="">كل الأنواع</option>
        <?php foreach ($APPEAL_TYPES as $k=>$v): ?>
        <option value="<?= $k ?>" <?= $atype===$k?'selected':'' ?>><?= $v['label'] ?></option>
        <?php endforeach; ?>
      </select>
      <select name="status" class="form-select" style="width:140px">
        <option value="">كل الحالات</option>
        <?php foreach ($APPEAL_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||$atype||$status||$date_from||$date_to): ?>
      <a href="appeals.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('appealsTable','قائمة_الطعون')">
        <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">
    <div class="table-responsive">
      <table class="table dt-table" id="appealsTable">
        <thead><tr>
          <th>#</th>
          <th>رقم القضية</th>
          <th>عنوان القضية</th>
          <th>نوع الطعن</th>
          <th>تاريخ الطعن</th>
          <th>المستأنف</th>
          <th>الحكم المطعون فيه</th>
          <th>الحالة</th>
          <th>الإجراءات</th>
        </tr></thead>
        <tbody>
        <?php if (empty($appeals)): ?>
        <tr><td colspan="9">
          <div class="empty-state py-5">
            <i class="bi bi-arrow-left-right" 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>
        </td></tr>
        <?php else: foreach ($appeals as $i => $a):
            $at = $APPEAL_TYPES[$a['appeal_type']]   ?? ['label'=>$a['appeal_type'],'class'=>'secondary'];
            $as_ = $APPEAL_STATUS[$a['status']]      ?? ['label'=>$a['status'],'class'=>'secondary'];
        ?>
        <tr>
          <td class="text-muted" style="font-size:12px"><?= $i+1 ?></td>
          <td>
            <a href="case-view.php?id=<?= $a['case_id'] ?>" class="text-navy fw-700 text-decoration-none">
              <?= htmlspecialchars($a['case_number']) ?>
            </a>
          </td>
          <td style="max-width:180px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis">
            <?= htmlspecialchars($a['case_title']) ?>
          </td>
          <td><span class="badge bg-<?= $at['class'] ?>"><?= $at['label'] ?></span></td>
          <td style="white-space:nowrap"><?= date('d/m/Y', strtotime($a['appeal_date'])) ?></td>
          <td><?= htmlspecialchars($a['appellant']) ?></td>
          <td style="font-size:13px"><?= htmlspecialchars($a['judgment_label']) ?></td>
          <td>
            <select class="form-select form-select-sm status-asel" data-id="<?= $a['id'] ?>"
                    style="width:130px;font-size:12px" onchange="updateAppealStatus(this)">
              <?php foreach ($APPEAL_STATUS as $k=>$v): ?>
              <option value="<?= $k ?>" <?= $a['status']===$k?'selected':'' ?>><?= $v['label'] ?></option>
              <?php endforeach; ?>
            </select>
          </td>
          <td>
            <div class="d-flex gap-1">
              <?php if ($a['grounds']): ?>
              <button class="action-btn" title="أسباب الطعن"
                onclick='alert(<?= json_encode($a["grounds"]) ?>)'><i class="bi bi-chat-text"></i></button>
              <?php endif; ?>
              <a href="case-view.php?id=<?= $a['case_id'] ?>" class="action-btn gold" title="عرض القضية"><i class="bi bi-folder2-open"></i></a>
              <button class="action-btn danger" title="حذف" onclick="deleteAppeal(<?= $a['id'] ?>)"><i class="bi bi-trash"></i></button>
            </div>
          </td>
        </tr>
        <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </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-arrow-left-right 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="aa_case_id" class="form-select" onchange="loadJudgments(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">الحكم المطعون فيه <span class="text-danger">*</span></label>
            <select id="aa_judgment_id" class="form-select">
              <option value="">— اختر أولاً القضية —</option>
            </select>
          </div>
          <div class="col-md-6">
            <label class="form-label">نوع الطعن <span class="text-danger">*</span></label>
            <select id="aa_appeal_type" class="form-select" onchange="updateRecourseHint()">
              <?php foreach ($APPEAL_TYPES as $k=>$v): ?>
              <option value="<?= $k ?>"><?= $v['label'] ?></option>
              <?php endforeach; ?>
            </select>
            <small id="recourseHint" class="text-muted d-block mt-1" style="font-size:11px"></small>
          </div>
          <div class="col-md-6">
            <label class="form-label">تاريخ تقديم الطعن <span class="text-danger">*</span></label>
            <input type="date" id="aa_appeal_date" class="form-control" value="<?= date('Y-m-d') ?>">
            <small id="deadlineHint" class="text-warning d-block mt-1" style="font-size:11px"></small>
          </div>
          <div class="col-12">
            <label class="form-label">المستأنف / الطاعن <span class="text-danger">*</span></label>
            <input type="text" id="aa_appellant" class="form-control" placeholder="اسم الطرف المستأنف">
          </div>
          <div class="col-12">
            <label class="form-label">أسباب الطعن</label>
            <textarea id="aa_grounds" class="form-control" rows="4" 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="submitAppeal()"><i class="bi bi-save"></i> تسجيل الطعن</button>
      </div>
    </div>
  </div>
</div>

<script>
const RECOURSE_TYPES = <?= json_encode(RECOURSE_TYPES, JSON_UNESCAPED_UNICODE) ?>;
let addModal;
let currentJudgments = [];

document.addEventListener('DOMContentLoaded', () => {
  addModal = new bootstrap.Modal(document.getElementById('addModal'));
  updateRecourseHint();
});
function showAddModal() { addModal.show(); }

function loadJudgments(caseId) {
  const sel = document.getElementById('aa_judgment_id');
  sel.innerHTML = '<option value="">جارٍ التحميل...</option>';
  currentJudgments = [];
  if (!caseId) { sel.innerHTML = '<option value="">— اختر أولاً القضية —</option>'; return; }
  fetch(`appeals.php?ajax_judgments=${caseId}`)
    .then(r => r.json())
    .then(data => {
      currentJudgments = data || [];
      sel.innerHTML = '<option value="">اختر الحكم...</option>';
      if (!currentJudgments.length) { sel.innerHTML = '<option value="">لا توجد أحكام لهذه القضية</option>'; return; }
      currentJudgments.forEach(j => {
        const o = document.createElement('option');
        o.value = j.id;
        const tag = (parseInt(j.is_default) === 1) ? ' [غيابي]' : ' [حضوري]';
        o.textContent = `${j.label} — ${j.judgment_date}${tag}`;
        o.dataset.isDefault = j.is_default;
        o.dataset.date = j.judgment_date;
        sel.appendChild(o);
      });
    });
}

function updateRecourseHint() {
  const t = document.getElementById('aa_appeal_type').value;
  const meta = RECOURSE_TYPES[t];
  const hint = document.getElementById('recourseHint');
  if (!meta) { hint.textContent = ''; return; }
  let txt = `يُقدَّم ضد: ${meta.against}`;
  if (meta.requires_default_judgment) txt += ' — يستلزم حكماً غيابياً';
  hint.textContent = txt;
  hint.className = meta.requires_default_judgment ? 'text-info d-block mt-1' : 'text-muted d-block mt-1';
  hint.style.fontSize = '11px';
  showDeadline();
}

function showDeadline() {
  const sel = document.getElementById('aa_judgment_id');
  const opt = sel.options[sel.selectedIndex];
  const t = document.getElementById('aa_appeal_type').value;
  const meta = RECOURSE_TYPES[t];
  const out = document.getElementById('deadlineHint');
  if (!opt || !opt.dataset.date || !meta) { out.textContent = ''; return; }
  // نأخذ الآجل المدني افتراضياً (لا نعلم نوع القضية هنا بدون نداء آخر)
  const days = parseInt(meta.deadline_days_civil) || 0;
  if (!days) { out.textContent = 'لا يوجد أجل قانوني صارم لهذا النوع.'; return; }
  const d = new Date(opt.dataset.date);
  d.setDate(d.getDate() + days);
  out.textContent = `آخر أجل (تقديري، مدني): ${d.toISOString().substr(0,10)} — ${days} يوماً من تاريخ الحكم`;
}

document.getElementById('aa_judgment_id').addEventListener('change', showDeadline);

function submitAppeal() {
  const msg = document.getElementById('addMsg');
  const caseId = document.getElementById('aa_case_id').value;
  const judgmentSel = document.getElementById('aa_judgment_id');
  const judgmentId = judgmentSel.value;
  const appellant = document.getElementById('aa_appellant').value.trim();
  const type = document.getElementById('aa_appeal_type').value;
  if (!caseId || !judgmentId || !appellant) {
    msg.innerHTML = '<div class="alert alert-danger py-2">يرجى ملء جميع الحقول المطلوبة</div>';
    return;
  }
  // فحص مسبق على جهة العميل (السيرفر يفحص أيضاً)
  if (type === 'opposition') {
    const opt = judgmentSel.options[judgmentSel.selectedIndex];
    if (opt && parseInt(opt.dataset.isDefault) !== 1) {
      msg.innerHTML = '<div class="alert alert-warning py-2">المعارضة لا تُقبل إلا ضد حكم غيابي. اختر حكماً يحمل وسم [غيابي] أو غيّر نوع الطعن.</div>';
      return;
    }
  }
  const body = new URLSearchParams({
    action: 'add',
    case_id: caseId,
    judgment_id: judgmentId,
    appeal_type: type,
    appeal_date: document.getElementById('aa_appeal_date').value,
    appellant: appellant,
    grounds: document.getElementById('aa_grounds').value
  });
  fetch('appeals.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 updateAppealStatus(sel) {
  const prev = sel.dataset.prev;
  fetch('appeals.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-asel').forEach(s => {
  s.dataset.prev = s.value;
  s.addEventListener('focus', function(){ this.dataset.prev = this.value; });
});

function deleteAppeal(id) {
  if (!confirm('هل تريد حذف هذا الطعن نهائياً؟')) return;
  fetch('appeals.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(); });
}
</script>

<?php renderFoot(); ?>
