<?php
/**
 * Roles Management Page
 * SSCI Office Platform
 */

// Bootstrap is already loaded from public/index.php

$auth = $GLOBALS['auth'];
$db = $GLOBALS['db'];
$pageTitle = trans('roles') . ' - ' . config('app.name');

if (!$auth->isAuthenticated() || !$auth->hasPermission('manage_roles')) {
    header('Location: ?page=login');
    exit();
}

require_once __DIR__ . '/../../layouts/header.php';

// Get roles configuration
$rolesConfig = require config_path('roles.php');
$predefinedRoles = ['admin', 'manager', 'controller', 'guard', 'client'];

// Get all available permissions
$allPermissions = [];
if (is_array($rolesConfig)) {
    foreach ($rolesConfig as $role => $config) {
        if (isset($config['permissions'])) {
            $allPermissions = array_unique(array_merge($allPermissions, $config['permissions']));
        }
    }
}
sort($allPermissions);

$action = $_GET['action'] ?? null;
$roleName = $_GET['role'] ?? null;
?>

<div class="animate__animated animate__fadeIn w-full mx-auto px-4 sm:px-6 lg:px-8 max-w-6xl pb-20 md:pb-8">
    <div class="mb-6">
        <h1 class="text-2xl sm:text-3xl font-bold text-gray-800">
            <i class="fas fa-users-cog text-blue-600 mr-3"></i><?php echo trans('user_management') ?? 'User Management'; ?>
        </h1>
        <p class="text-gray-600 text-sm mt-1"><?php echo trans('manage_users_and_roles') ?? 'Manage users, roles, and permissions'; ?></p>
    </div>

    <!-- Tabs Navigation -->
    <div class="bg-white rounded-lg shadow mb-6 overflow-hidden">
        <div class="flex border-b border-gray-200 overflow-x-auto">
            <button class="tab-btn flex-1 min-w-max px-6 py-4 text-center font-semibold transition-all active" data-tab="roles">
                <i class="fas fa-shield-alt mr-2"></i><?php echo trans('roles') ?? 'Roles & Permissions'; ?>
            </button>
            <button class="tab-btn flex-1 min-w-max px-6 py-4 text-center font-semibold transition-all text-gray-600 hover:text-gray-900" data-tab="users">
                <i class="fas fa-users mr-2"></i><?php echo trans('users') ?? 'Users'; ?>
            </button>
        </div>
    </div>

    <!-- Roles Tab Content -->
    <div class="tab-content active" id="roles-content">
        <!-- Roles Grid -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <?php foreach ($predefinedRoles as $role) { 
            $config = $rolesConfig[$role] ?? [];
            $permissions = $config['permissions'] ?? [];
            $description = $config['description'] ?? '';
        ?>
            <div class="bg-white rounded-lg shadow overflow-hidden hover:shadow-lg transition border-t-4 border-blue-600">
                <!-- Role Header -->
                <div class="bg-gradient-to-r from-blue-600 to-blue-700 p-4">
                    <h3 class="text-xl font-bold text-white mb-1"><?php echo ucfirst($role); ?></h3>
                    <p class="text-blue-100 text-sm"><?php echo htmlspecialchars($description); ?></p>
                </div>

                <!-- Permissions List -->
                <div class="p-4">
                    <p class="text-xs font-semibold text-gray-500 uppercase mb-3"><?php echo trans('permissions'); ?> (<?php echo count($permissions); ?>)</p>
                    
                    <?php if (!empty($permissions)) { ?>
                        <div class="space-y-2 max-h-48 overflow-y-auto mb-4">
                            <?php foreach ($permissions as $perm) { ?>
                                <div class="flex items-start gap-2">
                                    <i class="fas fa-check-circle text-green-600 mt-0.5 text-sm"></i>
                                    <span class="text-sm text-gray-700"><?php echo str_replace('_', ' ', ucfirst($perm)); ?></span>
                                </div>
                            <?php } ?>
                        </div>
                    <?php } else { ?>
                        <p class="text-sm text-gray-500 italic mb-4"><?php echo trans('no_permissions'); ?></p>
                    <?php } ?>
                </div>

                <!-- Actions -->
                <div class="bg-gray-50 px-4 py-3 flex gap-2">
                    <button onclick="editRole('<?php echo $role; ?>')" class="flex-1 bg-blue-600 text-white px-3 py-2 rounded text-xs font-semibold hover:bg-blue-700 transition flex items-center justify-center gap-1">
                        <i class="fas fa-edit"></i> <span class="hidden sm:inline"><?php echo trans('edit'); ?></span>
                    </button>
                    <?php if (!in_array($role, ['admin', 'client'])) { ?>
                        <button onclick="deleteRole('<?php echo $role; ?>')" class="flex-1 bg-red-600 text-white px-3 py-2 rounded text-xs font-semibold hover:bg-red-700 transition flex items-center justify-center gap-1">
                            <i class="fas fa-trash"></i> <span class="hidden sm:inline"><?php echo trans('delete'); ?></span>
                        </button>
                    <?php } ?>
                </div>
            </div>
        <?php } ?>

        <!-- Create New Role Card -->
        <div onclick="openCreateRoleModal()" class="bg-white rounded-lg shadow overflow-hidden hover:shadow-lg transition border-t-4 border-dashed border-green-500 cursor-pointer flex items-center justify-center min-h-64">
            <div class="text-center p-6">
                <i class="fas fa-plus text-5xl text-green-600 mb-3"></i>
                <p class="text-gray-700 font-semibold"><?php echo trans('create_new_role'); ?></p>
                <p class="text-sm text-gray-500 mt-1"><?php echo trans('add_custom_role'); ?></p>
            </div>
        </div>
    </div>

    <!-- Permission Matrix View -->
    <div class="mt-8 bg-white rounded-lg shadow p-4 sm:p-6">
        <h2 class="text-xl font-bold text-gray-800 mb-4 flex items-center">
            <i class="fas fa-table text-blue-600 mr-3"></i><?php echo trans('permission_matrix'); ?>
        </h2>
        
        <div class="overflow-x-auto">
            <table class="w-full text-sm">
                <thead class="bg-gray-100 border-b border-gray-200">
                    <tr>
                        <th class="px-4 py-3 text-left font-semibold text-gray-700"><?php echo trans('permission'); ?></th>
                        <?php foreach ($predefinedRoles as $role) { ?>
                            <th class="px-4 py-3 text-center font-semibold text-gray-700"><?php echo ucfirst($role); ?></th>
                        <?php } ?>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($allPermissions as $perm) { ?>
                        <tr class="border-b border-gray-200 hover:bg-gray-50">
                            <td class="px-4 py-3 font-medium text-gray-700">
                                <?php echo str_replace('_', ' ', ucfirst($perm)); ?>
                            </td>
                            <?php foreach ($predefinedRoles as $role) { 
                                $config = $rolesConfig[$role] ?? [];
                                $permissions = $config['permissions'] ?? [];
                                $hasPermission = in_array($perm, $permissions);
                            ?>
                                <td class="px-4 py-3 text-center">
                                    <?php if ($hasPermission) { ?>
                                        <span class="inline-block bg-green-100 text-green-700 px-2 py-1 rounded text-xs font-semibold">
                                            <i class="fas fa-check"></i>
                                        </span>
                                    <?php } else { ?>
                                        <span class="inline-block bg-gray-100 text-gray-400 px-2 py-1 rounded text-xs">
                                            <i class="fas fa-minus"></i>
                                        </span>
                                    <?php } ?>
                                </td>
                            <?php } ?>
                        </tr>
                    <?php } ?>
                </tbody>
            </table>
        </div>
    </div>
    </div>

    <!-- Users Tab Content -->
    <div class="tab-content hidden" id="users-content">
        <div class="bg-white rounded-lg shadow p-6">
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-xl font-bold text-gray-800">
                    <i class="fas fa-users text-blue-600 mr-2"></i><?php echo trans('manage_users') ?? 'Manage Users'; ?>
                </h2>
                <button onclick="openAddUserModal()" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition font-semibold flex items-center gap-2">
                    <i class="fas fa-plus"></i><?php echo trans('add_user') ?? 'Add User'; ?>
                </button>
            </div>

            <!-- Users List Table -->
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead class="bg-gray-50 border-b border-gray-200">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase"><?php echo trans('name'); ?></th>
                            <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase"><?php echo trans('email'); ?></th>
                            <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase"><?php echo trans('role'); ?></th>
                            <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase"><?php echo trans('status'); ?></th>
                            <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase"><?php echo trans('created_at') ?? 'Created'; ?></th>
                            <th class="px-6 py-3 text-center text-xs font-semibold text-gray-700 uppercase"><?php echo trans('actions'); ?></th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-200" id="usersTableBody">
                        <tr>
                            <td colspan="6" class="px-6 py-8 text-center text-gray-500">
                                <i class="fas fa-spinner fa-spin text-2xl"></i> <?php echo trans('loading') ?? 'Loading...'; ?>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Add/Edit User Modal -->
