<?php
$page_title = 'User Management';
require_once 'includes/header.php';

// Fetch All Users
try {
    $stmt = $pdo->prepare("
        SELECT u.*, s.shop_name 
        FROM users u 
        LEFT JOIN shops s ON u.shop_id = s.shop_id 
        ORDER BY u.user_id DESC
    ");
    $stmt->execute();
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Fetch Shops for Dropdown
    $shopStmt = $pdo->query("SELECT shop_id, shop_name FROM shops WHERE status = 1");
    $shops = $shopStmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}
?>

<div class="card">
    <div class="card-header">
        <h3 class="card-title"><i class="fas fa-users"></i> ຈັດການຜູ້ໃຊ້ງານ</h3>
        <button class="btn btn-primary" onclick="openAddModal()">
            <i class="fas fa-plus"></i> ເພີ່ມຜູ້ໃຊ້
        </button>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table" style="width:100%; border-collapse: collapse; text-align: left;">
                <thead>
                    <tr style="border-bottom: 1px solid var(--border-color);">
                        <th style="padding: 12px;">ID</th>
                        <th style="padding: 12px;">Username</th>
                        <th style="padding: 12px;">ຊື່</th>
                        <th style="padding: 12px;">Role</th>
                        <th style="padding: 12px;">ຮ້ານຄ້າ</th>
                        <th style="padding: 12px;">ສະຖານະ</th>
                        <th style="padding: 12px;">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($users as $user): ?>
                        <tr style="border-bottom: 1px solid var(--border-color);">
                            <td style="padding: 12px;">
                                <?= $user['user_id'] ?>
                            </td>
                            <td style="padding: 12px;">
                                <?= htmlspecialchars($user['username']) ?>
                            </td>
                            <td style="padding: 12px;">
                                <?= htmlspecialchars($user['name']) ?>
                            </td>
                            <td style="padding: 12px;">
                                <span class="badge badge-role">
                                    <?= ucfirst($user['role']) ?>
                                </span>
                            </td>
                            <td style="padding: 12px;">
                                <?= htmlspecialchars($user['shop_name'] ?? '-') ?>
                            </td>
                            <td style="padding: 12px;">
                                <?php if ($user['status'] == 1): ?>
                                    <span style="color: var(--success);">Active</span>
                                <?php else: ?>
                                    <span style="color: var(--danger);">Inactive</span>
                                <?php endif; ?>
                            </td>
                            <td style="padding: 12px;">
                                <button class="btn btn-secondary" onclick='editUser(<?= json_encode($user) ?>)'
                                    style="padding: 5px 10px; font-size: 13px;">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button class="btn btn-danger" onclick="deleteUser(<?= $user['user_id'] ?>)"
                                    style="padding: 5px 10px; font-size: 13px; background: var(--danger); color: white; border: none;">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Add/Edit User Modal -->
<div id="userModal" class="modal-overlay">
    <div class="modal">
        <div class="modal-header">
            <h3 class="modal-title" id="modalTitle">ເພີ່ມຜູ້ໃຊ້</h3>
            <button class="modal-close" onclick="closeGenericModal('userModal')">&times;</button>
        </div>
        <form id="userForm" action="actions/user_actions.php" method="POST">
            <div class="modal-body">
                <input type="hidden" name="action" id="action" value="add">
                <input type="hidden" name="user_id" id="user_id">

                <div class="form-group">
                    <label class="form-label">Username</label>
                    <input type="text" name="username" id="username" class="form-control" required>
                </div>
                <div class="form-group">
                    <label class="form-label">ຊື່-ນາມສະກຸນ</label>
                    <input type="text" name="name" id="name" class="form-control" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Email</label>
                    <input type="email" name="email" id="email" class="form-control">
                </div>
                <div class="form-group">
                    <label class="form-label">Password <span id="passwordHint"
                            style="font-size: 12px; color: var(--text-secondary);">(ວ່າງໄວ້ຖ້າບໍ່ປ່ຽນ)</span></label>
                    <input type="password" name="password" id="password" class="form-control">
                </div>
                <div class="form-group">
                    <label class="form-label">Role</label>
                    <select name="role" id="role" class="form-control" required>
                        <option value="staff">Staff</option>
                        <option value="manager">Manager</option>
                        <option value="superadmin">Superadmin</option>
                        <option value="representative">Representative</option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">ຮ້ານຄ້າ</label>
                    <select name="shop_id" id="shop_id" class="form-control">
                        <option value="">ເລືອກຮ້ານຄ້າ</option>
                        <?php foreach ($shops as $shop): ?>
                            <option value="<?= $shop['shop_id'] ?>">
                                <?= htmlspecialchars($shop['shop_name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">ສະຖານະ</label>
                    <select name="status" id="status" class="form-control">
                        <option value="1">Active</option>
                        <option value="0">Inactive</option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary"
                    onclick="closeGenericModal('userModal')">ຍົກເລີກ</button>
                <button type="submit" class="btn btn-primary">ບັນທຶກ</button>
            </div>
        </form>
    </div>
</div>

<script>
    function openAddModal() {
        document.getElementById('modalTitle').innerText = 'ເພີ່ມຜູ້ໃຊ້';
        document.getElementById('action').value = 'add';
        document.getElementById('user_id').value = '';
        document.getElementById('userForm').reset();
        document.getElementById('password').required = true;
        document.getElementById('passwordHint').style.display = 'none';
        openGenericModal('userModal');
    }

    function editUser(user) {
        document.getElementById('modalTitle').innerText = 'ແກ້ໄຂຜູ້ໃຊ້';
        document.getElementById('action').value = 'edit';
        document.getElementById('user_id').value = user.user_id;
        document.getElementById('username').value = user.username;
        document.getElementById('name').value = user.name;
        document.getElementById('email').value = user.email;
        document.getElementById('role').value = user.role;
        document.getElementById('shop_id').value = user.shop_id || '';
        document.getElementById('status').value = user.status;

        document.getElementById('password').required = false;
        document.getElementById('passwordHint').style.display = 'inline';

        openGenericModal('userModal');
    }

    function deleteUser(id) {
        Swal.fire({
            title: 'ຢືນຢັນການລຶບ?',
            text: "ທ່ານຕ້ອງການລຶບຜູ້ໃຊ້ນີ້ບໍ່?",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'ລຶບ!',
            cancelButtonText: 'ຍົກເລີກ'
        }).then((result) => {
            if (result.isConfirmed) {
                // Send delete request
                const formData = new FormData();
                formData.append('action', 'delete');
                formData.append('user_id', id);

                fetch('actions/user_actions.php', {
                    method: 'POST',
                    body: formData
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            Swal.fire('Deleted!', 'ລຶບສຳເລັດແລ້ວ.', 'success')
                                .then(() => location.reload());
                        } else {
                            Swal.fire('Error!', data.message || 'ເກີດຂໍ້ຜິດພາດ', 'error');
                        }
                    });
            }
        });
    }

    // Handle Form Submit
    document.getElementById('userForm').onsubmit = function (e) {
        e.preventDefault();
        const formData = new FormData(this);

        fetch('actions/user_actions.php', {
            method: 'POST',
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    closeGenericModal('userModal');
                    Swal.fire('Success!', 'ບັນທຶກສຳເລັດແລ້ວ.', 'success')
                        .then(() => location.reload());
                } else {
                    Swal.fire('Error!', data.message || 'ເກີດຂໍ້ຜິດພາດ', 'error');
                }
            });
    };
</script>

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