<?php
/**
 * User Management Page
 * CMTC Shopping
 */
require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/navbar.php';

require_login();
require_permission($db, 'manage_users');

$error = "";
$success = "";

// Handle User Status Update
if (isset($_GET['toggle_status_id'])) {
    $toggle_id = intval($_GET['toggle_status_id']);
    $current_status = $_GET['current'] ?? 'active';
    $new_status = ($current_status === 'active') ? 'inactive' : 'active';

    if ($toggle_id !== $_SESSION['user_id']) {
        $stmt_tog = $db->prepare("UPDATE users SET status = ? WHERE id = ?");
        $stmt_tog->execute([$new_status, $toggle_id]);
        $success = "อัปเดตสถานะผู้ใช้งานเรียบร้อยแล้ว";
    }
}

// Fetch users
$stmt_u = $db->query("
    SELECT u.*, r.name as role_name, d.name as department_name
    FROM users u
    LEFT JOIN user_roles r ON u.role_id = r.id
    LEFT JOIN departments d ON u.department_id = d.id
    ORDER BY u.id DESC
");
$users = $stmt_u->fetchAll();
$roles = $db->query("SELECT * FROM user_roles ORDER BY id ASC")->fetchAll();
?>

<div class="d-flex">
    <?php require_once __DIR__ . '/../includes/sidebar.php'; ?>

    <main class="flex-grow-1 p-4" style="background-color: var(--bs-body-bg);">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h3 class="fw-bold mb-0"><i class="bi bi-people-fill text-primary me-2"></i>จัดการผู้ใช้งาน (Users)</h3>
                <p class="text-muted small mb-0">ตรวจสอบรายชื่อ สิทธิ์การใช้งาน และสถานะสมาชิก</p>
            </div>
        </div>

        <?php if (!empty($error)): ?>
            <div class="alert alert-danger mb-4"><?php echo $error; ?></div>
        <?php endif; ?>
        <?php if (!empty($success)): ?>
            <div class="alert alert-success mb-4"><?php echo $success; ?></div>
        <?php endif; ?>

        <div class="card border-0 shadow-sm glass-card p-4">
            <div class="table-responsive">
                <table class="table table-hover align-middle datatable">
                    <thead>
                        <tr>
                            <th>ผู้ใช้งาน</th>
                            <th>ชื่อผู้ใช้</th>
                            <th>เบอร์โทร</th>
                            <th>อีเมล</th>
                            <th>บทบาท</th>
                            <th>สถานะ</th>
                            <th class="text-center">จัดการ</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($users as $u): ?>
                            <tr>
                                <td>
                                    <div class="d-flex align-items-center gap-2">
                                        <?php if (!empty($u['avatar'])): ?>
                                            <img src="<?php echo base_url('uploads/' . sanitize($u['avatar'])); ?>" class="rounded-circle" width="40" height="40" style="object-fit: cover;">
                                        <?php else: ?>
                                            <div class="bg-primary-subtle text-primary rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                                <i class="bi bi-person"></i>
                                            </div>
                                        <?php endif; ?>
                                        <div>
                                            <div class="fw-semibold"><?php echo sanitize($u['prefix'] . $u['firstname'] . ' ' . $u['lastname']); ?></div>
                                            <small class="text-muted"><?php echo sanitize($u['department_name'] ?? '-'); ?></small>
                                        </div>
                                    </div>
                                </td>
                                <td><code><?php echo sanitize($u['username']); ?></code></td>
                                <td><?php echo sanitize($u['phone']); ?></td>
                                <td><?php echo sanitize($u['email']); ?></td>
                                <td>
                                    <span class="badge bg-primary"><?php echo sanitize($u['role_name']); ?></span>
                                </td>
                                <td>
                                    <span class="badge bg-<?php echo $u['status'] === 'active' ? 'success' : 'secondary'; ?>">
                                        <?php echo $u['status'] === 'active' ? 'ใช้งานได้' : 'ระงับการใช้'; ?>
                                    </span>
                                </td>
                                <td class="text-center">
                                    <?php if ($u['id'] !== $_SESSION['user_id']): ?>
                                        <a href="users.php?toggle_status_id=<?php echo $u['id']; ?>&current=<?php echo $u['status']; ?>" 
                                           class="btn btn-sm btn-outline-<?php echo $u['status'] === 'active' ? 'warning' : 'success'; ?>"
                                           onclick="return confirm('ยืนยันเปลี่ยนสถานะผู้ใช้นี้?');">
                                            <?php echo $u['status'] === 'active' ? 'ระงับ' : 'เปิดใช้งาน'; ?>
                                        </a>
                                    <?php else: ?>
                                        <span class="badge bg-light text-dark">บัญชีของคุณ</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>
</div>

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