<div id="userModal" class="fixed inset-0 bg-black bg-opacity-50 hidden flex items-center justify-center p-4 z-50 overflow-y-auto">
    <div class="bg-white rounded-lg shadow-lg max-w-2xl w-full my-8 animate__animated animate__slideInDown">
        <div class="flex justify-between items-center p-6 border-b border-gray-200 sticky top-0 bg-white">
            <h2 class="text-xl font-bold text-gray-800" id="userModalTitle"><?php echo trans('add_user'); ?></h2>
            <button onclick="closeUserModal()" class="text-gray-500 hover:text-gray-700 text-2xl">×</button>
        </div>

        <form id="userForm" class="p-6 space-y-4 max-h-96 overflow-y-auto">
            <input type="hidden" name="id" id="userId">

            <!-- Photo Upload -->
            <div class="border-2 border-dashed border-gray-300 rounded-lg p-4 text-center cursor-pointer hover:border-blue-500 transition" onclick="document.getElementById('photoInput').click()">
                <div id="photoPreview" class="hidden">
                    <img id="photoImg" src="" alt="Photo" class="h-32 w-32 mx-auto object-cover rounded-lg mb-2">
                </div>
                <div id="photoPlaceholder">
                    <i class="fas fa-cloud-upload-alt text-3xl text-gray-400 mb-2"></i>
                    <p class="text-gray-600 font-semibold"><?php echo trans('upload_photo') ?? 'Click to upload photo'; ?></p>
                    <p class="text-xs text-gray-500"><?php echo trans('image_formats') ?? 'PNG, JPG, GIF up to 5MB'; ?></p>
                </div>
                <input type="file" id="photoInput" name="photo" class="hidden" accept="image/*" onchange="previewPhoto(this)">
            </div>

            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-gray-700 font-semibold mb-2">
                        <i class="fas fa-user text-blue-600 mr-2"></i><?php echo trans('name'); ?> *
                    </label>
                    <input type="text" name="name" id="userName" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500" required>
                </div>

                <div>
                    <label class="block text-gray-700 font-semibold mb-2">
                        <i class="fas fa-id-badge text-blue-600 mr-2"></i><?php echo trans('role'); ?> *
                    </label>
                    <select name="role" id="userRole" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500" required>
                        <option value="">Select Role</option>
                        <option value="admin"><?php echo trans('admin'); ?></option>
                        <option value="manager"><?php echo trans('manager'); ?></option>
                        <option value="controller"><?php echo trans('controller'); ?></option>
                        <option value="guard"><?php echo trans('guard'); ?></option>
                        <option value="client"><?php echo trans('client'); ?></option>
                    </select>
                </div>
            </div>

            <div>
                <label class="block text-gray-700 font-semibold mb-2">
                    <i class="fas fa-envelope text-blue-600 mr-2"></i><?php echo trans('email'); ?> *
                </label>
                <input type="email" name="email" id="userEmail" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500" required>
            </div>

            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-gray-700 font-semibold mb-2">
                        <i class="fas fa-phone text-blue-600 mr-2"></i><?php echo trans('phone'); ?>
                    </label>
                    <input type="text" name="phone" id="userPhone" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500" placeholder="+237...">
                </div>

                <div>
                    <label class="block text-gray-700 font-semibold mb-2">
                        <i class="fab fa-whatsapp text-green-600 mr-2"></i><?php echo trans('whatsapp'); ?>
                    </label>
                    <input type="text" name="whatsapp" id="userWhatsapp" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500" placeholder="+237...">
                </div>
            </div>

            <div>
                <label class="block text-gray-700 font-semibold mb-2">
                    <i class="fas fa-map-marker-alt text-blue-600 mr-2"></i><?php echo trans('address'); ?>
                </label>
                <textarea name="address" id="userAddress" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500" rows="2" placeholder="Street address..."></textarea>
            </div>

            <div>
                <label class="flex items-center gap-3 cursor-pointer p-2 hover:bg-gray-50 rounded transition">
                    <input type="checkbox" name="active" id="userActive" class="w-5 h-5 rounded border-gray-300" checked>
                    <span class="text-gray-700 font-semibold"><i class="fas fa-check-circle text-green-600 mr-2"></i><?php echo trans('active'); ?></span>
                </label>
            </div>

            <div class="flex gap-3 pt-4 border-t border-gray-200">
                <button type="submit" class="flex-1 bg-blue-600 text-white py-2 rounded-lg hover:bg-blue-700 transition font-semibold flex items-center justify-center gap-2">
                    <i class="fas fa-save"></i><?php echo trans('save'); ?>
                </button>
                <button type="button" onclick="closeUserModal()" class="flex-1 bg-gray-300 text-gray-700 py-2 rounded-lg hover:bg-gray-400 transition font-semibold">
                    <?php echo trans('cancel'); ?>
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Edit Role Modal -->
<div id="editRoleModal" class="fixed inset-0 bg-black bg-opacity-50 hidden flex items-center justify-center p-4 z-50">
    <div class="bg-white rounded-lg shadow-lg max-w-2xl w-full max-h-96 overflow-y-auto animate__animated animate__slideInDown">
        <div class="flex justify-between items-center p-6 border-b border-gray-200 sticky top-0 bg-white">
            <h2 class="text-xl font-bold text-gray-800"><?php echo trans('edit_role'); ?></h2>
            <button onclick="closeEditRoleModal()" class="text-gray-500 hover:text-gray-700 text-2xl">×</button>
        </div>

        <form id="editRoleForm" class="p-6 space-y-4">
            <input type="hidden" name="role" id="editRoleName">

            <div>
                <h3 class="text-lg font-semibold text-gray-800 mb-4">
                    <i class="fas fa-lock text-blue-600 mr-2"></i><?php echo trans('select_permissions'); ?>
                </h3>
                
                <div class="space-y-2 max-h-64 overflow-y-auto">
                    <?php foreach ($allPermissions as $perm) { ?>
                        <label class="flex items-center gap-3 cursor-pointer hover:bg-gray-50 p-2 rounded transition">
                            <input type="checkbox" name="permissions[]" value="<?php echo $perm; ?>" class="w-5 h-5 rounded border-gray-300">
                            <span class="text-gray-700"><?php echo str_replace('_', ' ', ucfirst($perm)); ?></span>
                        </label>
                    <?php } ?>
                </div>
            </div>

            <div class="flex gap-3 pt-4 border-t border-gray-200">
                <button type="submit" class="flex-1 bg-blue-600 text-white py-2 rounded-lg hover:bg-blue-700 transition font-semibold">
                    <?php echo trans('save_changes'); ?>
                </button>
                <button type="button" onclick="closeEditRoleModal()" class="flex-1 bg-gray-300 text-gray-700 py-2 rounded-lg hover:bg-gray-400 transition font-semibold">
                    <?php echo trans('cancel'); ?>
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Create Role Modal -->
<div id="createRoleModal" class="fixed inset-0 bg-black bg-opacity-50 hidden flex items-center justify-center p-4 z-50">
    <div class="bg-white rounded-lg shadow-lg max-w-md w-full animate__animated animate__slideInDown">
        <div class="flex justify-between items-center p-6 border-b border-gray-200">
            <h2 class="text-xl font-bold text-gray-800"><?php echo trans('create_new_role'); ?></h2>
            <button onclick="closeCreateRoleModal()" class="text-gray-500 hover:text-gray-700 text-2xl">×</button>
        </div>

        <form id="createRoleForm" class="p-6 space-y-4">
            <div>
                <label class="block text-gray-700 font-semibold mb-2">
                    <i class="fas fa-tag text-blue-600 mr-2"></i><?php echo trans('role_name'); ?>
                </label>
                <input type="text" name="name" id="roleName" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500" 
                       placeholder="e.g., supervisor" required>
                <p class="text-xs text-gray-500 mt-1"><?php echo trans('role_name_lowercase'); ?></p>
            </div>

            <div>
                <label class="block text-gray-700 font-semibold mb-2">
                    <i class="fas fa-align-left text-blue-600 mr-2"></i><?php echo trans('description'); ?>
                </label>
                <textarea name="description" id="roleDescription" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500" 
                          rows="3" placeholder="Brief description of this role" required></textarea>
            </div>

            <div class="flex gap-3">
                <button type="submit" class="flex-1 bg-green-600 text-white py-2 rounded-lg hover:bg-green-700 transition font-semibold">
                    <?php echo trans('create'); ?>
                </button>
                <button type="button" onclick="closeCreateRoleModal()" class="flex-1 bg-gray-300 text-gray-700 py-2 rounded-lg hover:bg-gray-400 transition font-semibold">
                    <?php echo trans('cancel'); ?>
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Photo Cropper Modal -->
<div id="photoClipperModal" class="fixed inset-0 bg-black bg-opacity-50 hidden flex items-center justify-center p-4 z-50 overflow-y-auto">
    <div class="bg-white rounded-lg shadow-lg max-w-2xl w-full my-8 animate__animated animate__slideInDown">
        <div class="flex justify-between items-center p-6 border-b border-gray-200 sticky top-0 bg-white">
            <h2 class="text-xl font-bold text-gray-800"><?php echo trans('crop_image'); ?></h2>
            <button onclick="cancelCropping()" class="text-gray-500 hover:text-gray-700 text-2xl">×</button>
        </div>

        <div class="p-6">
            <div class="mb-4" style="max-height: 500px; overflow: auto;">
                <img id="cropperImg" src="" alt="Image for cropping" style="max-width: 100%; display: block;">
            </div>

            <div class="flex gap-3">
                <button type="button" onclick="cropAndSavePhoto()" class="flex-1 bg-blue-600 text-white py-2 rounded-lg hover:bg-blue-700 transition font-semibold flex items-center justify-center gap-2">
                    <i class="fas fa-check"></i><?php echo trans('crop_and_save'); ?>
                </button>
                <button type="button" onclick="cancelCropping()" class="flex-1 bg-gray-300 text-gray-700 py-2 rounded-lg hover:bg-gray-400 transition font-semibold">
                    <?php echo trans('cancel'); ?>
                </button>
            </div>
        </div>
    </div>
