<?php
// Check if user is authenticated
if (!defined('AUTH_USER')) {
    header('Location: login.php');
    exit();
}

require_once('/docker/whp/web/libs/pgsqlmgmt.php');
$PgSQLMgmt = new pgsqlmgmt();

$message = '';
$message_type = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'create_database':
                if (!empty($_POST['database_name'])) {
                    $db_name = $_POST['database_name'];
                    if (AUTH_USER !== 'root' && strpos($db_name, AUTH_USER . '_') !== 0) {
                        $db_name = AUTH_USER . '_' . $db_name;
                    }
                    if (!preg_match('/^[a-zA-Z0-9_]+$/', $db_name)) {
                        $message = 'Database name can only contain letters, numbers, and underscores';
                        $message_type = 'danger';
                    } else {
                        // Use the actual PostgreSQL user as owner
                        $pg_owner = (AUTH_USER === 'root' || AUTH_USER === 'whp') ? 'postgres' : AUTH_USER . '_pg';
                        
                        // For non-root users, ensure PostgreSQL user exists
                        if (AUTH_USER !== 'root' && AUTH_USER !== 'whp') {
                            $userExists = $PgSQLMgmt->checkUserExists($pg_owner);
                            if (!$userExists['exists']) {
                                // Create PostgreSQL user if it doesn't exist
                                $pgPassword = bin2hex(random_bytes(12));
                                $createResult = $PgSQLMgmt->createPostgreSQLUserForSSO($pg_owner, $pgPassword);
                                if ($createResult['status'] !== '0') {
                                    $message = 'Error creating PostgreSQL user: ' . $createResult['msg'];
                                    $message_type = 'danger';
                                    break;
                                }
                                // Store password for SSO integration
                                require_once('/docker/whp/web/libs/usermgmt.php');
                                $UserMgmt = new usermgmt();
                                $UserMgmt->setUserPostgreSQLPassword(AUTH_USER, $pgPassword);
                            }
                        }
                        
                        $result = $PgSQLMgmt->createDatabase($db_name, $pg_owner);
                        if ($result['status'] === '0') {
                            $message = 'PostgreSQL database created successfully: ' . $db_name;
                            $message_type = 'success';
                        } else {
                            $message = 'Error creating database: ' . $result['msg'];
                            $message_type = 'danger';
                        }
                    }
                } else {
                    $message = 'Database name is required';
                    $message_type = 'danger';
                }
                break;
            case 'delete_database':
                if (!empty($_POST['database_name'])) {
                    $database_name = $_POST['database_name'];
                    
                    // Check if user has permission to delete this database
                    if (!$PgSQLMgmt->canManageDatabase(AUTH_USER, $database_name)) {
                        $message = 'You do not have permission to delete this database';
                        $message_type = 'danger';
                    } else {
                        $result = $PgSQLMgmt->deleteDatabase($database_name);
                        if ($result['status'] === '0') {
                            $message = 'PostgreSQL database deleted successfully: ' . $database_name;
                            $message_type = 'success';
                        } else {
                            $message = 'Error deleting database: ' . $result['msg'];
                            $message_type = 'danger';
                        }
                    }
                } else {
                    $message = 'Database name is required';
                    $message_type = 'danger';
                }
                break;
            case 'create_database_user':
                if (!empty($_POST['username']) && !empty($_POST['password']) && !empty($_POST['database_name'])) {
                    $db_user = $_POST['username'];
                    $db_name = $_POST['database_name'];
                    if (AUTH_USER !== 'root') {
                        if (strpos($db_user, AUTH_USER . '_') !== 0) {
                            $db_user = AUTH_USER . '_' . $db_user;
                        }
                        if (strpos($db_name, AUTH_USER . '_') !== 0) {
                            $db_name = AUTH_USER . '_' . $db_name;
                        }
                    }
                    if (!preg_match('/^[a-zA-Z0-9_]+$/', $db_user)) {
                        $message = 'Username can only contain letters, numbers, and underscores';
                        $message_type = 'danger';
                    } else {
                        $privileges = isset($_POST['privileges']) ? $_POST['privileges'] : ['ALL'];
                        $result = $PgSQLMgmt->createDatabaseUser($db_user, $_POST['password'], $db_name, $privileges);
                        if ($result['status'] === '0') {
                            $message = 'PostgreSQL database user created successfully: ' . $db_user;
                            $message_type = 'success';
                        } else {
                            $message = 'Error creating database user: ' . $result['msg'];
                            $message_type = 'danger';
                        }
                    }
                } else {
                    $message = 'Username, password, and database name are required';
                    $message_type = 'danger';
                }
                break;
            case 'delete_database_user':
                if (!empty($_POST['username'])) {
                    $target_user = $_POST['username'];
                    
                    // Check if user has permission to delete this database user
                    if (!$PgSQLMgmt->canManageDatabaseUser(AUTH_USER, $target_user)) {
                        $message = 'You do not have permission to delete this database user';
                        $message_type = 'danger';
                    } else {
                        $result = $PgSQLMgmt->deleteDatabaseUser($target_user);
                        if ($result['status'] === '0') {
                            $message = 'PostgreSQL database user deleted successfully: ' . $target_user;
                            $message_type = 'success';
                        } else {
                            $message = 'Error deleting database user: ' . $result['msg'];
                            $message_type = 'danger';
                        }
                    }
                } else {
                    $message = 'Username is required';
                    $message_type = 'danger';
                }
                break;
            case 'update_privileges':
                if (!empty($_POST['username']) && !empty($_POST['database_name']) && isset($_POST['privileges'])) {
                    $result = $PgSQLMgmt->updateDatabaseUserPrivileges($_POST['username'], $_POST['database_name'], $_POST['privileges']);
                    if ($result['status'] === '0') {
                        $message = 'Privileges updated successfully for user: ' . $_POST['username'];
                        $message_type = 'success';
                    } else {
                        $message = 'Error updating privileges: ' . $result['msg'];
                        $message_type = 'danger';
                    }
                } else {
                    $message = 'Username, database name, and privileges are required';
                    $message_type = 'danger';
                }
                break;
        }
    }
}

