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

if (!isAdmin() && !canView('charity_members')) {
    echo "<div class='alert alert-danger'>غير مصرح لك بالوصول لهذه الصفحة.</div>";
    require_once 'includes/footer.php';
    exit;
}

$action = $_GET['action'] ?? 'list';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_member']) && (isAdmin() || canAdd('charity_members'))) {
        $name = $_POST['name'] ?? '';
        $role = $_POST['role'] ?? '';
        $phone = $_POST['phone'] ?? '';
        $email = $_POST['email'] ?? '';
        $join_date = $_POST['join_date'] ?? date('Y-m-d');
        $status = $_POST['status'] ?? 'active';

        $stmt = db()->prepare("INSERT INTO charity_members (name, role, phone, email, join_date, status) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->execute([$name, $role, $phone, $email, $join_date, $status]);
        
        $_SESSION['success'] = "تمت إضافة العضو بنجاح.";
        redirect('charity_members.php');
    } elseif (isset($_POST['edit_member']) && (isAdmin() || canEdit('charity_members'))) {
        $id = $_POST['id'];
        $name = $_POST['name'] ?? '';
        $role = $_POST['role'] ?? '';
        $phone = $_POST['phone'] ?? '';
        $email = $_POST['email'] ?? '';
        $join_date = $_POST['join_date'] ?? date('Y-m-d');
        $status = $_POST['status'] ?? 'active';

        $stmt = db()->prepare("UPDATE charity_members SET name = ?, role = ?, phone = ?, email = ?, join_date = ?, status = ? WHERE id = ?");
        $stmt->execute([$name, $role, $phone, $email, $join_date, $status, $id]);
        
        $_SESSION['success'] = "تم تحديث العضو بنجاح.";
        redirect('charity_members.php');
    } elseif (isset($_POST['delete_member']) && (isAdmin() || canDelete('charity_members'))) {
        $id = $_POST['id'];
        $stmt = db()->prepare("DELETE FROM charity_members WHERE id = ?");
        $stmt->execute([$id]);
        
        $_SESSION['success'] = "تم حذف العضو بنجاح.";
        redirect('charity_members.php');
    }
}

// Fetch members
$stmt = db()->query("SELECT * FROM charity_members ORDER BY name ASC");
$members = $stmt->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2 class="h4 mb-0"><i class="fas fa-users text-primary me-2"></i> أعضاء الجمعية</h2>
    <div>
        <a href="print_charity_report.php" target="_blank" class="btn btn-secondary me-2">
            <i class="fas fa-print me-2"></i> طباعة تقرير الجمعية
        </a>
        <?php if (isAdmin() || canAdd('charity_members')): ?>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addMemberModal">
        <i class="fas fa-plus me-2"></i> إضافة عضو جديد
    </button>
    <?php endif; ?>
    </div>
</div>

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