</div>

<script>
function editRole(role) {
    const rolesConfig = <?php echo json_encode($rolesConfig); ?>;
    const config = rolesConfig[role] || {};
    const permissions = config.permissions || [];

    document.getElementById('editRoleName').value = role;
    
    // Uncheck all
    document.querySelectorAll('#editRoleForm input[type="checkbox"]').forEach(cb => cb.checked = false);
    
    // Check selected permissions
    permissions.forEach(perm => {
        const checkbox = document.querySelector(`#editRoleForm input[value="${perm}"]`);
        if (checkbox) checkbox.checked = true;
    });

    document.getElementById('editRoleModal').classList.remove('hidden');
}

function closeEditRoleModal() {
    document.getElementById('editRoleModal').classList.add('hidden');
}

function openCreateRoleModal() {
    document.getElementById('createRoleForm').reset();
    document.getElementById('createRoleModal').classList.remove('hidden');
}

function closeCreateRoleModal() {
    document.getElementById('createRoleModal').classList.add('hidden');
}

function deleteRole(role) {
    Swal.fire({
        title: '<?php echo trans('delete_role'); ?>?',
        text: '<?php echo trans('delete_role_confirm'); ?>',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#ef4444',
        cancelButtonColor: '#3b82f6',
        confirmButtonText: '<?php echo trans('yes_delete'); ?>'
    }).then((result) => {
        if (result.isConfirmed) {
            // TODO: Make API call to delete role
            Swal.fire('<?php echo trans('success'); ?>', '<?php echo trans('role_deleted'); ?>', 'success');
        }
    });
}

