<?php
/**
 * users.php - إدارة المستخدمين (المشرفين)
 * @version 2.0.0
 */

require_once 'config.php';
checkAdminAuth();

$message = '';
$message_type = '';

// معالجة النماذج
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    // إضافة مستخدم
    if (isset($_POST['add_admin'])) {
        $name = $conn->real_escape_string($_POST['name']);
        $email = $conn->real_escape_string($_POST['email']);
        $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
        
        $check = $conn->query("SELECT id FROM admins WHERE email = '$email'");
        if ($check->num_rows > 0) {
            $message = "❌ البريد الإلكتروني مسجل مسبقاً";
            $message_type = "danger";
        } else {
            if ($conn->query("INSERT INTO admins (name, email, password) VALUES ('$name', '$email', '$password')")) {
                $_SESSION['success_message'] = "✅ تم إضافة المستخدم بنجاح";
                header('Location: users.php');
                exit();
            } else {
                $message = "❌ خطأ: " . $conn->error;
                $message_type = "danger";
            }
        }
    }
    
    // تعديل مستخدم
    if (isset($_POST['edit_admin'])) {
        $id = intval($_POST['id']);
        $name = $conn->real_escape_string($_POST['name']);
        $email = $conn->real_escape_string($_POST['email']);
        
        $check = $conn->query("SELECT id FROM admins WHERE email = '$email' AND id != $id");
        if ($check->num_rows > 0) {
            $message = "❌ البريد الإلكتروني مسجل مسبقاً";
            $message_type = "danger";
        } else {
            $sql = "UPDATE admins SET name='$name', email='$email'";
            
            if (!empty($_POST['password'])) {
                $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
                $sql .= ", password='$password'";
            }
            
            $sql .= " WHERE id=$id";
            
            if ($conn->query($sql)) {
                $_SESSION['success_message'] = "✅ تم تحديث المستخدم بنجاح";
                header('Location: users.php');
                exit();
            } else {
                $message = "❌ خطأ: " . $conn->error;
                $message_type = "danger";
            }
        }
    }
    
    // حذف مستخدم
    if (isset($_POST['delete_admin'])) {
        $id = intval($_POST['id']);
        
        if ($id == $_SESSION['admin_id']) {
            $message = "❌ لا يمكن حذف حسابك الشخصي";
            $message_type = "danger";
        } else {
            if ($conn->query("DELETE FROM admins WHERE id=$id")) {
                $_SESSION['success_message'] = "✅ تم حذف المستخدم بنجاح";
                header('Location: users.php');
                exit();
            } else {
                $message = "❌ خطأ: " . $conn->error;
                $message_type = "danger";
            }
        }
    }
}

// جلب المستخدمين
$admins = $conn->query("SELECT id, name, email, created_at FROM admins ORDER BY created_at DESC");

$page_title = 'إدارة المستخدمين';
include 'includes/header.php';
include 'includes/sidebar.php';
?>

<style>
.user-avatar-lg {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    background: #FFF3E0;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 2rem;
    color: #F57C00;
}

.user-avatar-sm {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: #FFF3E0;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.2rem;
    color: #F57C00;
}

.current-user-badge {
    background: #F57C00;
    color: white;
    font-size: 0.7rem;
    padding: 2px 8px;
    border-radius: 12px;
    margin-right: 5px;
}

@media (max-width: 768px) {
    .user-avatar-lg {
        width: 50px;
        height: 50px;
        font-size: 1.5rem;
    }
    
    .table td, .table th {
        white-space: nowrap;
        font-size: 0.9rem;
    }
}
</style>

