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

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

$id = $_GET['id'] ?? 0;
if (!$id) {
    redirect('committees.php');
}

$db = db();
$stmt = $db->prepare("SELECT * FROM committees WHERE id = ?");
$stmt->execute([$id]);
$committee = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$committee) {
    redirect('committees.php');
}

// Check membership for non-admins
if (!isAdmin()) {
    $check_stmt = $db->prepare("
        SELECT 1 
        FROM committee_members m 
        JOIN charity_members cm ON m.charity_member_id = cm.id
        JOIN users u ON (u.id = cm.user_id) OR (cm.email != '' AND cm.email = u.email) OR (cm.name = u.full_name) OR (cm.name = u.username)
        WHERE m.committee_id = ? AND u.id = ?
    ");
    $check_stmt->execute([$id, $_SESSION['user_id']]);
    if (!$check_stmt->fetchColumn()) {
        $_SESSION['error'] = 'غير مصرح لك بعرض هذه اللجنة';
        redirect('committees.php');
    }
}

$tab = $_GET['tab'] ?? 'members';
$allowed_tabs = ['members', 'plans', 'activities'];
if (!in_array($tab, $allowed_tabs)) {
    $tab = 'members';
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    try {
        if ($action === 'add_member' && canAdd('committees')) {
            $charity_member_id = $_POST['charity_member_id'] ?? 0;
            $role = trim($_POST['role'] ?? 'عضو');
            if ($charity_member_id) {
                $stmt = $db->prepare("INSERT INTO committee_members (committee_id, charity_member_id, role, joined_at) VALUES (?, ?, ?, CURDATE())");
                $stmt->execute([$id, $charity_member_id, $role]);
                $_SESSION['success'] = 'تم إضافة العضو بنجاح';
            }
        } elseif ($action === 'edit_member' && canEdit('committees')) {
            $member_id = $_POST['member_id'] ?? 0;
            $role = trim($_POST['role'] ?? 'عضو');
            if ($member_id) {
                $stmt = $db->prepare("UPDATE committee_members SET role = ? WHERE id = ?");
                $stmt->execute([$role, $member_id]);
                $_SESSION['success'] = 'تم تحديث دور العضو بنجاح';
            }
        } elseif ($action === 'delete_member' && canDelete('committees')) {
            $member_id = $_POST['member_id'] ?? 0;
            if ($member_id) {
                $stmt = $db->prepare("DELETE FROM committee_members WHERE id = ?");
                $stmt->execute([$member_id]);
                $_SESSION['success'] = 'تم حذف العضو بنجاح';
            }
        } elseif ($action === 'add_plan' && canAdd('committees')) {
            $title = trim($_POST['title'] ?? '');
            $description = trim($_POST['description'] ?? '');
            $start_date = $_POST['start_date'] ?: null;
            $end_date = $_POST['end_date'] ?: null;
            if ($title) {
                $stmt = $db->prepare("INSERT INTO committee_plans (committee_id, title, description, start_date, end_date) VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([$id, $title, $description, $start_date, $end_date]);
                $_SESSION['success'] = 'تم إضافة الخطة بنجاح';
            }
        } elseif ($action === 'edit_plan' && canEdit('committees')) {
            $plan_id = $_POST['plan_id'] ?? 0;
            $title = trim($_POST['title'] ?? '');
            $description = trim($_POST['description'] ?? '');
            $start_date = $_POST['start_date'] ?: null;
            $end_date = $_POST['end_date'] ?: null;
            $status = $_POST['status'] ?? 'pending';
            if ($plan_id && $title) {
                $stmt = $db->prepare("UPDATE committee_plans SET title = ?, description = ?, start_date = ?, end_date = ?, status = ? WHERE id = ?");
                $stmt->execute([$title, $description, $start_date, $end_date, $status, $plan_id]);
                $_SESSION['success'] = 'تم تحديث الخطة بنجاح';
            }
        } elseif ($action === 'delete_plan' && canDelete('committees')) {
            $plan_id = $_POST['plan_id'] ?? 0;
            if ($plan_id) {
                $stmt = $db->prepare("DELETE FROM committee_plans WHERE id = ?");
                $stmt->execute([$plan_id]);
                $_SESSION['success'] = 'تم حذف الخطة بنجاح';
            }
        } elseif ($action === 'add_activity' && canAdd('committees')) {
            $title = trim($_POST['title'] ?? '');
            $description = trim($_POST['description'] ?? '');
            $activity_date = $_POST['activity_date'] ?: null;
            $location = trim($_POST['location'] ?? '');
            if ($title) {
                $stmt = $db->prepare("INSERT INTO committee_activities (committee_id, title, description, activity_date, location) VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([$id, $title, $description, $activity_date, $location]);
                $_SESSION['success'] = 'تم إضافة النشاط بنجاح';
            }
        } elseif ($action === 'edit_activity' && canEdit('committees')) {
            $activity_id = $_POST['activity_id'] ?? 0;
            $title = trim($_POST['title'] ?? '');
            $description = trim($_POST['description'] ?? '');
            $activity_date = $_POST['activity_date'] ?: null;
            $location = trim($_POST['location'] ?? '');
            if ($activity_id && $title) {
                $stmt = $db->prepare("UPDATE committee_activities SET title = ?, description = ?, activity_date = ?, location = ? WHERE id = ?");
                $stmt->execute([$title, $description, $activity_date, $location, $activity_id]);
                $_SESSION['success'] = 'تم تحديث النشاط بنجاح';
            }
        } elseif ($action === 'delete_activity' && canDelete('committees')) {
            $activity_id = $_POST['activity_id'] ?? 0;
            if ($activity_id) {
                $stmt = $db->prepare("DELETE FROM committee_activities WHERE id = ?");
                $stmt->execute([$activity_id]);
                $_SESSION['success'] = 'تم حذف النشاط بنجاح';
            }
        }
    } catch (PDOException $e) {
        $_SESSION['error'] = 'حدث خطأ: ' . $e->getMessage();
    }
    redirect("view_committee.php?id=$id&tab=$tab");
}

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

// Fetch tab data
$members = [];
$plans = [];
$activities = [];

if ($tab === 'members') {
    $stmt = $db->prepare("SELECT cm.*, u.name as full_name, u.email, u.phone FROM committee_members cm JOIN charity_members u ON cm.charity_member_id = u.id WHERE cm.committee_id = ? ORDER BY cm.id DESC");
    $stmt->execute([$id]);
    $members = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get available users to add
    $member_ids = array_column($members, 'charity_member_id');
    $not_in = count($member_ids) > 0 ? implode(',', array_map('intval', $member_ids)) : '0';
    $available_users = $db->query("SELECT id, name as full_name, email FROM charity_members WHERE status = 'active' AND id NOT IN ($not_in) ORDER BY full_name ASC")->fetchAll(PDO::FETCH_ASSOC);
} elseif ($tab === 'plans') {
    $stmt = $db->prepare("SELECT * FROM committee_plans WHERE committee_id = ? ORDER BY id DESC");
    $stmt->execute([$id]);
    $plans = $stmt->fetchAll(PDO::FETCH_ASSOC);
} elseif ($tab === 'activities') {
    $stmt = $db->prepare("SELECT * FROM committee_activities WHERE committee_id = ? ORDER BY activity_date DESC, id DESC");
    $stmt->execute([$id]);
    $activities = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>

<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">إدارة اللجنة: <?= htmlspecialchars($committee['name']) ?></h1>
    <a href="committees.php" class="btn btn-secondary shadow-sm">
        <i class="fas fa-arrow-right"></i> عودة للجان
    </a>
</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; ?>

<p class="lead text-muted"><?= nl2br(htmlspecialchars($committee['description'])) ?></p>

<ul class="nav nav-tabs mb-4">
    <li class="nav-item">
        <a class="nav-link <?= $tab === 'members' ? 'active' : '' ?>" href="view_committee.php?id=<?= $id ?>&tab=members">
            <i class="fas fa-users"></i> الأعضاء
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link <?= $tab === 'plans' ? 'active' : '' ?>" href="view_committee.php?id=<?= $id ?>&tab=plans">
            <i class="fas fa-tasks"></i> الخطط
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link <?= $tab === 'activities' ? 'active' : '' ?>" href="view_committee.php?id=<?= $id ?>&tab=activities">
            <i class="fas fa-calendar-alt"></i> الأنشطة والفعاليات
        </a>
    </li>
</ul>

<?php if ($tab === 'members'): ?>
    <div class="card shadow-sm border-0 mb-4">
        <div class="card-header bg-white d-flex justify-content-between align-items-center">
            <h5 class="mb-0">أعضاء اللجنة</h5>
            <?php if (canAdd('committees')): ?>
                <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#addMemberModal">
                    <i class="fas fa-plus"></i> إضافة عضو
                </button>
            <?php endif; ?>
        </div>
        <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">الاسم</th>
                            <th>البريد الإلكتروني</th>
                            <th>الهاتف</th>
                            <th>الدور</th>
                            <th>تاريخ الانضمام</th>
                            <th class="text-center">الإجراءات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (count($members) > 0): ?>
                            <?php foreach ($members as $m): ?>
                                <tr>
                                    <td class="ps-4 fw-bold"><?= htmlspecialchars($m['full_name']) ?></td>
                                    <td><?= htmlspecialchars($m['email']) ?></td>
                                    <td><a href="tel:<?= htmlspecialchars($m['phone'] ?? '') ?>"><?= htmlspecialchars($m['phone'] ?? '-' ) ?></a></td>
                                    <td><span class="badge bg-info text-dark"><?= htmlspecialchars($m['role']) ?></span></td>
                                    <td><?= $m['joined_at'] ?></td>
                                    <td class="text-center">
                                        <?php if (canEdit('committees')): ?>
                                        <button class="btn btn-sm btn-outline-primary me-1" onclick='editMember(<?= json_encode($m, JSON_HEX_APOS | JSON_HEX_QUOT) ?>)'>
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <?php endif; ?>
                                        <?php if (canDelete('committees')): ?>
                                        <form method="POST" class="d-inline" onsubmit="return confirm('هل أنت متأكد من الحذف؟');">
                                            <input type="hidden" name="action" value="delete_member">
                                            <input type="hidden" name="member_id" value="<?= $m['id'] ?>">
                                            <button type="submit" class="btn btn-sm btn-outline-danger">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="5" class="text-center py-4 text-muted">لا يوجد أعضاء في هذه اللجنة حالياً.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Add Member Modal -->
    <div class="modal fade" id="addMemberModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="POST">
                    <input type="hidden" name="action" value="add_member">
                    <div class="modal-header bg-primary text-white">
                        <h5 class="modal-title">إضافة عضو جديد</h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label fw-bold">المستخدم <span class="text-danger">*</span></label>
                            <select name="charity_member_id" class="form-select" required>
                                <option value="">-- اختر مستخدم --</option>
                                <?php foreach ($available_users as $u): ?>
                                    <option value="<?= $u['id'] ?>"><?= htmlspecialchars($u['full_name']) ?> (<?= htmlspecialchars($u['email']) ?>)</option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-bold">الدور في اللجنة</label>
                            <input type="text" name="role" class="form-control" placeholder="مثال: رئيس اللجنة، عضو، سكرتير" value="عضو">
                        </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>

    <!-- Edit Member Modal -->
    <div class="modal fade" id="editMemberModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="POST">
                    <input type="hidden" name="action" value="edit_member">
                    <input type="hidden" name="member_id" id="edit_member_id">
                    <div class="modal-header bg-primary text-white">
                        <h5 class="modal-title">تعديل دور العضو</h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label fw-bold">الدور في اللجنة</label>
                            <input type="text" name="role" id="edit_member_role" class="form-control" required>
                        </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>
    function editMember(member) {
        document.getElementById('edit_member_id').value = member.id;
        document.getElementById('edit_member_role').value = member.role;
        new bootstrap.Modal(document.getElementById('editMemberModal')).show();
    }
    </script>
<?php endif; ?>


<?php if ($tab === 'plans'): ?>
    <div class="card shadow-sm border-0 mb-4">
        <div class="card-header bg-white d-flex justify-content-between align-items-center">
            <h5 class="mb-0">خطط اللجنة</h5>
            <?php if (canAdd('committees')): ?>
                <button class="btn btn-sm btn-primary" onclick="openPlanModal('add')">
                    <i class="fas fa-plus"></i> إضافة خطة
                </button>
            <?php endif; ?>
        </div>
        <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">عنوان الخطة</th>
                            <th>تاريخ البداية</th>
                            <th>تاريخ النهاية</th>
                            <th>الحالة</th>
                            <th class="text-center">الإجراءات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $status_colors = [
                            'pending' => 'secondary',
                            'in_progress' => 'primary',
                            'completed' => 'success',
                            'cancelled' => 'danger'
                        ];
                        $status_labels = [
                            'pending' => 'قيد الانتظار',
                            'in_progress' => 'قيد التنفيذ',
                            'completed' => 'مكتملة',
                            'cancelled' => 'ملغاة'
                        ];
                        if (count($plans) > 0): ?>
                            <?php foreach ($plans as $p): ?>
                                <tr>
                                    <td class="ps-4 fw-bold">
                                        <?= htmlspecialchars($p['title']) ?>
                                        <div class="small text-muted text-truncate" style="max-width: 200px;"><?= htmlspecialchars($p['description'] ?? '') ?></div>
                                    </td>
                                    <td><?= $p['start_date'] ?: '-' ?></td>
                                    <td><?= $p['end_date'] ?: '-' ?></td>
                                    <td><span class="badge bg-<?= $status_colors[$p['status']] ?>"><?= $status_labels[$p['status']] ?></span></td>
                                    <td class="text-center">
                                        <?php if (canEdit('committees')): ?>
                                        <button class="btn btn-sm btn-outline-primary me-1" onclick='openPlanModal("edit", <?= json_encode($p, JSON_HEX_APOS | JSON_HEX_QUOT) ?>)'>
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <?php endif; ?>
                                        <?php if (canDelete('committees')): ?>
                                        <form method="POST" class="d-inline" onsubmit="return confirm('هل أنت متأكد من الحذف؟');">
                                            <input type="hidden" name="action" value="delete_plan">
                                            <input type="hidden" name="plan_id" value="<?= $p['id'] ?>">
                                            <button type="submit" class="btn btn-sm btn-outline-danger">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="5" class="text-center py-4 text-muted">لا توجد خطط مضافة حالياً.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Plan Modal -->
    <div class="modal fade" id="planModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="POST">
                    <input type="hidden" name="action" id="planAction" value="add_plan">
                    <input type="hidden" name="plan_id" id="planId" value="0">
                    <div class="modal-header bg-primary text-white">
                        <h5 class="modal-title" id="planModalTitle">إضافة خطة جديدة</h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label fw-bold">عنوان الخطة <span class="text-danger">*</span></label>
                            <input type="text" name="title" id="planTitle" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-bold">الوصف</label>
                            <textarea name="description" id="planDescription" class="form-control" rows="3"></textarea>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">تاريخ البداية</label>
                                <input type="date" name="start_date" id="planStart" class="form-control">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">تاريخ النهاية</label>
                                <input type="date" name="end_date" id="planEnd" class="form-control">
                            </div>
                        </div>
                        <div class="mb-3" id="planStatusDiv" style="display:none;">
                            <label class="form-label fw-bold">الحالة</label>
                            <select name="status" id="planStatus" class="form-select">
                                <option value="pending">قيد الانتظار</option>
                                <option value="in_progress">قيد التنفيذ</option>
                                <option value="completed">مكتملة</option>
                                <option value="cancelled">ملغاة</option>
                            </select>
                        </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 planModal;
    function openPlanModal(action, data = null) {
        if (!planModal) planModal = new bootstrap.Modal(document.getElementById('planModal'));
        document.getElementById('planAction').value = action === 'add' ? 'add_plan' : 'edit_plan';
        document.getElementById('planModalTitle').textContent = action === 'add' ? 'إضافة خطة جديدة' : 'تعديل الخطة';
        
        if (action === 'add') {
            document.getElementById('planId').value = '';
            document.getElementById('planTitle').value = '';
            document.getElementById('planDescription').value = '';
            document.getElementById('planStart').value = '';
            document.getElementById('planEnd').value = '';
            document.getElementById('planStatusDiv').style.display = 'none';
        } else {
            document.getElementById('planId').value = data.id;
            document.getElementById('planTitle').value = data.title;
            document.getElementById('planDescription').value = data.description || '';
            document.getElementById('planStart').value = data.start_date || '';
            document.getElementById('planEnd').value = data.end_date || '';
            document.getElementById('planStatus').value = data.status;
            document.getElementById('planStatusDiv').style.display = 'block';
        }
        planModal.show();
    }
    </script>
<?php endif; ?>


<?php if ($tab === 'activities'): ?>
    <div class="card shadow-sm border-0 mb-4">
        <div class="card-header bg-white d-flex justify-content-between align-items-center">
            <h5 class="mb-0">أنشطة وفعاليات اللجنة</h5>
            <?php if (canAdd('committees')): ?>
                <button class="btn btn-sm btn-primary" onclick="openActivityModal('add')">
                    <i class="fas fa-plus"></i> إضافة نشاط
                </button>
            <?php endif; ?>
        </div>
        <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">النشاط</th>
                            <th>التاريخ</th>
                            <th>الموقع</th>
                            <th class="text-center">الإجراءات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (count($activities) > 0): ?>
                            <?php foreach ($activities as $a): ?>
                                <tr>
                                    <td class="ps-4 fw-bold">
                                        <?= htmlspecialchars($a['title']) ?>
                                        <div class="small text-muted text-truncate" style="max-width: 200px;"><?= htmlspecialchars($a['description'] ?? '') ?></div>
                                    </td>
                                    <td><?= $a['activity_date'] ?: '-' ?></td>
                                    <td><?= htmlspecialchars($a['location'] ?? '-') ?></td>
                                    <td class="text-center">
                                        <?php if (canEdit('committees')): ?>
                                        <button class="btn btn-sm btn-outline-primary me-1" onclick='openActivityModal("edit", <?= json_encode($a, JSON_HEX_APOS | JSON_HEX_QUOT) ?>)'>
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <?php endif; ?>
                                        <?php if (canDelete('committees')): ?>
                                        <form method="POST" class="d-inline" onsubmit="return confirm('هل أنت متأكد من الحذف؟');">
                                            <input type="hidden" name="action" value="delete_activity">
                                            <input type="hidden" name="activity_id" value="<?= $a['id'] ?>">
                                            <button type="submit" class="btn btn-sm btn-outline-danger">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="4" class="text-center py-4 text-muted">لا توجد أنشطة مضافة حالياً.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Activity Modal -->
    <div class="modal fade" id="activityModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="POST">
                    <input type="hidden" name="action" id="activityAction" value="add_activity">
                    <input type="hidden" name="activity_id" id="activityId" value="0">
                    <div class="modal-header bg-primary text-white">
                        <h5 class="modal-title" id="activityModalTitle">إضافة نشاط جديد</h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label fw-bold">عنوان النشاط <span class="text-danger">*</span></label>
                            <input type="text" name="title" id="activityTitle" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-bold">الوصف</label>
                            <textarea name="description" id="activityDescription" class="form-control" rows="3"></textarea>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">تاريخ النشاط</label>
                                <input type="date" name="activity_date" id="activityDate" class="form-control">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">الموقع / المكان</label>
                                <input type="text" name="location" id="activityLocation" class="form-control">
                            </div>
                        </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 activityModal;
    function openActivityModal(action, data = null) {
        if (!activityModal) activityModal = new bootstrap.Modal(document.getElementById('activityModal'));
        document.getElementById('activityAction').value = action === 'add' ? 'add_activity' : 'edit_activity';
        document.getElementById('activityModalTitle').textContent = action === 'add' ? 'إضافة نشاط جديد' : 'تعديل النشاط';
        
        if (action === 'add') {
            document.getElementById('activityId').value = '';
            document.getElementById('activityTitle').value = '';
            document.getElementById('activityDescription').value = '';
            document.getElementById('activityDate').value = '';
            document.getElementById('activityLocation').value = '';
        } else {
            document.getElementById('activityId').value = data.id;
            document.getElementById('activityTitle').value = data.title;
            document.getElementById('activityDescription').value = data.description || '';
            document.getElementById('activityDate').value = data.activity_date || '';
            document.getElementById('activityLocation').value = data.location || '';
        }
        activityModal.show();
    }
    </script>
<?php endif; ?>

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