// Form submissions
document.getElementById('editRoleForm')?.addEventListener('submit', function(e) {
    e.preventDefault();
    // TODO: Submit form to API
});

document.getElementById('createRoleForm')?.addEventListener('submit', function(e) {
    e.preventDefault();
    // TODO: Submit form to API
});

// Global cropper instance
let cropper = null;

// Photo Preview Function with Cropping
function previewPhoto(input) {
    const file = input.files[0];
    if (!file) return;

    // Validate file size (5MB max)
    if (file.size > 5 * 1024 * 1024) {
        Swal.fire('<?php echo trans('error'); ?>', '<?php echo trans('file_too_large'); ?> (Max 5MB)', 'error');
        input.value = '';
        return;
    }

    // Validate file type
    if (!file.type.startsWith('image/')) {
        Swal.fire('<?php echo trans('error'); ?>', '<?php echo trans('invalid_file_type'); ?>', 'error');
        input.value = '';
        return;
    }

    const reader = new FileReader();
    reader.onload = function(e) {
        // Show cropper modal
        const cropperModal = document.getElementById('photoClipperModal');
        if (cropperModal) {
            const cropperImg = document.getElementById('cropperImg');
            cropperImg.src = e.target.result;
            cropperModal.classList.remove('hidden');
            
            // Initialize cropper if not already done
            if (cropper) {
                cropper.destroy();
            }
            
            cropper = new Cropper(cropperImg, {
                aspectRatio: 1,
                viewMode: 1,
                autoCropArea: 0.8,
                responsive: true,
                guides: true,
                highlight: true,
                cropBoxMovable: true,
                cropBoxResizable: true,
                toggleDragModeOnDblclick: true,
            });
        } else {
            // Fallback if no cropper modal exists
            document.getElementById('photoImg').src = e.target.result;
            document.getElementById('photoPreview').classList.remove('hidden');
            document.getElementById('photoPlaceholder').classList.add('hidden');
        }
    };
    reader.readAsDataURL(file);
}

