<?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 user operations
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add':
                $password_hash = password_hash($_POST['password'], PASSWORD_DEFAULT);
                $stmt = $db->prepare("INSERT INTO users (username, password, role) VALUES (?, ?, ?)");
                $stmt->execute([
                    $_POST['username'],
                    $password_hash,
                    $_POST['role']
                ]);
                break;

            case 'edit':
                if (!empty($_POST['password'])) {
                    $password_hash = password_hash($_POST['password'], PASSWORD_DEFAULT);
                    $stmt = $db->prepare("UPDATE users SET username = ?, password = ?, role = ? WHERE id = ?");
                    $stmt->execute([
                        $_POST['username'],
                        $password_hash,
                        $_POST['role'],
                        $_POST['user_id']
                    ]);
                } else {
                    $stmt = $db->prepare("UPDATE users SET username = ?, role = ? WHERE id = ?");
                    $stmt->execute([
                        $_POST['username'],
                        $_POST['role'],
                        $_POST['user_id']
                    ]);
                }
                break;

            case 'delete':
                $stmt = $db->prepare("DELETE FROM users WHERE id = ? AND id != ?");
                $stmt->execute([$_POST['user_id'], $_SESSION['user_id']]);
                break;
        }
        header('Location: index.php?page=users');
        exit();
    }
}

// Get all users
$stmt = $db->query("SELECT * FROM users ORDER BY username");
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Define user roles
$userRoles = [
    'president' => 'رئيس',
    'treasurer' => 'أمين المال',
    '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="#addUserModal">
                <i class="bi bi-person-plus"></i> إضافة مستخدم جديد
            </button>
        </div>
    </div>

    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-striped datatable">
                    <thead>
                        <tr>
                            <th>اسم المستخدم</th>
                            <th>الدور</th>
                            <th>تاريخ الإنشاء</th>
                            <th>العمليات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($users as $user): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($user['username']); ?></td>
                            <td><?php echo htmlspecialchars($userRoles[$user['role']] ?? $user['role']); ?></td>
                            <td><?php echo htmlspecialchars($user['created_at']); ?></td>
                            <td>
                                <?php if ($user['id'] != $_SESSION['user_id']): ?>
                                <button class="btn btn-sm btn-primary edit-user" 
                                        data-user='<?php echo json_encode($user); ?>'
                                        data-bs-toggle="modal" 
                                        data-bs-target="#editUserModal">
                                    <i class="bi bi-pencil"></i>
                                </button>
                                <button class="btn btn-sm btn-danger delete-item" 
                                        data-id="<?php echo $user['id']; ?>"
                                        data-type="المستخدم"
                                        data-name="<?php echo htmlspecialchars($user['username']); ?>"
                                        data-action="delete"
                                        data-form-id="deleteUserForm"
                                        data-id-field="user_id">
                                    <i class="bi bi-trash"></i>
                                </button>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Add User Modal -->
<div class="modal fade" id="addUserModal" 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="username" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">كلمة المرور</label>
                        <input type="password" class="form-control" name="password" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">الدور</label>
                        <select class="form-control" name="role" required>
                            <?php foreach ($userRoles as $value => $label): ?>
                            <option value="<?php echo $value; ?>"><?php echo $label; ?></option>
                            <?php endforeach; ?>
                        </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>

<!-- Edit User Modal -->
<div class="modal fade" id="editUserModal" 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="user_id" id="edit_user_id">
                    <div class="mb-3">
                        <label class="form-label">اسم المستخدم</label>
                        <input type="text" class="form-control" name="username" id="edit_username" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">كلمة المرور (اتركها فارغة إذا لم ترد تغييرها)</label>
                        <input type="password" class="form-control" name="password">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">الدور</label>
                        <select class="form-control" name="role" id="edit_role" required>
                            <?php foreach ($userRoles as $value => $label): ?>
                            <option value="<?php echo $value; ?>"><?php echo $label; ?></option>
                            <?php endforeach; ?>
                        </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>

<!-- Delete User Form -->
<form id="deleteUserForm" method="POST" style="display: none;">
    <input type="hidden" name="action" value="delete">
    <input type="hidden" name="user_id" id="delete_user_id">
</form>

<script>
$(document).ready(function() {
    // Initialize edit user modal
    $('.edit-user').click(function() {
        const user = $(this).data('user');
        $('#edit_user_id').val(user.id);
        $('#edit_username').val(user.username);
        $('#edit_role').val(user.role);
    });

    // Handle user deletion
    $('.delete-item').click(function() {
        const id = $(this).data('id');
        const type = $(this).data('type');
        const name = $(this).data('name');
        const action = $(this).data('action');
        const formId = $(this).data('form-id');
        const idField = $(this).data('id-field');
        if (confirm(`هل أنت متأكد من حذف ${type} "${name}"؟`)) {
            $(`#${formId} #${idField}`).val(id);
            $(`#${formId}`).submit();
        }
    });
});
</script>