// Get manageable databases (for display and deletion)
$manageable_databases = [];
$db_result = $PgSQLMgmt->listManageableDatabases(AUTH_USER);
if ($db_result['status'] === '0') {
    $manageable_databases = $db_result['databases'];
}

// Get user's databases for creation form
$user_databases = [];
if (AUTH_USER !== 'root') {
    $db_result = $PgSQLMgmt->listUserDatabases(AUTH_USER);
    if ($db_result['status'] === '0') {
        $user_databases = $db_result['databases'];
    }
}

// Get all databases for root user (for creation form)
$all_databases = [];
if (AUTH_USER === 'root') {
    $db_result = $PgSQLMgmt->listUserDatabases('root');
    if ($db_result['status'] === '0') {
        $all_databases = $db_result['databases'];
    }
}

// Get manageable database users
$manageable_users = [];
$db_users_result = $PgSQLMgmt->listManageableDatabaseUsers(AUTH_USER);
if ($db_users_result['status'] === '0') {
    $manageable_users = $db_users_result['users'];
}
?>
<?php if (!empty($message)): ?>
    <div class="alert alert-<?php echo $message_type; ?>"> <?php echo htmlspecialchars($message); ?> </div>
<?php endif; ?>
<div class="row g-4 mb-5">
    <div class="col-md-6">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="card-title mb-0">PostgreSQL Database Management</h5>
            </div>
            <div class="card-body">
                <!-- Create New Database Section -->
                <div class="mb-4">
                    <h6 class="text-primary mb-3">
                        <i class="fa fa-plus-circle"></i> Create New PostgreSQL Database
                    </h6>
                    <form method="POST" action="">
                        <input type="hidden" name="action" value="create_database">
                        <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                        <div class="mb-3">
                            <label class="form-label">Database Name</label>
                            <div class="input-group">
                                <?php if (AUTH_USER !== 'root'): ?>
                                    <span class="input-group-text"><?php echo AUTH_USER . '_'; ?></span>
                                <?php endif; ?>
                                <input type="text" class="form-control" name="database_name" required pattern="[a-zA-Z0-9_]+">
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary">Create Database</button>
                    </form>
                </div>
                
                <hr class="my-4">
                
                <!-- Database List Section -->
                <div>
                    <h6 class="text-primary mb-3">
                        <i class="fa fa-database"></i> 
                        <?php if (AUTH_USER === 'root'): ?>
                            All PostgreSQL Databases
                        <?php else: ?>
                            Your PostgreSQL Databases
                        <?php endif; ?>
                    </h6>
                    <?php if (empty($manageable_databases)): ?>
                        <p class="text-muted">No PostgreSQL databases found.</p>
                    <?php else: ?>
                        <div class="mb-3">
                            <label for="databaseSelect" class="form-label">Select Database</label>
                            <select class="form-control" id="databaseSelect">
                                <option value="">-- Choose a database --</option>
                                <?php foreach ($manageable_databases as $db): ?>
                                    <?php if (in_array(strtolower($db), ['postgres', 'template0', 'template1'])) continue; ?>
                                    <option value="<?php echo htmlspecialchars($db); ?>">
                                        <?php echo htmlspecialchars($db); ?>
                                        <?php if (AUTH_USER !== 'root' && strpos($db, AUTH_USER . '_') === 0): ?>
                                            (Your database)
                                        <?php endif; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mt-2">
                            <form id="deleteDatabaseForm" method="POST" action="">
                                <input type="hidden" name="action" value="delete_database">
                                <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                                <input type="hidden" name="database_name" id="deleteDatabaseName">
                                <button id="deleteDatabaseBtn" class="btn btn-danger" style="display:none;" type="submit" onclick="return confirm('Are you sure you want to delete the selected PostgreSQL database? This action cannot be undone.');">
                                    <i class="fa fa-trash"></i> Delete Database
                                </button>
                            </form>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <!-- Adminer Quick Access -->
        <div class="card mb-3">
            <div class="card-body text-center py-3">
                <h6 class="card-title mb-2">
                    <i class="fa fa-database"></i> Adminer
                </h6>
                <a href="adminer-sso.php" class="btn btn-primary btn-sm" target="_blank">
                    <i class="fa fa-external-link"></i> Open Adminer
                </a>
                <p class="text-muted mb-0 mt-2 small">Database management interface</p>
            </div>
        </div>
        
        <div class="card mb-4">
            <div class="card-header"><h5 class="card-title mb-0">Create New PostgreSQL User</h5></div>
            <div class="card-body">
                <form method="POST" action="">
                    <input type="hidden" name="action" value="create_database_user">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                    <div class="mb-3">
                        <label class="form-label">Username</label>
                        <div class="input-group">
                            <?php if (AUTH_USER !== 'root'): ?>
                                <span class="input-group-text"><?php echo AUTH_USER . '_'; ?></span>
                            <?php endif; ?>
                            <input type="text" class="form-control" name="username" required pattern="[a-zA-Z0-9_]+">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Password</label>
                        <div class="input-group">
                            <input type="password" class="form-control" name="password" id="dbUserPassword" required>
                            <button type="button" class="btn btn-outline-secondary" onclick="togglePasswordVisibility()" tabindex="-1" aria-label="Show password">
                                <i class="fa fa-eye" id="passwordToggleIcon"></i>
                            </button>
                        </div>
                        <div class="text-right mt-2">
                            <button type="button" class="btn btn-outline-primary btn-sm" onclick="generatePassword()">
                                <i class="fa fa-magic"></i> Generate Password
                            </button>
                        </div>
                        <div class="form-text text-white">Click "Generate Password" to create a PostgreSQL-compatible password</div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Database</label>
                        <select class="form-select" name="database_name" required>
                            <?php if (AUTH_USER === 'root'): ?>
                                <?php foreach ($all_databases as $db): ?>
                                    <option value="<?php echo htmlspecialchars($db); ?>"><?php echo htmlspecialchars($db); ?></option>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <?php foreach ($user_databases as $db): ?>
                                    <option value="<?php echo htmlspecialchars($db); ?>"><?php echo htmlspecialchars($db); ?></option>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Privileges</label>
                        <div class="row">
                            <div class="col-sm-6">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="privileges[]" value="SELECT" checked id="priv_select">
                                    <label class="form-check-label" for="priv_select">SELECT</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="privileges[]" value="INSERT" checked id="priv_insert">
                                    <label class="form-check-label" for="priv_insert">INSERT</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="privileges[]" value="UPDATE" checked id="priv_update">
                                    <label class="form-check-label" for="priv_update">UPDATE</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="privileges[]" value="DELETE" checked id="priv_delete">
                                    <label class="form-check-label" for="priv_delete">DELETE</label>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="privileges[]" value="CREATE" checked id="priv_create">
                                    <label class="form-check-label" for="priv_create">CREATE</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="privileges[]" value="CONNECT" checked id="priv_connect">
                                    <label class="form-check-label" for="priv_connect">CONNECT</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="privileges[]" value="ALL" id="priv_all">
                                    <label class="form-check-label" for="priv_all">ALL PRIVILEGES</label>
                                </div>
                            </div>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary">Create PostgreSQL User</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Database Users Management Section -->