// Crop and save image
function cropAndSavePhoto() {
    if (!cropper) return;
    
    const canvas = cropper.getCroppedCanvas({
        maxWidth: 4096,
        maxHeight: 4096,
        fillColor: '#fff',
        imageSmoothingEnabled: true,
        imageSmoothingQuality: 'high',
    });
    
    // Convert canvas to blob and update preview
    canvas.toBlob((blob) => {
        // Update the file input with the new blob
        const dataTransfer = new DataTransfer();
        const file = new File([blob], 'cropped-photo.png', { type: 'image/png' });
        dataTransfer.items.add(file);
        document.getElementById('photoInput').files = dataTransfer.files;
        
        // Show preview
        document.getElementById('photoImg').src = canvas.toDataURL();
        document.getElementById('photoPreview').classList.remove('hidden');
        document.getElementById('photoPlaceholder').classList.add('hidden');
        
        // Close cropper modal
        document.getElementById('photoClipperModal').classList.add('hidden');
        if (cropper) {
            cropper.destroy();
            cropper = null;
        }
    });
}

// Cancel cropping
function cancelCropping() {
    document.getElementById('photoClipperModal').classList.add('hidden');
    document.getElementById('photoInput').value = '';
    if (cropper) {
        cropper.destroy();
        cropper = null;
    }
}

