<?php
$groups = $groups ?? [];
$old = $oldInput ?? [];
?>

<div class="page-header">
    <h1 class="page-title">Add Server</h1>
    <p class="page-subtitle">Register a new Linux server</p>
</div>

<div class="card">
    <div class="card-body">
        <form method="POST" action="/servers/create" class="form" id="serverForm">
            <input type="hidden" name="_csrf_token" value="<?= $this->csrfToken() ?>">

            <div class="form-section">
                <h3><i class="fas fa-info-circle"></i> General Information</h3>
                <div class="form-row">
                    <div class="form-group">
                        <label for="name">Server Name *</label>
                        <input type="text" id="name" name="name" class="form-input"
                               placeholder="e.g., Production Web Server" required
                               value="<?= htmlspecialchars($old['name'] ?? '') ?>">
                    </div>
                    <div class="form-group">
                        <label for="group_name">Group / Category</label>
                        <input type="text" id="group_name" name="group_name" class="form-input"
                               placeholder="e.g., Production, Staging"
                               list="groupList"                                value="<?= htmlspecialchars($old['group_name'] ?? '') ?>">
                        <datalist id="groupList">
                            <?php foreach ($groups as $group): ?>
                                <option value="<?= htmlspecialchars($group) ?>">
                            <?php endforeach; ?>
                        </datalist>
                    </div>
                </div>
                <div class="form-group">
                    <label for="description">Description</label>
                    <textarea id="description" name="description" class="form-input" rows="3"
                              placeholder="Optional description of the server"><?= htmlspecialchars($old['description'] ?? '') ?></textarea>
                </div>
            </div>

            <div class="form-section">
                <h3><i class="fas fa-plug"></i> Connection Details</h3>
                <div class="form-row form-row-3">
                    <div class="form-group">
                        <label for="ip_address">IP Address / Hostname *</label>
                        <input type="text" id="ip_address" name="ip_address" class="form-input"
                               placeholder="e.g., 192.168.1.100 or server.example.com" required
                               value="<?= htmlspecialchars($old['ip_address'] ?? '') ?>">
                    </div>
                    <div class="form-group">
                        <label for="ssh_port">SSH Port *</label>
                        <input type="number" id="ssh_port" name="ssh_port" class="form-input"
                               value="<?= htmlspecialchars($old['ssh_port'] ?? '22') ?>" min="1" max="65535" required>
                    </div>
                    <div class="form-group">
                        <label for="ssh_user">SSH User *</label>
                        <input type="text" id="ssh_user" name="ssh_user" class="form-input"
                               placeholder="e.g., root or admin" required
                               value="<?= htmlspecialchars($old['ssh_user'] ?? '') ?>">
                    </div>
                </div>
            </div>

            <div class="form-section">
                <h3><i class="fas fa-key"></i> Authentication</h3>
                <div class="auth-method-tabs">
                    <button type="button" class="tab active" data-method="password">Password</button>
                    <button type="button" class="tab" data-method="key">Private Key</button>
                </div>
                <div class="auth-method-content" id="passwordMethod">
                    <div class="form-group">
                        <label for="ssh_password">SSH Password</label>
                        <div class="input-group">
                            <input type="password" id="ssh_password" name="ssh_password" class="form-input"
                                   placeholder="Leave blank if using key-based auth">
                            <button type="button" class="input-toggle-password" tabindex="-1">
                                <i class="fas fa-eye"></i>
                            </button>
                        </div>
                        <small class="form-hint">Credentials are encrypted with AES-256 before storage.</small>
                    </div>
                </div>
                <div class="auth-method-content" id="keyMethod" style="display: none;">
                    <div class="form-group">
                        <label for="ssh_key">SSH Private Key</label>
                                <textarea id="ssh_key" name="ssh_key" class="form-input font-mono" rows="6"
                                  placeholder="Paste the private key content (RSA/Ed25519)"></textarea>
                        <small class="form-hint">Private key is encrypted before storage. Passphrase-protected keys supported.</small>
                    </div>
                </div>
            </div>

            <div class="form-section">
                <h3><i class="fas fa-shield-alt"></i> Required Permissions</h3>
                <p class="form-hint">The system will connect to the remote server and verify each permission before saving.</p>

                <div id="permissions-container">
                    <?php
                    $savedPerms = $old['permissions'] ?? [];
                    if (!empty($savedPerms) && is_array($savedPerms)):
                        foreach ($savedPerms as $i => $perm):
                    ?>
                    <div class="permission-row" data-index="<?= $i ?>">
                        <select name="permissions[<?= $i ?>][type]" class="form-input permission-type">
                            <option value="sudo" <?= ($perm['type'] ?? '') === 'sudo' ? 'selected' : '' ?>>Sudo (passwordless)</option>
                            <option value="command" <?= ($perm['type'] ?? '') === 'command' ? 'selected' : '' ?>>Command</option>
                            <option value="file_read" <?= ($perm['type'] ?? '') === 'file_read' ? 'selected' : '' ?>>File Read</option>
                            <option value="file_write" <?= ($perm['type'] ?? '') === 'file_write' ? 'selected' : '' ?>>File Write</option>
                            <option value="custom" <?= ($perm['type'] ?? '') === 'custom' ? 'selected' : '' ?>>Custom Command</option>
                        </select>
                        <input type="text" name="permissions[<?= $i ?>][value]" class="form-input permission-value"
                               placeholder="e.g., systemctl" value="<?= htmlspecialchars($perm['value'] ?? '') ?>">
                        <input type="text" name="permissions[<?= $i ?>][description]" class="form-input permission-desc"
                               placeholder="Description (optional)" value="<?= htmlspecialchars($perm['description'] ?? '') ?>">
                        <button type="button" class="btn btn-danger btn-sm" onclick="removePermissionRow(this)"><i class="fas fa-times"></i></button>
                    </div>
                    <?php
                        endforeach;
                    endif;
                    ?>
                </div>

                <div class="permission-actions">
                    <button type="button" id="addPermissionBtn" class="btn btn-secondary">
                        <i class="fas fa-plus"></i> Add Permission
                    </button>
                </div>

                <div class="permission-presets">
                    <span class="preset-label">Quick add:</span>
                    <button type="button" class="btn btn-xs btn-outline" onclick="addPresetPermission('sudo', 'sudo -n true', 'Passwordless sudo for system management')">Sudo</button>
                    <button type="button" class="btn btn-xs btn-outline" onclick="addPresetPermission('command', 'systemctl', 'Service management')">systemctl</button>
                    <button type="button" class="btn btn-xs btn-outline" onclick="addPresetPermission('command', 'df', 'Disk usage monitoring')">df</button>
                    <button type="button" class="btn btn-xs btn-outline" onclick="addPresetPermission('command', 'free', 'Memory monitoring')">free</button>
                    <button type="button" class="btn btn-xs btn-outline" onclick="addPresetPermission('command', 'top', 'CPU monitoring')">top</button>
                </div>
            </div>

            <div class="form-section">
                <div class="form-group">
                    <label class="checkbox-label">
                        <input type="checkbox" name="is_active" value="1" checked>
                        <span>Server active</span>
                    </label>
                </div>
            </div>

            <div class="form-actions">
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-save"></i> Save Server
                </button>
                <a href="/servers" class="btn btn-secondary">Cancel</a>
            </div>
        </form>
    </div>