<?php if (!empty($manageable_users)): ?>
<div class="row mt-5">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <?php if (AUTH_USER === 'root'): ?>
                    All PostgreSQL Users
                    <?php else: ?>
                    Your PostgreSQL Users
                    <?php endif; ?>
                </h5>
            </div>
            <div class="card-body">
                    <!-- Search Controls -->
                    <div class="row mb-3">
                        <div class="col-md-8">
                            <div class="input-group">
                                <span class="input-group-text"><i class="fa fa-search"></i></span>
                                <input type="text" class="form-control" id="pgUserSearchInput" placeholder="Search PostgreSQL users...">
                            </div>
                        </div>
                        <div class="col-md-4 text-end">
                            <small class="text-muted" id="pgUserTableInfo"></small>
                        </div>
                    </div>

                    <div class="table-responsive">
                        <table class="table table-striped table-hover" id="pgUsersTable">
                            <thead class="table-dark">
                                <tr>
                                    <th>Username</th>
                                    <th>Databases</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($manageable_users as $user): ?>
                                <tr>
                                    <td>
                                        <strong><?php echo htmlspecialchars($user['username']); ?></strong>
                                        <?php if (AUTH_USER !== 'root' && strpos($user['username'], AUTH_USER . '_') === 0): ?>
                                        <br><small class="text-muted">Your database user</small>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if (!empty($user['databases'])): ?>
                                            <?php 
                                            $databases = explode(',', $user['databases']);
                                            foreach ($databases as $db) {
                                                echo '<span class="badge bg-info text-dark me-1">' . htmlspecialchars(trim($db)) . '</span> ';
                                            }
                                            ?>
                                        <?php else: ?>
                                            <span class="text-muted">No databases assigned</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <form method="POST" action="" style="display:inline;" onsubmit="return confirm('Are you sure you want to delete the PostgreSQL user \'<?php echo htmlspecialchars($user['username']); ?>\'? This action cannot be undone.');">
                                            <input type="hidden" name="action" value="delete_database_user">
                                            <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                                            <input type="hidden" name="username" value="<?php echo htmlspecialchars($user['username']); ?>">
                                            <button type="submit" class="btn btn-danger btn-sm">
                                                <i class="fa fa-trash"></i> Delete
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- Pagination Controls -->
                    <div class="d-flex justify-content-center mt-3">
                        <nav id="pgUserPagination"></nav>
                    </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<script src="/js/table-pagination.js"></script>