// Tab switching functionality
document.querySelectorAll('.tab-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        const tabName = this.getAttribute('data-tab');
        
        // Remove active state from all buttons
        document.querySelectorAll('.tab-btn').forEach(b => {
            b.classList.add('text-gray-600', 'hover:text-gray-900');
            b.classList.remove('text-blue-600', 'border-b-2', 'border-blue-600');
        });
        
        // Add active state to clicked button
        this.classList.remove('text-gray-600', 'hover:text-gray-900');
        this.classList.add('text-blue-600', 'border-b-2', 'border-blue-600');
        
        // Hide all tab contents
        document.querySelectorAll('.tab-content').forEach(content => {
            content.classList.add('hidden');
        });
        
        // Show selected tab content
        const tabContent = document.getElementById(tabName + '-content');
        if (tabContent) {
            tabContent.classList.remove('hidden');
            
            // Load users if users tab is opened
            if (tabName === 'users') {
                loadUsers();
            }
        }
    });
});

// User Management Functions
function openAddUserModal() {
    document.getElementById('userId').value = '';
    document.getElementById('userForm').reset();
    document.getElementById('userModalTitle').textContent = '<?php echo trans('add_user'); ?>';
    document.getElementById('userModal').classList.remove('hidden');
}

function closeUserModal() {
    document.getElementById('userModal').classList.add('hidden');
}

