<?php
// ============================================================
// modules/admin/bar-associations.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_ADMIN);
$GLOBALS['BASE_URL_CSS'] = BASE_URL . '/public/assets/css/main.css';
$user = currentUser(); $pdo = db();

$msg = $err = '';

// ─── إضافة نقابة جديدة ───────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'add_bar') {
    $name = trim($_POST['name'] ?? '');
    $wilaya = $_POST['seat_wilaya_code'] ?: null;
    if ($name === '') { $err = 'اسم النقابة إلزامي.'; }
    else {
        try {
            $pdo->prepare("INSERT INTO bar_associations (name, seat_wilaya_code) VALUES (?,?)")->execute([$name, $wilaya]);
            auditLog($user['id'],'create_bar_association','bar_associations',(int)$pdo->lastInsertId(),'إنشاء نقابة: '.$name);
            $msg = 'تمت إضافة النقابة بنجاح.';
        } catch (\Exception $e) { $err = 'هذه النقابة موجودة بالفعل أو حدث خطأ.'; }
    }
}

// ─── إضافة مجلس قضائي جديد ───────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'add_council') {
    $name = trim($_POST['name'] ?? '');
    $wilaya = $_POST['wilaya_code'] ?: null;
    $barId = $_POST['bar_association_id'] ?: null;
    if ($name === '') { $err = 'اسم المجلس إلزامي.'; }
    else {
        try {
            $pdo->prepare("INSERT INTO judicial_councils (name, wilaya_code, bar_association_id) VALUES (?,?,?)")->execute([$name, $wilaya, $barId]);
            $councilId = (int)$pdo->lastInsertId();
            // ننشئ تلقائياً محكمة الاستئناف الخاصة بالمجلس (مقر المجلس)
            $pdo->prepare("INSERT INTO courts (name, branch, level, wilaya_code, council_id, is_seat) VALUES (?,?,?,?,?,1)")
                ->execute(["$name (استئناف)", 'ordinary', 'majlis', $wilaya, $councilId]);
            auditLog($user['id'],'create_judicial_council','judicial_councils',$councilId,'إنشاء مجلس قضاء: '.$name);
            $msg = 'تمت إضافة المجلس القضائي بنجاح.';
        } catch (\Exception $e) { $err = 'هذا المجلس موجود بالفعل أو حدث خطأ.'; }
    }
}

// ─── إضافة محكمة تابعة لمجلس ─────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'add_court') {
    $name = trim($_POST['name'] ?? '');
    $councilId = (int)($_POST['council_id'] ?? 0);
    $isSeat = !empty($_POST['is_seat']) ? 1 : 0;
    if ($name === '' || !$councilId) { $err = 'اسم المحكمة والمجلس التابع له إلزاميان.'; }
    else {
        $c = $pdo->prepare("SELECT wilaya_code FROM judicial_councils WHERE id=?"); $c->execute([$councilId]);
        $wilaya = $c->fetchColumn();
        $pdo->prepare("INSERT INTO courts (name, branch, level, wilaya_code, council_id, is_seat) VALUES (?,?,?,?,?,?)")
            ->execute([$name, 'ordinary', 'ibtidaiya', $wilaya ?: null, $councilId, $isSeat]);
        auditLog($user['id'],'create_court','courts',(int)$pdo->lastInsertId(),'إنشاء محكمة: '.$name);
        $msg = 'تمت إضافة المحكمة بنجاح.';
    }
}

// ─── تمييز مجلس كمكتمل البيانات ──────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'toggle_complete') {
    $councilId = (int)($_POST['council_id'] ?? 0);
    $pdo->prepare("UPDATE judicial_councils SET is_complete = 1 - is_complete WHERE id=?")->execute([$councilId]);
}

// ─── جلب الشجرة الكاملة: نقابات > مجالس > محاكم ──────────────
$bars = $pdo->query("SELECT * FROM bar_associations ORDER BY name")->fetchAll();
$councils = $pdo->query("SELECT * FROM judicial_councils ORDER BY name")->fetchAll();
$courtsAll = $pdo->query("SELECT * FROM courts WHERE council_id IS NOT NULL ORDER BY is_seat DESC, name")->fetchAll();