<div class="main-content">
    <!-- الهيدر -->
    <nav class="navbar">
        <div class="container-fluid">
            <div class="d-flex align-items-center w-100">
                <span class="navbar-text">
                    <i class="bi bi-person-circle me-2 text-primary"></i>
                    <span class="d-none d-sm-inline">مرحباً،</span>
                    <strong><?php echo htmlspecialchars($_SESSION['admin_name']); ?></strong>
                </span>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <!-- عنوان الصفحة -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>
                <i class="bi bi-people text-primary me-2"></i>
                إدارة المستخدمين
            </h2>
            <button class="btn btn-primary" onclick="openAddModal()">
                <i class="bi bi-plus-circle me-1"></i>
                <span class="d-none d-sm-inline">إضافة مستخدم جديد</span>
                <span class="d-sm-none">إضافة</span>
            </button>
        </div>

        <!-- رسائل التنبيه -->
        <?php if ($message): ?>
            <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show" role="alert">
                <?php echo $message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- بطاقات المستخدمين للجوال -->
        <div class="d-md-none mb-3">
            <?php if ($admins && $admins->num_rows > 0): ?>
                <?php while ($admin = $admins->fetch_assoc()): ?>
                    <div class="card border-0 shadow-sm mb-3">
                        <div class="card-body">
                            <div class="d-flex align-items-center gap-3 mb-3">
                                <div class="user-avatar-lg">
                                    <i class="bi bi-person-circle"></i>
                                </div>
                                <div>
                                    <h6 class="mb-1">
                                        <?php echo htmlspecialchars($admin['name']); ?>
                                        <?php if ($admin['id'] == $_SESSION['admin_id']): ?>
                                            <span class="current-user-badge">أنت</span>
                                        <?php endif; ?>
                                    </h6>
                                    <p class="mb-0 text-muted small"><?php echo htmlspecialchars($admin['email']); ?></p>
                                </div>
                            </div>
                            <div class="d-flex justify-content-between align-items-center">
                                <small class="text-muted">
                                    <i class="bi bi-calendar me-1"></i>
                                    <?php echo date('Y-m-d', strtotime($admin['created_at'])); ?>
                                </small>
                                <div class="d-flex gap-2">
                                    <button class="btn btn-sm btn-warning" 
                                            onclick="editUser(<?php echo $admin['id']; ?>, '<?php echo htmlspecialchars(addslashes($admin['name'])); ?>', '<?php echo $admin['email']; ?>')">
                                        <i class="bi bi-pencil"></i>
                                    </button>
                                    <?php if ($admin['id'] != $_SESSION['admin_id']): ?>
                                        <button class="btn btn-sm btn-danger" 
                                                onclick="deleteUser(<?php echo $admin['id']; ?>, '<?php echo htmlspecialchars(addslashes($admin['name'])); ?>')">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endwhile; ?>
            <?php else: ?>
                <div class="card border-0 shadow-sm">
                    <div class="card-body text-center py-5">
                        <i class="bi bi-people fs-1 text-muted d-block mb-3"></i>
                        <h5 class="text-muted">لا توجد مستخدمين</h5>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <!-- جدول المستخدمين للكمبيوتر -->
        <div class="card border-0 shadow-sm d-none d-md-block">
            <div class="card-header bg-white py-3">
                <h5 class="mb-0">
                    <i class="bi bi-list-ul text-primary me-2"></i>
                    قائمة المستخدمين
                </h5>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="bg-light">
                            <tr>
                                <th>#</th>
                                <th>المستخدم</th>
                                <th>البريد الإلكتروني</th>
                                <th>تاريخ الإنشاء</th>
                                <th>الإجراءات</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($admins && $admins->num_rows > 0): ?>
                                <?php $counter = 1; ?>
                                <?php 
                                $admins->data_seek(0);
                                while ($admin = $admins->fetch_assoc()): 
                                ?>
                                    <tr>
                                        <td><?php echo $counter++; ?></td>
                                        <td>
                                            <div class="d-flex align-items-center gap-2">
                                                <div class="user-avatar-sm">
                                                    <i class="bi bi-person-circle"></i>
                                                </div>
                                                <div>
                                                    <strong><?php echo htmlspecialchars($admin['name']); ?></strong>
                                                    <?php if ($admin['id'] == $_SESSION['admin_id']): ?>
                                                        <span class="current-user-badge">أنت</span>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </td>
                                        <td><?php echo htmlspecialchars($admin['email']); ?></td>
                                        <td><?php echo date('Y-m-d', strtotime($admin['created_at'])); ?></td>
                                        <td>
                                            <button class="btn btn-sm btn-warning" 
                                                    onclick="editUser(<?php echo $admin['id']; ?>, '<?php echo htmlspecialchars(addslashes($admin['name'])); ?>', '<?php echo $admin['email']; ?>')">
                                                <i class="bi bi-pencil"></i>
                                            </button>
                                            <?php if ($admin['id'] != $_SESSION['admin_id']): ?>
                                                <button class="btn btn-sm btn-danger" 
                                                        onclick="deleteUser(<?php echo $admin['id']; ?>, '<?php echo htmlspecialchars(addslashes($admin['name'])); ?>')">
                                                    <i class="bi bi-trash"></i>
                                                </button>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="5" class="text-center py-5">
                                        <i class="bi bi-people fs-1 text-muted d-block mb-3"></i>
                                        <h5 class="text-muted">لا توجد مستخدمين</h5>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- مودال إضافة مستخدم -->
<div class="modal fade" id="addModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-plus-circle text-primary me-2"></i>
                    إضافة مستخدم جديد
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">اسم المستخدم <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="name" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">البريد الإلكتروني <span class="text-danger">*</span></label>
                        <input type="email" class="form-control" name="email" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">كلمة المرور <span class="text-danger">*</span></label>
                        <input type="password" class="form-control" name="password" required minlength="6">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" name="add_admin" class="btn btn-primary">
                        <i class="bi bi-check-circle me-1"></i> إضافة
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- مودال تعديل مستخدم -->
<div class="modal fade" id="editModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-pencil-square text-warning me-2"></i>
                    تعديل المستخدم
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" id="edit_id" name="id">
                    <div class="mb-3">
                        <label class="form-label">اسم المستخدم</label>
                        <input type="text" class="form-control" id="edit_name" name="name" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">البريد الإلكتروني</label>
                        <input type="email" class="form-control" id="edit_email" name="email" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">كلمة المرور الجديدة</label>
                        <input type="password" class="form-control" name="password" minlength="6">
                        <small class="text-muted">اتركها فارغة إذا لم ترغب في التغيير</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" name="edit_admin" class="btn btn-primary">
                        <i class="bi bi-check-circle me-1"></i> تحديث
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function openAddModal() {
    new bootstrap.Modal(document.getElementById('addModal')).show();
}

function editUser(id, name, email) {
    document.getElementById('edit_id').value = id;
    document.getElementById('edit_name').value = name;
    document.getElementById('edit_email').value = email;
    new bootstrap.Modal(document.getElementById('editModal')).show();
}

function deleteUser(id, name) {
    if (confirm(`هل أنت متأكد من حذف المستخدم "${name}"؟`)) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = `
            <input type="hidden" name="id" value="${id}">
            <input type="hidden" name="delete_admin" value="1">
        `;
        document.body.appendChild(form);
        form.submit();
    }
}
</script>

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