<script>
// Initialize PostgreSQL users pagination
document.addEventListener('DOMContentLoaded', function() {
    const pgUsersTable = document.getElementById('pgUsersTable');
    if (pgUsersTable) {
        new TablePagination({
            tableId: 'pgUsersTable',
            searchId: 'pgUserSearchInput',
            paginationId: 'pgUserPagination',
            infoId: 'pgUserTableInfo',
            itemsPerPage: 25
        });
    }
});
</script>

<style>
/* Fix form-text visibility on dark backgrounds */
.form-text {
    color: #f8f9fa !important;
}

/* Ensure eye icon is visible and maintains styling */
#togglePasswordBtn {
    color: #6c757d !important;
    background-color: #f8f9fa !important;
    border-color: #ced4da !important;
    display: block !important;
    visibility: visible !important;
    opacity: 1 !important;
    width: auto !important;
    height: auto !important;
    min-width: 38px !important;
    min-height: 38px !important;
}

#togglePasswordBtn:hover {
    color: #495057 !important;
    background-color: #e9ecef !important;
    border-color: #adb5bd !important;
}

#togglePasswordBtn:focus {
    color: #495057 !important;
    background-color: #e9ecef !important;
    border-color: #86b7fe !important;
    box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25) !important;
}

/* Ensure the eye icon itself is always visible */
#togglePasswordBtn i {
    display: inline-block !important;
    visibility: visible !important;
    opacity: 1 !important;
    font-size: 14px !important;
}

/* Fix Choices.js dropdown position inside Bootstrap cards/rows */
.choices-container {
    position: static !important;
}
.choices-container .choices__list--dropdown {
    position: absolute !important;
    left: 0 !important;
    right: 0 !important;
    z-index: 9999 !important;
}

