<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../config/database.php';

$database = new Database();
$db = $database->getConnection();
$auth = new Auth($database);

// Check permissions
if (!$auth->hasPermission('president')) {
    header('Location: index.php');
    exit();
}

// Handle member operations
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        try {
            switch ($_POST['action']) {
                case 'add':
                    $stmt = $db->prepare("INSERT INTO members (full_name, role, phone, email) VALUES (?, ?, ?, ?)");
                    $stmt->execute([
                        $_POST['full_name'],
                        $_POST['role'],
                        $_POST['phone'],
                        $_POST['email']
                    ]);
                    break;

                case 'edit':
                    $stmt = $db->prepare("UPDATE members SET full_name = ?, role = ?, phone = ?, email = ? WHERE id = ?");
                    $stmt->execute([
                        $_POST['full_name'],
                        $_POST['role'],
                        $_POST['phone'],
                        $_POST['email'],
                        $_POST['member_id']
                    ]);
                    break;

                case 'delete':
                    if (isset($_POST['member_id']) && !empty($_POST['member_id'])) {
                        $stmt = $db->prepare("DELETE FROM members WHERE id = ?");
                        $stmt->execute([$_POST['member_id']]);
                    }
                    break;
            }
            header('Location: ?page=members&success=1');
            exit();
        } catch (PDOException $e) {
            $error = 'حدث خطأ أثناء تنفيذ العملية: ' . $e->getMessage();
        }
    }
}

// Get all active members
$stmt = $db->query("SELECT * FROM members WHERE status = 'active' ORDER BY role, full_name");
$members = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Define member roles
$memberRoles = [
    'president' => 'رئيس',
    'vice_president' => 'نائب الرئيس',
    'secretary' => 'الكاتب',
    'vice_secretary' => 'نائب الكاتب',
    'treasurer' => 'الأمين',
    'vice_treasurer' => 'نائب الأمين',
    'advisor' => 'مستشار',
    'member' => 'منخرط'
];
?>

<div class="container-fluid">
    <div class="row mb-4">
        <div class="col">
            <h2>إدارة الأعضاء</h2>
        </div>
        <div class="col-auto">
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addMemberModal">
                <i class="bi bi-plus-circle"></i> إضافة عضو جديد
            </button>
        </div>
    </div>

    <div class="table-container">
        <table class="table table-striped datatable">
            <thead>
                <tr>
                    <th>الاسم الكامل</th>
                    <th>الصفة</th>
                    <th>الهاتف</th>
                    <th>البريد الإلكتروني</th>
                    <th>العمليات</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($members as $member): ?>
                <tr>
                    <td><?php echo htmlspecialchars($member['full_name']); ?></td>
                    <td><?php echo htmlspecialchars($memberRoles[$member['role']] ?? $member['role']); ?></td>
                    <td><?php echo htmlspecialchars($member['phone']); ?></td>
                    <td><?php echo htmlspecialchars($member['email']); ?></td>
                    <td>
                        <button class="btn btn-sm btn-primary edit-member" 
                                data-member='<?php echo json_encode($member); ?>'
                                data-bs-toggle="modal" 
                                data-bs-target="#editMemberModal">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <button class="btn btn-sm btn-danger delete-item" 
                                data-id="<?php echo $member['id']; ?>"
                                data-type="العضو"
                                data-name="<?php echo htmlspecialchars($member['full_name']); ?>"
                                data-action="delete"
                                data-form-id="deleteMemberForm"
                                data-id-field="member_id">
                            <i class="bi bi-trash"></i>
                        </button>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Add Member Modal -->
<div class="modal fade" id="addMemberModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <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="action" value="add">
                    <div class="mb-3">
                        <label class="form-label">الاسم الكامل</label>
                        <input type="text" class="form-control" name="full_name" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">الصفة</label>
                        <select class="form-control" name="role" required>
                            <?php foreach ($memberRoles as $value => $label): ?>
                            <option value="<?php echo $value; ?>"><?php echo $label; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">الهاتف</label>
                        <input type="tel" 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>
                <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">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <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="action" value="edit">
                    <input type="hidden" name="member_id" id="edit_member_id">
                    <div class="mb-3">
                        <label class="form-label">الاسم الكامل</label>
                        <input type="text" class="form-control" name="full_name" id="edit_full_name" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">الصفة</label>
                        <select class="form-control" name="role" id="edit_role" required>
                            <?php foreach ($memberRoles as $value => $label): ?>
                            <option value="<?php echo $value; ?>"><?php echo $label; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">الهاتف</label>
                        <input type="tel" class="form-control" name="phone" id="edit_phone">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">البريد الإلكتروني</label>
                        <input type="email" class="form-control" name="email" id="edit_email">
                    </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>

<form method="POST" id="deleteMemberForm" style="display: none;">
    <input type="hidden" name="action" value="delete">
    <input type="hidden" name="member_id" id="delete_member_id">
</form>

<script>
$(document).ready(function() {
    // Initialize edit member modal
    $('.edit-member').click(function() {
        const member = $(this).data('member');
        $('#edit_member_id').val(member.id);
        $('#edit_full_name').val(member.full_name);
        $('#edit_role').val(member.role);
        $('#edit_phone').val(member.phone);
        $('#edit_email').val(member.email);
    });
});
</script>
