<?php
require_once __DIR__ . '/includes/header.php';

if (!canView('committees')) {
    redirect('index.php');
}

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        $action = $_POST['action'];
        $id = $_POST['id'] ?? 0;
        $name = trim($_POST['name'] ?? '');
        $description = trim($_POST['description'] ?? '');
        
        try {
            $db = db();
            if ($action === 'add' && canAdd('committees')) {
                if (empty($name)) {
                    $_SESSION['error'] = 'اسم اللجنة مطلوب';
                } else {
                    $stmt = $db->prepare("INSERT INTO committees (name, description) VALUES (?, ?)");
                    $stmt->execute([$name, $description]);
                    $_SESSION['success'] = 'تم إضافة اللجنة بنجاح';
                }
            } elseif ($action === 'edit' && $id && canEdit('committees')) {
                if (empty($name)) {
                    $_SESSION['error'] = 'اسم اللجنة مطلوب';
                } else {
                    $stmt = $db->prepare("UPDATE committees SET name = ?, description = ? WHERE id = ?");
                    $stmt->execute([$name, $description, $id]);
                    $_SESSION['success'] = 'تم تحديث اللجنة بنجاح';
                }
            }
        } catch (PDOException $e) {
            $_SESSION['error'] = 'حدث خطأ: ' . $e->getMessage();
        }
        redirect('committees.php');
    }
}

if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    if (!canDelete('committees')) redirect('committees.php');
    $id = $_GET['id'];
    try {
        $db = db();
        $stmt = $db->prepare("DELETE FROM committees WHERE id = ?");
        $stmt->execute([$id]);
        $_SESSION['success'] = 'تم حذف اللجنة بنجاح';
    } catch (PDOException $e) {
        $_SESSION['error'] = 'حدث خطأ: ' . $e->getMessage();
    }
    redirect('committees.php');
}

$committees = db()->query("SELECT * FROM committees ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);

if (isset($_SESSION['success'])) {
    $success = $_SESSION['success'];
    unset($_SESSION['success']);
}
if (isset($_SESSION['error'])) {
    $error = $_SESSION['error'];
    unset($_SESSION['error']);
}
?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">اللجان</h1>
    <?php if (canAdd('committees')): ?>
    <button type="button" class="btn btn-primary shadow-sm" onclick="openModal('add')">
        <i class="fas fa-plus"></i> إضافة لجنة جديدة
    </button>
    <?php endif; ?>
</div>

<?php if ($success): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <?= $success ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<?php if ($error): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <?= $error ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<div class="card shadow-sm border-0">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="bg-light">
                    <tr>
                        <th class="ps-4" style="width: 80px;">الرقم</th>
                        <th>اسم اللجنة</th>
                        <th>الوصف</th>
                        <th class="text-secondary text-nowrap" style="font-size: 0.85rem;"><i class="fas fa-user-plus me-1"></i>أضيف بواسطة</th>
                        <th class="text-secondary text-nowrap" style="font-size: 0.85rem;"><i class="fas fa-user-edit me-1"></i>عُدل بواسطة</th>
                        <th class="text-center">الإجراءات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($committees) > 0): ?>
                        <?php foreach ($committees as $committee): ?>
                            <tr>
                                <td class="ps-4"><?= htmlspecialchars($committee['id']) ?></td>
                                <td class="fw-bold"><?= htmlspecialchars($committee['name']) ?></td>
                                <td><?= htmlspecialchars($committee['description'] ?? '') ?></td>
<td><small class="text-muted"><i class="fas fa-user text-primary opacity-50 me-1"></i><?= htmlspecialchars(getAuditUserName($committee['created_by'] ?? null)) ?></small></td>
                            <td><small class="text-muted"><i class="fas fa-user-edit text-warning opacity-50 me-1"></i><?= htmlspecialchars(getAuditUserName($committee['updated_by'] ?? null)) ?></small></td>
                            <td class="text-center">
                                    <a href="view_committee.php?id=<?= $committee['id'] ?>" class="btn btn-sm btn-outline-info me-1" title="إدارة اللجنة"><i class="fas fa-cog"></i> إدارة</a>
                                    <?php if (canEdit('committees')): ?>
                                    <button class="btn btn-sm btn-outline-primary me-1" onclick='openModal("edit", <?= json_encode($committee, JSON_HEX_APOS | JSON_HEX_QUOT) ?>)'>
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <?php endif; ?>
                                    <?php if (canDelete('committees')): ?>
                                    <a href="javascript:void(0)" onclick="confirmDelete(<?= $committee['id'] ?>)" class="btn btn-sm btn-outline-danger">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="6" class="text-center py-4 text-muted">لا توجد لجان مضافة حتى الآن.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Modal -->
<div class="modal fade" id="committeeModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="modalTitle">إضافة لجنة جديدة</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" action="committees.php">
                <div class="modal-body">
                    <input type="hidden" name="action" id="modalAction" value="add">
                    <input type="hidden" name="id" id="modalId" value="0">
                    
                    <div class="mb-3">
                        <label class="form-label fw-bold">اسم اللجنة <span class="text-danger">*</span></label>
                        <input type="text" name="name" id="modalName" class="form-control" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label fw-bold">الوصف</label>
                        <textarea name="description" id="modalDescription" class="form-control" rows="4"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" class="btn btn-primary">حفظ</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
let committeeModal;

function openModal(action, data = null) {
    if (!committeeModal) {
        committeeModal = new bootstrap.Modal(document.getElementById('committeeModal'));
    }
    
    document.getElementById('modalAction').value = action;
    const title = document.getElementById('modalTitle');
    
    if (action === 'add') {
        title.textContent = 'إضافة لجنة جديدة';
        document.getElementById('modalId').value = 0;
        document.getElementById('modalName').value = '';
        document.getElementById('modalDescription').value = '';
    } else {
        title.textContent = 'تعديل بيانات اللجنة';
        document.getElementById('modalId').value = data.id;
        document.getElementById('modalName').value = data.name;
        document.getElementById('modalDescription').value = data.description || '';
    }
    
    committeeModal.show();
}

function confirmDelete(id) {
    if (confirm('هل أنت متأكد من حذف هذه اللجنة؟ لا يمكن التراجع عن هذا الإجراء.')) {
        window.location.href = 'committees.php?action=delete&id=' + id;
    }
}
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
