<?php
$isEdit = isset($user) && !empty($user);
$pageTitle = $isEdit ? 'Edit User' : 'Add User';
$breadcrumb = [
    ['label' => 'Users', 'url' => APP_URL . '/users'],
    ['label' => $pageTitle, 'url' => null]
];
ob_start();
?>
<div class="max-w-4xl mx-auto">
    <div class="flex justify-between items-center mb-6">
        <h1 class="text-2xl font-bold text-gray-800"><?= $pageTitle ?></h1>
        <a href="<?= APP_URL ?>/users" class="text-gray-600 hover:text-gray-900">Back to List</a>
    </div>

    <form action="<?= APP_URL ?>/users<?= $isEdit ? '/' . $user['id'] . '/edit' : '/create' ?>" method="POST" class="space-y-6">
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION[CSRF_TOKEN_NAME] ?? '') ?>">

        <!-- Personal Info -->
        <div class="bg-white rounded-lg shadow overflow-hidden">
            <div class="bg-gray-50 px-6 py-4 border-b border-gray-200">
                <h3 class="text-lg leading-6 font-medium text-gray-900">Personal Information</h3>
            </div>
            <div class="p-6 grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label class="block text-sm font-medium text-gray-700">First Name *</label>
                    <input type="text" name="first_name" required value="<?= htmlspecialchars($user['first_name'] ?? '') ?>" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-[#0A3A6B] focus:ring-[#0A3A6B] sm:text-sm border p-2">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">Last Name *</label>
                    <input type="text" name="last_name" required value="<?= htmlspecialchars($user['last_name'] ?? '') ?>" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-[#0A3A6B] focus:ring-[#0A3A6B] sm:text-sm border p-2">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">Email *</label>
                    <input type="email" name="email" required value="<?= htmlspecialchars($user['email'] ?? '') ?>" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-[#0A3A6B] focus:ring-[#0A3A6B] sm:text-sm border p-2">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">Phone</label>
                    <input type="text" name="phone" value="<?= htmlspecialchars($user['phone'] ?? '') ?>" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-[#0A3A6B] focus:ring-[#0A3A6B] sm:text-sm border p-2">
                </div>
                <?php if (!empty($organizations)): ?>
                <div>
                    <label class="block text-sm font-medium text-gray-700">Organization *</label>
                    <select name="org_id" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-[#0A3A6B] focus:ring-[#0A3A6B] sm:text-sm border p-2">
                        <option value="">Select Organization...</option>
                        <?php foreach ($organizations as $org): ?>
                        <option value="<?= $org['id'] ?>" <?= (int)($user['org_id'] ?? 0) === (int)$org['id'] ? 'selected' : '' ?>><?= htmlspecialchars($org['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <p class="mt-1 text-xs text-gray-500">As a platform super-admin, pick which organization this user belongs to.</p>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Entity Type & Roles -->
        <div class="bg-white rounded-lg shadow overflow-hidden">
            <div class="bg-gray-50 px-6 py-4 border-b border-gray-200">
                <h3 class="text-lg leading-6 font-medium text-gray-900">Account Type & Access</h3>
            </div>
            <div class="p-6 space-y-6">
                <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Entity Type *</label>
                        <select name="entity_type" id="entity_type" required class="block w-full rounded-md border-gray-300 shadow-sm focus:border-[#0A3A6B] focus:ring-[#0A3A6B] sm:text-sm border p-2">
                            <option value="org_user" <?= ($user['entity_type'] ?? 'org_user') === 'org_user' ? 'selected' : '' ?>>Organization User</option>
                            <option value="contractor_user" <?= ($user['entity_type'] ?? '') === 'contractor_user' ? 'selected' : '' ?>>Contractor User</option>
                            <option value="supplier_user" <?= ($user['entity_type'] ?? '') === 'supplier_user' ? 'selected' : '' ?>>Supplier User</option>
                        </select>
                    </div>

                    <div id="contractor_select_div" class="<?= ($user['entity_type'] ?? '') === 'contractor_user' ? '' : 'hidden' ?>">
                        <label class="block text-sm font-medium text-gray-700 mb-1">Select Contractor *</label>
                        <select name="contractor_id" id="contractor_id" class="block w-full rounded-md border-gray-300 shadow-sm focus:border-[#0A3A6B] focus:ring-[#0A3A6B] sm:text-sm border p-2">
                            <option value="">Select Contractor...</option>
                            <?php foreach ($contractors ?? [] as $c): ?>
                            <option value="<?= htmlspecialchars($c['id']) ?>" <?= ($user['entity_id'] ?? '') == $c['id'] ? 'selected' : '' ?>><?= htmlspecialchars($c['company_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div id="supplier_select_div" class="<?= ($user['entity_type'] ?? '') === 'supplier_user' ? '' : 'hidden' ?>">
                        <label class="block text-sm font-medium text-gray-700 mb-1">Select Supplier *</label>
                        <select name="supplier_id" id="supplier_id" class="block w-full rounded-md border-gray-300 shadow-sm focus:border-[#0A3A6B] focus:ring-[#0A3A6B] sm:text-sm border p-2">
                            <option value="">Select Supplier...</option>
                            <?php foreach ($suppliers ?? [] as $s): ?>
                            <option value="<?= htmlspecialchars($s['id']) ?>" <?= ($user['entity_id'] ?? '') == $s['id'] ? 'selected' : '' ?>><?= htmlspecialchars($s['company_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-3">Assign Roles</label>
                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                        <?php foreach ($availableRoles ?? [] as $role): ?>
                        <div class="relative flex items-start border border-gray-200 rounded p-3">
                            <div class="flex items-center h-5">
                                <input type="checkbox" name="roles[]" value="<?= htmlspecialchars($role['id']) ?>" <?= in_array($role['id'], $userRoles ?? []) ? 'checked' : '' ?> class="focus:ring-[#0A3A6B] h-4 w-4 text-[#0A3A6B] border-gray-300 rounded">
                            </div>
                            <div class="ml-3 text-sm">
                                <label class="font-medium text-gray-700"><?= htmlspecialchars($role['name']) ?></label>
                                <p class="text-gray-500 text-xs"><?= htmlspecialchars($role['description'] ?? '') ?></p>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>

        <?php if (!$isEdit): ?>
        <!-- Password & Welcome -->
        <div class="bg-white rounded-lg shadow overflow-hidden">
            <div class="bg-gray-50 px-6 py-4 border-b border-gray-200">
                <h3 class="text-lg leading-6 font-medium text-gray-900">Password & Security</h3>
            </div>
            <div class="p-6 space-y-4">
                <div class="flex items-center">
                    <input type="checkbox" id="auto_generate_password" name="auto_generate_password" value="1" checked class="h-4 w-4 text-[#0A3A6B] focus:ring-[#0A3A6B] border-gray-300 rounded">
                    <label for="auto_generate_password" class="ml-2 block text-sm text-gray-900">
                        Auto-generate password
                    </label>
                </div>
                
                <div id="manual_password_div" class="hidden grid grid-cols-1 md:grid-cols-2 gap-6 mt-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700">Password</label>
                        <input type="password" name="password" id="password_input" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-[#0A3A6B] focus:ring-[#0A3A6B] sm:text-sm border p-2">
                    </div>
                </div>

                <div class="flex items-center mt-4">
                    <input type="checkbox" name="send_welcome_email" value="1" checked class="h-4 w-4 text-[#0A3A6B] focus:ring-[#0A3A6B] border-gray-300 rounded">
                    <label class="ml-2 block text-sm text-gray-900">
                        Send welcome email with login instructions
                    </label>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <div class="flex justify-end pt-4">
            <button type="submit" class="bg-[#0A3A6B] hover:bg-blue-700 text-white font-bold py-3 px-8 rounded shadow">
                <?= $isEdit ? 'Save Changes' : 'Add User' ?>
            </button>
        </div>
    </form>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const entityTypeSelect = document.getElementById('entity_type');
    const contractorDiv = document.getElementById('contractor_select_div');
    const supplierDiv = document.getElementById('supplier_select_div');
    
    entityTypeSelect.addEventListener('change', function() {
        contractorDiv.classList.add('hidden');
        supplierDiv.classList.add('hidden');
        if (this.value === 'contractor_user') {
            contractorDiv.classList.remove('hidden');
        } else if (this.value === 'supplier_user') {
            supplierDiv.classList.remove('hidden');
        }
    });

    const autoGenCheck = document.getElementById('auto_generate_password');
    if (autoGenCheck) {
        const manualPassDiv = document.getElementById('manual_password_div');
        autoGenCheck.addEventListener('change', function() {
            if (this.checked) {
                manualPassDiv.classList.add('hidden');
            } else {
                manualPassDiv.classList.remove('hidden');
            }
        });
    }
});
</script>
<?php
$content = ob_get_clean();
require ROOT_PATH . '/modules/shared/views/layouts/main.php';
?>