<div class="card border-0 shadow-sm">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead class="table-light">
                    <tr>
                        <th>الاسم</th>
                        <th>الدور/الصفة</th>
                        <th>رقم الجوال</th>
                        <th>البريد الإلكتروني</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-end">الإجراءات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($members as $member): ?>
                    <tr>
                        <td>
                            <div class="d-flex align-items-center">
                                <div class="bg-primary bg-opacity-10 text-primary rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 40px; height: 40px;">
                                    <i class="fas fa-user"></i>
                                </div>
                                <div>
                                    <div class="fw-bold"><?= htmlspecialchars($member['name']) ?></div>
                                </div>
                            </div>
                        </td>
                        <td><?= htmlspecialchars($member['role']) ?></td>
                        <td><?= htmlspecialchars($member['phone']) ?></td>
                        <td><?= htmlspecialchars($member['email']) ?></td>
                        <td><?= htmlspecialchars($member['join_date']) ?></td>
                        <td>
                            <?php if ($member['status'] === 'active'): ?>
                                <span class="badge bg-success bg-opacity-10 text-success px-3 py-2 rounded-pill">نشط</span>
                            <?php else: ?>
                                <span class="badge bg-secondary bg-opacity-10 text-secondary px-3 py-2 rounded-pill">غير نشط</span>
                            <?php endif; ?>
                        </td>
                        <td><small class="text-muted"><i class="fas fa-user text-primary opacity-50 me-1"></i><?= htmlspecialchars(getAuditUserName($member['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($member['updated_by'] ?? null)) ?></small></td>
                            <td class="text-end">
                            <?php if (isAdmin() || canEdit('charity_members')): ?>
                            <button class="btn btn-sm btn-outline-primary me-2" data-bs-toggle="modal" data-bs-target="#editMemberModal<?= $member['id'] ?>">
                                <i class="fas fa-edit"></i>
                            </button>
                            <?php endif; ?>
                            <?php if (isAdmin() || canDelete('charity_members')): ?>
                            <button class="btn btn-sm btn-outline-danger" data-bs-toggle="modal" data-bs-target="#deleteMemberModal<?= $member['id'] ?>">
                                <i class="fas fa-trash"></i>
                            </button>
                            <?php endif; ?>
                        </td>
                    </tr>

                    <!-- Edit Modal -->
                    <div class="modal fade" id="editMemberModal<?= $member['id'] ?>" tabindex="-1">
                        <div class="modal-dialog">
                            <div class="modal-content border-0 shadow">
                                <div class="modal-header bg-light">
                                    <h5 class="modal-title">تعديل بيانات العضو</h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                </div>
                                <form method="POST">
                                    <div class="modal-body">
                                        <input type="hidden" name="id" value="<?= $member['id'] ?>">
                                        <input type="hidden" name="edit_member" value="1">
                                        
                                        <div class="mb-3">
                                            <label class="form-label">الاسم</label>
                                            <input type="text" class="form-control" name="name" value="<?= htmlspecialchars($member['name']) ?>" required>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">الدور/الصفة في الجمعية</label>
                                            <input type="text" class="form-control" name="role" value="<?= htmlspecialchars($member['role']) ?>" placeholder="مثال: عضو مجلس الإدارة، مدير عام...">
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">رقم الجوال</label>
                                            <input type="text" class="form-control" name="phone" value="<?= htmlspecialchars($member['phone']) ?>">
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">البريد الإلكتروني</label>
                                            <input type="email" class="form-control" name="email" value="<?= htmlspecialchars($member['email']) ?>">
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">تاريخ الانضمام</label>
                                            <input type="date" class="form-control" name="join_date" value="<?= htmlspecialchars($member['join_date']) ?>">
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">الحالة</label>
                                            <select class="form-select" name="status">
                                                <option value="active" <?= $member['status'] == 'active' ? 'selected' : '' ?>>نشط</option>
                                                <option value="inactive" <?= $member['status'] == 'inactive' ? 'selected' : '' ?>>غير نشط</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">إلغاء</button>
                                        <button type="submit" class="btn btn-primary">حفظ التغييرات</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <!-- Delete Modal -->
                    <div class="modal fade" id="deleteMemberModal<?= $member['id'] ?>" tabindex="-1">
                        <div class="modal-dialog">
                            <div class="modal-content border-0 shadow">
                                <div class="modal-header bg-light">
                                    <h5 class="modal-title">تأكيد الحذف</h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                </div>
                                <div class="modal-body text-center p-4">
                                    <i class="fas fa-exclamation-triangle text-danger fa-3x mb-3"></i>
                                    <h4 class="mb-3">هل أنت متأكد؟</h4>
                                    <p class="text-muted">هل تريد حقاً حذف العضو "<?= htmlspecialchars($member['name']) ?>"؟ لا يمكن التراجع عن هذا الإجراء وسيتم حذفه من أي لجان مرتبط بها.</p>
                                </div>
                                <div class="modal-footer justify-content-center border-0">
                                    <form method="POST">
                                        <input type="hidden" name="id" value="<?= $member['id'] ?>">
                                        <input type="hidden" name="delete_member" value="1">
                                        <button type="button" class="btn btn-light px-4" data-bs-dismiss="modal">إلغاء</button>
                                        <button type="submit" class="btn btn-danger px-4">نعم، احذف</button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                    <?php if (empty($members)): ?>
                    <tr>
                        <td colspan="9" class="text-center text-muted py-4">لا يوجد أعضاء مضافين حتى الآن</td>
                    </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Add Modal -->
<div class="modal fade" id="addMemberModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-light">
                <h5 class="modal-title">إضافة عضو جديد</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="add_member" value="1">
                    
                    <div class="mb-3">
                        <label class="form-label">الاسم</label>
                        <input type="text" class="form-control" name="name" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">الدور/الصفة في الجمعية</label>
                        <input type="text" class="form-control" name="role" placeholder="مثال: عضو مجلس الإدارة، مدير عام...">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">رقم الجوال</label>
                        <input type="text" class="form-control" name="phone">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">البريد الإلكتروني</label>
                        <input type="email" class="form-control" name="email">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">تاريخ الانضمام</label>
                        <input type="date" class="form-control" name="join_date" value="<?= date('Y-m-d') ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">الحالة</label>
                        <select class="form-select" name="status">
                            <option value="active">نشط</option>
                            <option value="inactive">غير نشط</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" class="btn btn-primary">إضافة العضو</button>
                </div>
            </form>
        </div>
    </div>
</div>

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