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

require_once('/docker/whp/web/libs/mysqlmgmt.php');
require_once('/docker/whp/web/libs/database_actions.php');
$MySQLMgmt = new mysqlmgmt();

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

// Handle form submissions. Logic lives in libs/database_actions.php and is
// shared with api/database-ajax.php (async fetch). Non-JS posts re-render here.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $whp_db_result = whp_database_handle_action($MySQLMgmt);
    $message = $whp_db_result['message'];
    $message_type = $whp_db_result['type'];
}

// Get manageable databases (for display and deletion)
$manageable_databases = [];
$db_result = $MySQLMgmt->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 = $MySQLMgmt->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 = $MySQLMgmt->listUserDatabases('root');
    if ($db_result['status'] === '0') {
        $all_databases = $db_result['databases'];
    }
}
// Get system users for database ownership (for root only)
$system_users = [];
if (AUTH_USER === 'root') {
    require_once('/docker/whp/web/libs/usermgmt.php');
    $UserMgmt = new usermgmt();
    $users = $UserMgmt->list_users();
    foreach ($users as $user) {
        if ($user['uid'] >= 1000 && !$user['protected']) {
            $system_users[] = $user['username'];
        }
    }
}

// Get manageable database users
$manageable_users = [];
$db_users_result = $MySQLMgmt->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">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 Database
                    </h6>
                    <form method="POST" action="" data-whp-async data-whp-action="/api/database-ajax.php" data-whp-reset>
                        <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 for="createDbName" 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" id="createDbName" 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 Databases
                        <?php else: ?>
                            Your Databases
                        <?php endif; ?>
                    </h6>
                    <?php if (empty($manageable_databases)): ?>
                        <p class="text-muted">No databases found.</p>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-striped table-hover mb-0" id="dbDatabasesTable" data-whp-table data-whp-page-size="10">
                                <thead><tr><th>Database</th><th class="text-end" data-whp-nosort>Actions</th></tr></thead>
                                <tbody>
                                <?php foreach ($manageable_databases as $db): ?>
                                    <?php if (in_array(strtolower($db), ['whp', 'powerdns', 'phpmyadmin'])) continue; ?>
                                    <tr>
                                        <td>
                                            <code><?php echo htmlspecialchars($db); ?></code>
                                            <?php if (AUTH_USER !== 'root' && strpos($db, AUTH_USER . '_') === 0): ?>
                                                <span class="badge bg-secondary">Your database</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-end">
                                            <form method="POST" action="" style="display:inline;" data-whp-async data-whp-action="/api/database-ajax.php" data-whp-remove-row data-whp-confirm="Delete database '<?php echo htmlspecialchars($db, ENT_QUOTES); ?>'? This action cannot be undone.">
                                                <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" value="<?php echo htmlspecialchars($db); ?>">
                                                <button type="submit" class="btn btn-danger btn-sm" aria-label="Delete database <?php echo htmlspecialchars($db); ?>" title="Delete database <?php echo htmlspecialchars($db); ?>">
                                                    <i class="fa fa-trash" aria-hidden="true"></i>
                                                </button>
                                            </form>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <!-- phpMyAdmin 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 text-success"></i> phpMyAdmin
                </h6>
                <a href="phpmyadmin-sso.php" class="btn btn-success btn-sm" target="_blank">
                    <i class="fa fa-external-link"></i> Open phpMyAdmin
                </a>
                <p class="text-muted mb-0 mt-2 small">Auto-login in new window</p>
            </div>
        </div>
        
        <div class="card mb-4">
            <div class="card-header"><h5 class="card-title mb-0">Create New Database User</h5></div>
            <div class="card-body">
                <form method="POST" action="" data-whp-async data-whp-action="/api/database-ajax.php" data-whp-reset>
                    <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 for="createDbUser" 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" id="createDbUser" name="username" required pattern="[a-zA-Z0-9_]+">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="dbUserPassword" 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 MySQL-compatible password</div>
                    </div>
                    <div class="mb-3">
                        <label for="createDbForUser" class="form-label">Database</label>
                        <select class="form-select" id="createDbForUser" 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 id="createDbPrivilegesLabel" class="form-label">Privileges</label>
                        <div class="row" role="group" aria-labelledby="createDbPrivilegesLabel">
                            <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>
                            <div class="col-sm-6">
                                <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 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 Database 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 Database Users
                    <?php else: ?>
                    Your Database Users
                    <?php endif; ?>
                </h5>
            </div>
            <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped table-hover" id="dbUsersTable" data-whp-table data-whp-page-size="10">
                            <thead class="table-dark">
                                <tr>
                                    <th>Username</th>
                                    <th>Host</th>
                                    <th data-whp-nosort>Databases</th>
                                    <th data-whp-nosort>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($manageable_users as $user): ?>
                                <tr>
                                    <td>
                                        <strong><?php echo htmlspecialchars($user['User']); ?></strong>
                                        <?php if (AUTH_USER !== 'root' && strpos($user['User'], AUTH_USER . '_') === 0): ?>
                                        <br><small class="text-muted">Your database user</small>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo htmlspecialchars($user['Host']); ?></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($db) . '</span> ';
                                            }
                                            ?>
                                        <?php else: ?>
                                            <span class="text-muted">No databases assigned</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <form method="POST" action="" style="display:inline;" data-whp-async data-whp-action="/api/database-ajax.php" data-whp-remove-row data-whp-confirm="Delete the database user '<?php echo htmlspecialchars($user['User'], ENT_QUOTES); ?>'? 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['User']); ?>">
                                            <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>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

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

/* Ensure eye icon is visible and maintains styling */
#togglePasswordBtn {
    color: #6c757d !important;
    background-color: var(--whp-card-header-bg) !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: var(--whp-form-bg) !important;
    color: var(--whp-content-text) !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, MySQL-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>
<script src="/js/whp-table.js?v=<?php echo htmlspecialchars($whp_css_v); ?>"></script>
<script src="/js/whp-async-forms.js?v=<?php echo htmlspecialchars($whp_css_v); ?>"></script>