function editUser(userId) {
    // Fetch user data and populate form
    fetch(`?page=api&endpoint=users/get&id=${userId}`)
        .then(r => r.json())
        .then(data => {
            if (data.user) {
                document.getElementById('userId').value = data.user.id;
                document.getElementById('userName').value = data.user.name;
                document.getElementById('userEmail').value = data.user.email;
                document.getElementById('userRole').value = data.user.role;
                document.getElementById('userPhone').value = data.user.phone || '';
                document.getElementById('userWhatsapp').value = data.user.whatsapp || '';
                document.getElementById('userAddress').value = data.user.address || '';
                document.getElementById('userActive').checked = data.user.active == 1;
                
                // Load photo if exists
                if (data.user.photo) {
                    document.getElementById('photoImg').src = data.user.photo;
                    document.getElementById('photoPreview').classList.remove('hidden');
                    document.getElementById('photoPlaceholder').classList.add('hidden');
                } else {
                    document.getElementById('photoPreview').classList.add('hidden');
                    document.getElementById('photoPlaceholder').classList.remove('hidden');
                }
                
                document.getElementById('userModalTitle').textContent = '<?php echo trans('edit_user'); ?>';
                document.getElementById('userModal').classList.remove('hidden');
            }
        })
        .catch(err => Swal.fire('<?php echo trans('error'); ?>', '<?php echo trans('error_loading_user'); ?>', 'error'));
}

function deleteUser(userId, userName) {
    Swal.fire({
        title: '<?php echo trans('delete_user'); ?>?',
        html: '<?php echo trans('delete_user_confirm'); ?> <strong>' + userName + '</strong>?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#ef4444',
        cancelButtonColor: '#3b82f6',
        confirmButtonText: '<?php echo trans('yes_delete'); ?>'
    }).then((result) => {
        if (result.isConfirmed) {
            fetch(`?page=api&endpoint=users/delete`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ id: userId })
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    Swal.fire('<?php echo trans('success'); ?>', '<?php echo trans('user_deleted'); ?>', 'success');
                    loadUsers();
                } else {
                    Swal.fire('<?php echo trans('error'); ?>', data.message || '<?php echo trans('error_deleting_user'); ?>', 'error');
                }
            })
            .catch(err => Swal.fire('<?php echo trans('error'); ?>', '<?php echo trans('error_deleting_user'); ?>', 'error'));
        }
    });
}