</div>

<script>
document.querySelectorAll('.auth-method-tabs .tab').forEach(tab => {
    tab.addEventListener('click', function() {
        document.querySelectorAll('.auth-method-tabs .tab').forEach(t => t.classList.remove('active'));
        this.classList.add('active');
        const method = this.dataset.method;
        document.getElementById('passwordMethod').style.display = method === 'password' ? 'block' : 'none';
        document.getElementById('keyMethod').style.display = method === 'key' ? 'block' : 'none';
    });
});

let permIndex = <?= !empty($savedPerms) && is_array($savedPerms) ? count($savedPerms) : 0 ?>;

function createPermissionRow(type, value, description) {
    const idx = permIndex++;
    const container = document.getElementById('permissions-container');
    const div = document.createElement('div');
    div.className = 'permission-row';
    div.dataset.index = idx;
    div.innerHTML = `
        <select name="permissions[${idx}][type]" class="form-input permission-type">
            <option value="sudo" ${type === 'sudo' ? 'selected' : ''}>Sudo (passwordless)</option>
            <option value="command" ${type === 'command' ? 'selected' : ''}>Command</option>
            <option value="file_read" ${type === 'file_read' ? 'selected' : ''}>File Read</option>
            <option value="file_write" ${type === 'file_write' ? 'selected' : ''}>File Write</option>
            <option value="custom" ${type === 'custom' ? 'selected' : ''}>Custom Command</option>
        </select>
        <input type="text" name="permissions[${idx}][value]" class="form-input permission-value"
               placeholder="e.g., systemctl" value="${escapeHtml(value || '')}">
        <input type="text" name="permissions[${idx}][description]" class="form-input permission-desc"
               placeholder="Description (optional)" value="${escapeHtml(description || '')}">
        <button type="button" class="btn btn-danger btn-sm" onclick="removePermissionRow(this)"><i class="fas fa-times"></i></button>
    `;
    container.appendChild(div);
}

function removePermissionRow(btn) {
    btn.closest('.permission-row').remove();
}

function addPresetPermission(type, value, description) {
    createPermissionRow(type, value, description);
}

document.getElementById('addPermissionBtn').addEventListener('click', function() {
    createPermissionRow('command', '', '');
});

function escapeHtml(str) {
    const div = document.createElement('div');
    div.textContent = str;
    return div.innerHTML;
}
</script>