/* Fix Choices.js dropdown/input text color for dark themes */
.choices__inner,
.choices__list--dropdown,
.choices__item--selectable,
.choices__input,
.choices__placeholder {
    background-color: #fff !important;
    color: #212529 !important;
}
.choices__list--dropdown .choices__item--selectable.is-highlighted {
    background-color: #e9ecef !important;
    color: #212529 !important;
}
</style>

<!-- Choices.js CSS/JS -->
<link rel="stylesheet" href="/css/choices.min.css">
<script src="/js/choices.min.js"></script>

<script>
// Global functions that need to be accessible from onclick attributes
window.togglePasswordVisibility = function() {
    var input = document.getElementById('dbUserPassword');
    var icon = document.getElementById('passwordToggleIcon');
    if (input && icon) {
        togglePasswordField(input, icon);
    }
};

window.generatePassword = function() {
    // Generate a secure, PostgreSQL-compatible password
    const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*';
    let password = '';
    
    // Ensure at least one character from each required category
    password += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[Math.floor(Math.random() * 26)]; // uppercase
    password += 'abcdefghijklmnopqrstuvwxyz'[Math.floor(Math.random() * 26)]; // lowercase
    password += '0123456789'[Math.floor(Math.random() * 10)]; // number
    password += '!@#$%^&*'[Math.floor(Math.random() * 8)]; // symbol
    
    // Fill the rest randomly
    for (let i = 4; i < 16; i++) {
        password += charset[Math.floor(Math.random() * charset.length)];
    }
    
    // Shuffle the password
    password = password.split('').sort(() => Math.random() - 0.5).join('');
    
    // Set the password
    var input = document.getElementById('dbUserPassword');
    var icon = document.getElementById('passwordToggleIcon');
    
    if (input) {
        input.value = password;
        
        // Show password briefly when generated
        input.type = 'text';
        if (icon) {
            icon.classList.remove('fa-eye');
            icon.classList.add('fa-eye-slash');
        }
        
        // Auto-hide after 10 seconds
        if (window.revealTimer) clearTimeout(window.revealTimer);
        window.revealTimer = setTimeout(function() {
            input.type = 'password';
            if (icon) {
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            }
        }, 10000);
    }
};

// Password generation and visibility toggle
var revealTimer = null;

// Simplified toggle function using Font Awesome icons
function togglePasswordField(input, iconElement) {
    var isVisible = input.type === 'text';
    
    if (isVisible) {
        // Hide password
        input.type = 'password';
        iconElement.classList.remove('fa-eye-slash');
        iconElement.classList.add('fa-eye');
        input.closest('.input-group').querySelector('button').setAttribute('aria-label', 'Show password');
        
        // Clear auto-hide timer
        if (revealTimer) {
            clearTimeout(revealTimer);
            revealTimer = null;
        }
    } else {
        // Show password
        input.type = 'text';
        iconElement.classList.remove('fa-eye');
        iconElement.classList.add('fa-eye-slash');
        input.closest('.input-group').querySelector('button').setAttribute('aria-label', 'Hide password');
        
        // Auto-hide after 10 seconds
        if (revealTimer) clearTimeout(revealTimer);
        revealTimer = setTimeout(function() {
            input.type = 'password';
            iconElement.classList.remove('fa-eye-slash');
            iconElement.classList.add('fa-eye');
            input.closest('.input-group').querySelector('button').setAttribute('aria-label', 'Show password');
        }, 10000);
    }
}

document.addEventListener('DOMContentLoaded', function() {
    // Initialize Choices.js for the database select
    const databaseSelect = document.getElementById('databaseSelect');
    if (databaseSelect) {
        const choices = new Choices(databaseSelect, {
            searchEnabled: true,
            itemSelectText: '',
            shouldSort: false
        });
    }
    var deleteBtn = document.getElementById('deleteDatabaseBtn');
    var deleteDatabaseName = document.getElementById('deleteDatabaseName');
    if (databaseSelect && deleteBtn && deleteDatabaseName) {
        databaseSelect.addEventListener('change', function() {
            if (this.value && this.value !== '') {
                deleteBtn.style.display = 'block';
                deleteDatabaseName.value = this.value;
            } else {
                deleteBtn.style.display = 'none';
                deleteDatabaseName.value = '';
            }
        });
    }
});
</script>