$councilsByBar = [];
foreach ($councils as $c) { $councilsByBar[$c['bar_association_id'] ?? 0][] = $c; }
$courtsByCouncil = [];
foreach ($courtsAll as $ct) { $courtsByCouncil[$ct['council_id']][] = $ct; }

$notifCount = getUnreadNotifCount($user['id']);
renderHead('الولايات والنقابات');
?>
<div class="sidebar" id="sidebar"><?php buildSidebar('bar_associations','admin'); ?></div>
<div class="sidebar-overlay" id="sidebarOverlay"></div>
<div class="main-wrap">
<?php renderTopbar('الهيكل التنظيمي — الولايات والنقابات والمجالس القضائية', $notifCount); ?>
<div class="page-content">

<?php if ($msg): ?><div class="alert alert-success alert-dismissible mb-3"><i class="bi bi-check-circle-fill me-2"></i><?= htmlspecialchars($msg) ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>
<?php if ($err): ?><div class="alert alert-danger alert-dismissible mb-3"><i class="bi bi-exclamation-triangle-fill me-2"></i><?= htmlspecialchars($err) ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

<div class="d-flex justify-content-between align-items-center mb-3">
  <h5 class="mb-0">النقابات (<?= count($bars) ?>) والمجالس القضائية التابعة لها</h5>
  <div class="d-flex gap-2">
    <button class="btn btn-outline-secondary btn-sm" data-bs-toggle="modal" data-bs-target="#addCouncilModal"><i class="bi bi-plus-circle"></i> مجلس قضاء جديد</button>
    <button class="btn btn-gold btn-sm" data-bs-toggle="modal" data-bs-target="#addBarModal"><i class="bi bi-plus-circle"></i> نقابة جديدة</button>
  </div>
</div>

<?php foreach ($bars as $bar): $myCouncils = $councilsByBar[$bar['id']] ?? []; ?>
<div class="panel mb-3">
  <div class="panel-header d-flex justify-content-between align-items-center">
    <div class="panel-title"><i class="bi bi-bank"></i> <?= htmlspecialchars($bar['name']) ?></div>
    <span class="badge bg-navy"><?= count($myCouncils) ?> مجلس قضائي</span>
  </div>
  <div class="panel-body">
    <?php if (empty($myCouncils)): ?>
      <p class="text-muted mb-0">لا توجد مجالس قضائية مرتبطة بعد.</p>
    <?php endif; ?>
    <div class="accordion" id="acc-<?= $bar['id'] ?>">
      <?php foreach ($myCouncils as $council): $myCourts = $courtsByCouncil[$council['id']] ?? []; ?>
      <div class="accordion-item" style="border-color:var(--border)">
        <h2 class="accordion-header">
          <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#c<?= $council['id'] ?>">
            <?= htmlspecialchars($council['name']) ?>
            &nbsp;<span class="badge bg-<?= $council['is_complete'] ? 'success' : 'warning' ?> ms-2"><?= $council['is_complete'] ? 'مكتمل' : 'غير مكتمل' ?></span>
            &nbsp;<span class="text-muted" style="font-size:12px">(<?= count($myCourts) ?> محكمة)</span>
          </button>
        </h2>
        <div id="c<?= $council['id'] ?>" class="accordion-collapse collapse" data-bs-parent="#acc-<?= $bar['id'] ?>">
          <div class="accordion-body">
            <ul class="mb-3">
              <?php foreach ($myCourts as $ct): ?>
              <li><?= htmlspecialchars($ct['name']) ?> <?php if ($ct['is_seat']): ?><span class="badge bg-gold" style="color:#0A1628">مقر</span><?php endif; ?> <span class="text-muted" style="font-size:11px">[<?= COURT_LEVELS[$ct['level']]['label'] ?? $ct['level'] ?>]</span></li>
              <?php endforeach; ?>
            </ul>
            <div class="d-flex gap-2">
              <button class="btn btn-sm btn-outline-secondary" onclick="openAddCourt(<?= $council['id'] ?>, '<?= htmlspecialchars(addslashes($council['name'])) ?>')"><i class="bi bi-plus"></i> إضافة محكمة</button>
              <form method="POST" class="d-inline">
                <input type="hidden" name="action" value="toggle_complete">
                <input type="hidden" name="council_id" value="<?= $council['id'] ?>">
                <button type="submit" class="btn btn-sm btn-outline-secondary"><i class="bi bi-check2-square"></i> <?= $council['is_complete'] ? 'وضع كغير مكتمل' : 'وضع كمكتمل' ?></button>
              </form>
            </div>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