function loadUsers() {
    const tbody = document.getElementById('usersTableBody');
    
    fetch('?page=api&endpoint=users/list')
        .then(r => r.json())
        .then(data => {
            if (!data.users || data.users.length === 0) {
                tbody.innerHTML = '<tr><td colspan="6" class="px-6 py-8 text-center text-gray-500"><?php echo trans('no_users'); ?></td></tr>';
                return;
            }
            
            tbody.innerHTML = data.users.map(user => `
                <tr class="hover:bg-gray-50 transition">
                    <td class="px-6 py-4 text-gray-900">${user.name}</td>
                    <td class="px-6 py-4 text-gray-600">${user.email}</td>
                    <td class="px-6 py-4">
                        <span class="px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm font-semibold">
                            ${user.role || 'N/A'}
                        </span>
                    </td>
                    <td class="px-6 py-4">
                        ${user.active == 1 
                            ? '<span class="px-3 py-1 bg-green-100 text-green-800 rounded-full text-sm font-semibold"><?php echo trans('active'); ?></span>' 
                            : '<span class="px-3 py-1 bg-gray-100 text-gray-800 rounded-full text-sm font-semibold"><?php echo trans('inactive'); ?></span>'
                        }
                    </td>
                    <td class="px-6 py-4 text-gray-600 text-sm">${new Date(user.created_at).toLocaleDateString()}</td>
                    <td class="px-6 py-4 text-center">
                        <div class="flex justify-center gap-2">
                            <button onclick="editUser(${user.id})" class="text-blue-600 hover:text-blue-900 font-semibold transition" title="Edit">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button onclick="deleteUser(${user.id}, '${user.name.replace(/'/g, "\\'")}') class="text-red-600 hover:text-red-900 font-semibold transition" title="Delete">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </td>
                </tr>
            `).join('');
        })
        .catch(err => {
            console.error('Error loading users:', err);
            tbody.innerHTML = '<tr><td colspan="6" class="px-6 py-8 text-center text-red-600"><i class="fas fa-exclamation-circle mr-2"></i><?php echo trans('error_loading_users'); ?></td></tr>';
        });
}

// User form submission
document.getElementById('userForm')?.addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const userId = formData.get('id');
    const isEdit = userId && userId.length > 0;
    const photoFile = document.getElementById('photoInput').files[0];
    
    // If there's a photo file, we need to use FormData for multipart upload
    if (photoFile) {
        const uploadFormData = new FormData();
        uploadFormData.append('id', userId || '');
        uploadFormData.append('name', formData.get('name'));
        uploadFormData.append('email', formData.get('email'));
        uploadFormData.append('role', formData.get('role'));
        uploadFormData.append('phone', formData.get('phone'));
        uploadFormData.append('whatsapp', formData.get('whatsapp'));
        uploadFormData.append('address', formData.get('address'));
        uploadFormData.append('active', formData.get('active') ? 1 : 0);
        uploadFormData.append('photo', photoFile);
        
        const endpoint = isEdit ? `users/update&id=${userId}` : 'users/create';
        
        fetch(`?page=api&endpoint=${endpoint}`, {
            method: 'POST',
            body: uploadFormData
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                Swal.fire('<?php echo trans('success'); ?>', 
                    isEdit ? '<?php echo trans('user_updated'); ?>' : '<?php echo trans('user_created'); ?>', 
                    'success');
                closeUserModal();
                loadUsers();
            } else {
                Swal.fire('<?php echo trans('error'); ?>', data.message || '<?php echo trans('error_saving_user'); ?>', 'error');
            }
        })
        .catch(err => {
            console.error('Error saving user:', err);
            Swal.fire('<?php echo trans('error'); ?>', '<?php echo trans('error_saving_user'); ?>', 'error');
        });
    } else {
        // No photo file, use JSON payload
        const payload = {
            id: userId || '',
            name: formData.get('name'),
            email: formData.get('email'),
            role: formData.get('role'),
            phone: formData.get('phone'),
            whatsapp: formData.get('whatsapp'),
            address: formData.get('address'),
            active: formData.get('active') ? 1 : 0
        };
        
        const endpoint = isEdit ? `users/update&id=${userId}` : 'users/create';
        
        fetch(`?page=api&endpoint=${endpoint}`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                Swal.fire('<?php echo trans('success'); ?>', 
                    isEdit ? '<?php echo trans('user_updated'); ?>' : '<?php echo trans('user_created'); ?>', 
                    'success');
                closeUserModal();
                loadUsers();
            } else {
                Swal.fire('<?php echo trans('error'); ?>', data.message || '<?php echo trans('error_saving_user'); ?>', 'error');
            }
        })
        .catch(err => {
            console.error('Error saving user:', err);
            Swal.fire('<?php echo trans('error'); ?>', '<?php echo trans('error_saving_user'); ?>', 'error');
        });
    }
});
</script>

<!-- Cropper.js Library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.13/cropper.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.13/cropper.min.css">

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