</div>
<?php endforeach; ?>
<?php if (empty($bars)): ?><div class="panel"><div class="panel-body text-center text-muted py-4">لا توجد نقابات مسجلة بعد.</div></div><?php endif; ?>

</div></div>

<!-- Add Bar Modal -->
<div class="modal fade" id="addBarModal" tabindex="-1">
  <div class="modal-dialog"><div class="modal-content">
    <div class="modal-header border-0 pb-0"><h5 class="modal-title font-amiri">إضافة نقابة محامين</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
    <form method="POST">
      <input type="hidden" name="action" value="add_bar">
      <div class="modal-body">
        <label class="form-label">اسم النقابة <span class="text-danger">*</span></label>
        <input type="text" name="name" class="form-control mb-3" placeholder="مثال: نقابة وهران" required>
        <label class="form-label">ولاية المقر</label>
        <select name="seat_wilaya_code" class="form-select">
          <option value="">— اختر —</option>
          <?php foreach (WILAYAS as $code=>$wname): ?><option value="<?= $code ?>"><?= $code ?> - <?= $wname ?></option><?php endforeach; ?>
        </select>
      </div>
      <div class="modal-footer border-0"><button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">إلغاء</button><button type="submit" class="btn btn-gold">إضافة</button></div>
    </form>
  </div></div>
</div>

<!-- Add Council Modal -->
<div class="modal fade" id="addCouncilModal" tabindex="-1">
  <div class="modal-dialog"><div class="modal-content">
    <div class="modal-header border-0 pb-0"><h5 class="modal-title font-amiri">إضافة مجلس قضاء</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
    <form method="POST">
      <input type="hidden" name="action" value="add_council">
      <div class="modal-body">
        <label class="form-label">اسم المجلس <span class="text-danger">*</span></label>
        <input type="text" name="name" class="form-control mb-3" placeholder="مثال: مجلس قضاء وهران" required>
        <label class="form-label">الولاية</label>
        <select name="wilaya_code" class="form-select mb-3">
          <option value="">— اختر —</option>
          <?php foreach (WILAYAS as $code=>$wname): ?><option value="<?= $code ?>"><?= $code ?> - <?= $wname ?></option><?php endforeach; ?>
        </select>
        <label class="form-label">النقابة التابع لها <span class="text-danger">*</span></label>
        <select name="bar_association_id" class="form-select" required>
          <option value="">— اختر —</option>
          <?php foreach ($bars as $b): ?><option value="<?= $b['id'] ?>"><?= htmlspecialchars($b['name']) ?></option><?php endforeach; ?>
        </select>
      </div>
      <div class="modal-footer border-0"><button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">إلغاء</button><button type="submit" class="btn btn-gold">إضافة</button></div>
    </form>
  </div></div>
</div>

<!-- Add Court Modal -->
<div class="modal fade" id="addCourtModal" tabindex="-1">
  <div class="modal-dialog"><div class="modal-content">
    <div class="modal-header border-0 pb-0"><h5 class="modal-title font-amiri">إضافة محكمة إلى <span id="councilNameLabel"></span></h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
    <form method="POST">
      <input type="hidden" name="action" value="add_court">
      <input type="hidden" name="council_id" id="addCourtCouncilId">
      <div class="modal-body">
        <label class="form-label">اسم المحكمة <span class="text-danger">*</span></label>
        <input type="text" name="name" class="form-control mb-3" placeholder="مثال: محكمة وهران" required>
        <div class="form-check">
          <input type="checkbox" class="form-check-input" name="is_seat" id="isSeatCheck" value="1">
          <label class="form-check-label" for="isSeatCheck">هذه هي محكمة مقر المجلس</label>
        </div>
      </div>
      <div class="modal-footer border-0"><button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">إلغاء</button><button type="submit" class="btn btn-gold">إضافة</button></div>
    </form>
  </div></div>
</div>

<script>
function openAddCourt(councilId, councilName) {
  document.getElementById('addCourtCouncilId').value = councilId;
  document.getElementById('councilNameLabel').textContent = councilName;
  new bootstrap.Modal(document.getElementById('addCourtModal')).show();
}
</script>
<?php renderFoot(); ?>
