<?php
// Permission checking is now handled by the permission system in auto-prepend.php

require_once('/docker/whp/web/libs/mysqlmgmt.php');

$MySQLMgmt = new mysqlmgmt();

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

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'update_resources':
                if (!empty($_POST['username']) && isset($_POST['max_cpu_allowance']) && isset($_POST['max_memory_allowance'])) {
                    // Archived-mailbox quota cannot be reduced below the user's current
                    // archived count; otherwise paid-for archives would silently exceed
                    // the new ceiling. Block here rather than after the write.
                    $req_archived = isset($_POST['max_archived_mailboxes'])
                        ? max(0, intval($_POST['max_archived_mailboxes']))
                        : null;
                    if ($req_archived !== null) {
                        $stmt = $MySQLMgmt->getMySQLConnection()->prepare(
                            "SELECT COUNT(*) FROM whp.email_accounts WHERE username = ? AND archival_enabled = 1"
                        );
                        $stmt->execute([$_POST['username']]);
                        $current_archived = (int)$stmt->fetchColumn();
                        if ($req_archived < $current_archived) {
                            $message = "Cannot reduce Max Archived Mailboxes to $req_archived for {$_POST['username']}: $current_archived currently archived. Disable archival on the excess mailboxes first.";
                            $message_type = 'danger';
                            break;
                        }
                    }

                    $result = $MySQLMgmt->updateClientAllowances(
                        $_POST['username'],
                        floatval($_POST['max_cpu_allowance']),
                        intval($_POST['max_memory_allowance']),
                        null, // max_domains not needed
                        isset($_POST['max_disk_space']) ? intval($_POST['max_disk_space']) : null,
                        isset($_POST['max_email_accounts']) ? intval($_POST['max_email_accounts']) : null,
                        isset($_POST['max_email_storage_mb']) ? intval($_POST['max_email_storage_mb']) : null,
                        isset($_POST['account_type']) ? $_POST['account_type'] : 'full',
                        $req_archived
                    );
                    
                    if ($result['status'] === '0') {
                        $message = $result['msg'] . ' for user: ' . $_POST['username'];
                        
                        // Sync filesystem quota if disk space was updated
                        if (isset($_POST['max_disk_space'])) {
                            $disk_quota_mb = intval($_POST['max_disk_space']);
                            $quota_cmd = '/root/whp/scripts/quota-helper.sh set ' . escapeshellarg($_POST['username']) . ' ' . $disk_quota_mb . ' 2>&1';
                            $quota_output = shell_exec($quota_cmd);
                            $quota_exit_code = 0;
                            exec('/root/whp/scripts/quota-helper.sh set ' . escapeshellarg($_POST['username']) . ' ' . $disk_quota_mb, $quota_exec_output, $quota_exit_code);
                            
                            if ($quota_exit_code === 0) {
                                $message .= ' (Filesystem quota synced: ' . $disk_quota_mb . ' MB)';
                            } else {
                                $message .= ' (Warning: Filesystem quota sync failed - ' . trim($quota_output) . ')';
                                error_log("Failed to update filesystem quota for {$_POST['username']} to {$disk_quota_mb}MB (exit code: $quota_exit_code): " . trim($quota_output));
                            }
                        }
                        
                        $message_type = 'success';
                    } else {
                        $message = $result['msg'];
                        $message_type = 'danger';
                    }
                }
                break;
                
            case 'reset_to_default':
                if (!empty($_POST['username'])) {
                    // Reset would drop archival quota to 0 — block if the user has any
                    // archived mailboxes; root must disable those first.
                    $stmt = $MySQLMgmt->getMySQLConnection()->prepare(
                        "SELECT COUNT(*) FROM whp.email_accounts WHERE username = ? AND archival_enabled = 1"
                    );
                    $stmt->execute([$_POST['username']]);
                    $current_archived = (int)$stmt->fetchColumn();
                    if ($current_archived > 0) {
                        $message = "Cannot reset {$_POST['username']}: $current_archived archived mailboxes are still active. Disable them on the Email Management page first.";
                        $message_type = 'danger';
                        break;
                    }

                    $result = $MySQLMgmt->updateClientAllowances(
                        $_POST['username'],
                        0.5, // Default CPU
                        512, // Default memory
                        null, // max_domains not needed
                        1000, // Default disk space
                        0,   // Default email accounts
                        1000, // Default email storage
                        'full', // Default account type
                        0    // Default archived mailboxes
                    );
                    
                    if ($result['status'] === '0') {
                        // Sync filesystem quota to default (1000 MB)
                        $quota_cmd = '/root/whp/scripts/quota-helper.sh set ' . escapeshellarg($_POST['username']) . ' 1000 2>&1';
                        $quota_output = shell_exec($quota_cmd);
                        $quota_exit_code = 0;
                        exec('/root/whp/scripts/quota-helper.sh set ' . escapeshellarg($_POST['username']) . ' 1000', $quota_exec_output, $quota_exit_code);
                        
                        $message = 'Resources reset to default for user: ' . $_POST['username'];
                        if ($quota_exit_code === 0) {
                            $message .= ' (Filesystem quota set to 1000 MB)';
                        } else {
                            $message .= ' (Warning: Filesystem quota sync failed - ' . trim($quota_output) . ')';
                            error_log("Failed to reset quota for {$_POST['username']} to 1000MB (exit code: $quota_exit_code): " . trim($quota_output));
                        }
                        $message_type = 'success';
                    } else {
                        $message = $result['msg'];
                        $message_type = 'danger';
                    }
                }
                break;
        }
    }
}

// Get all users with their resource allocations
$users_result = $MySQLMgmt->getAllSystemUsersWithResources();
$users = [];
if ($users_result['status'] === '0') {
    $users = $users_result['users'];
} else {
    $message = $users_result['msg'];
    $message_type = 'danger';
}

// Get current resource usage for each user
$user_usage = [];
foreach ($users as $user) {
    $user_usage[$user['username']] = $MySQLMgmt->getUserResourceUsage($user['username']);
}
?>

<div class="row">
    <div class="col-md-12">
        <?php if (!empty($message)): ?>
        <div class="alert alert-<?php echo $message_type; ?> alert-dismissible" role="alert">
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            <i class="fa fa-<?php echo $message_type === 'success' ? 'check' : 'exclamation-triangle'; ?>"></i>
            <?php echo htmlspecialchars($message); ?>
        </div>
        <?php endif; ?>
    </div>
</div>

<div class="row">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">User Resource Management</h5>
            </div>
            <div class="card-body">
                <div class="alert alert-info">
                    <i class="fa fa-info-circle"></i>
                    <strong>Resource Management</strong> - Configure CPU and memory allowances for hosting users. 
                    Users can allocate resources to their sites in 0.25 CPU increments and 256 MB memory increments.
                    <br><small><strong>Note:</strong> Memory usage tracking is not available in Docker environments. Active sites count shows running containers.</small>
                </div>
                
                <?php if (empty($users)): ?>
                <div class="alert alert-warning">
                    <i class="fa fa-exclamation-triangle"></i>
                    <strong>No hosting users found</strong> - Create hosting users via User Management to configure their resources.
                </div>
                <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-striped user-resource-table">
                        <thead>
                            <tr>
                                <th>User</th>
                                <th>Account Type</th>
                                <th>Max CPU</th>
                                <th>CPU Used</th>
                                <th>Max Mem</th>
                                <th>Mem Used</th>
                                <th>Disk</th>
                                <th>Used</th>
                                <th>Email</th>
                                <th>Mail MB</th>
                                <th title="Archival mailboxes (used/max)">Arch.</th>
                                <th title="Active containers">Cont.</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach (
                                $users as $user): ?>
                            <?php 
                            $usage = $user_usage[$user['username']];
                            $cpu_percentage = $user['max_cpu_allowance'] > 0 ? 
                                round(($usage['cpu_used'] / $user['max_cpu_allowance']) * 100, 1) : 0;
                            $memory_percentage = $user['max_memory_allowance'] > 0 ? 
                                round(($usage['memory_used'] / $user['max_memory_allowance']) * 100, 1) : 0;
                            $disk_percentage = ($user['max_disk_space'] > 0 && isset($usage['disk_used_mb'])) ? 
                                round(($usage['disk_used_mb'] / $user['max_disk_space']) * 100, 1) : 0;
                            $email_used = isset($usage['email_accounts']) ? $usage['email_accounts'] : 0;
                            $email_percentage = $user['max_email_accounts'] > 0 ? round(($email_used / $user['max_email_accounts']) * 100, 1) : 0;
                            $email_storage_used = isset($usage['email_storage_mb']) ? $usage['email_storage_mb'] : 0;
                            $max_email_storage = $user['max_email_storage_mb'] ?? 1000;
                            $storage_percentage = $max_email_storage > 0 ? round(($email_storage_used / $max_email_storage) * 100, 1) : 0;
                            $max_archived = (int)($user['max_archived_mailboxes'] ?? 0);
                            $archived_used = (int)($usage['archived_mailboxes'] ?? 0);
                            $archived_pct  = $max_archived > 0 ? round(($archived_used / $max_archived) * 100, 1) : 0;
                            ?>
                            <tr>
                                <td>
                                    <strong><?php echo htmlspecialchars($user['username']); ?></strong>
                                    <br><small class="text-muted">UID: <?php echo $user['uid']; ?> | <?php echo htmlspecialchars($user['home_dir']); ?></small>
                                </td>
                                <td>
                                    <?php
                                    $acct_type = $user['account_type'] ?? 'full';
                                    $acct_badge_classes = [
                                        'full' => 'bg-success',
                                        'domain_dns' => 'bg-primary',
                                        'mail_dns' => 'bg-purple'
                                    ];
                                    $acct_labels = [
                                        'full' => 'Full Hosting',
                                        'domain_dns' => 'Domain/DNS',
                                        'mail_dns' => 'Mail/DNS'
                                    ];
                                    $badge_class = $acct_badge_classes[$acct_type] ?? 'bg-secondary';
                                    $badge_label = $acct_labels[$acct_type] ?? ucfirst($acct_type);
                                    ?>
                                    <span class="badge <?php echo $badge_class; ?>"<?php if ($acct_type === 'mail_dns') echo ' style="background-color: #6f42c1 !important;"'; ?>><?php echo $badge_label; ?></span>
                                </td>
                                <td><?php echo number_format($user['max_cpu_allowance'], 2); ?></td>
                                <td><?php echo number_format($usage['cpu_used'], 2); ?> (<?php echo $cpu_percentage; ?>%)</td>
                                <td><?php echo number_format($user['max_memory_allowance']); ?></td>
                                <td><?php echo number_format($usage['memory_used']); ?> (<?php echo $memory_percentage; ?>%)</td>
                                <td><?php echo number_format($user['max_disk_space']); ?></td>
                                <td>
                                    <?php if (isset($usage['disk_used_mb'])): ?>
                                        <?php echo number_format($usage['disk_used_mb'], 1); ?> (<?php echo $disk_percentage; ?>%)
                                    <?php else: ?>
                                        <small class="text-muted">No quota</small>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo number_format($user['max_email_accounts']); ?></td>
                                <td><?php echo number_format($user['max_email_storage_mb'] ?? 1000); ?></td>
                                <td>
                                    <?php if ($max_archived > 0): ?>
                                        <?php echo $archived_used; ?>/<?php echo $max_archived; ?>
                                    <?php elseif ($archived_used > 0): ?>
                                        <span class="text-danger" title="Over quota — disable some to come into compliance"><?php echo $archived_used; ?>/0</span>
                                    <?php else: ?>
                                        <span class="text-muted small">&mdash;</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="badge <?php echo $usage['containers'] > 0 ? 'bg-success' : 'bg-secondary'; ?>">
                                        <?php echo $usage['containers']; ?>
                                    </span>
                                    <?php if ($usage['domains'] > 0): ?>
                                    <br><small class="text-muted">Domains: <?php echo $usage['domains']; ?></small>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#editResourcesModal"
                                            data-username="<?php echo htmlspecialchars($user['username']); ?>"
                                            data-cpu="<?php echo $user['max_cpu_allowance']; ?>"
                                            data-memory="<?php echo $user['max_memory_allowance']; ?>"
                                            data-disk="<?php echo $user['max_disk_space']; ?>"
                                            data-email="<?php echo $user['max_email_accounts']; ?>"
                                            data-email-storage="<?php echo $user['max_email_storage_mb'] ?? 1000; ?>"
                                            data-account-type="<?php echo htmlspecialchars($user['account_type'] ?? 'full'); ?>"
                                            data-archived="<?php echo $max_archived; ?>"
                                            data-archived-used="<?php echo $archived_used; ?>">
                                        <i class="fa fa-edit"></i>
                                    </button>
                                    <form method="post" style="display: inline;">
                                        <input type="hidden" name="action" value="reset_to_default">
                                        <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-sm btn-outline-secondary" 
                                                onclick="return confirm('Reset resources to default for <?php echo htmlspecialchars($user['username']); ?>?');">
                                            <i class="fa fa-refresh"></i>
                                        </button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
                
                <!-- System Overview -->
                <div class="row mt-4 resource-cards-row d-flex align-items-stretch">
                    <div class="col-md-2 d-flex align-items-stretch">
                        <div class="card bg-light text-dark h-100 w-100">
                            <div class="card-body text-center d-flex flex-column justify-content-center">
                                <h6 class="text-secondary">Total CPU</h6>
                                <h4 class="text-primary"><?php echo number_format($total_allocated_cpu, 2); ?> cores</h4>
                                <small class="text-muted"><?php echo number_format($total_used_cpu, 2); ?> used</small>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-2 d-flex align-items-stretch">
                        <div class="card bg-light text-dark h-100 w-100">
                            <div class="card-body text-center d-flex flex-column justify-content-center">
                                <h6 class="text-secondary">Total Mem</h6>
                                <h4 class="text-info"><?php echo number_format($total_allocated_memory); ?> MB</h4>
                                <small class="text-muted"><?php echo number_format($total_used_memory); ?> MB used</small>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-2 d-flex align-items-stretch">
                        <div class="card bg-light text-dark h-100 w-100">
                            <div class="card-body text-center d-flex flex-column justify-content-center">
                                <h6 class="text-secondary">Total Disk</h6>
                                <h4 class="text-warning"><?php echo number_format($total_allocated_disk); ?> MB</h4>
                                <small class="text-muted"><?php echo number_format($total_used_disk, 1); ?> MB used</small>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-2 d-flex align-items-stretch">
                        <div class="card bg-light text-dark h-100 w-100">
                            <div class="card-body text-center d-flex flex-column justify-content-center">
                                <h6 class="text-secondary">Containers</h6>
                                <h4 class="text-success"><?php echo $total_containers; ?></h4>
                                <small class="text-muted">Active</small>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-2 d-flex align-items-stretch">
                        <div class="card bg-light text-dark h-100 w-100">
                            <div class="card-body text-center d-flex flex-column justify-content-center">
                                <h6 class="text-secondary">Users</h6>
                                <h4 class="text-danger"><?php echo count($users); ?></h4>
                                <small class="text-muted">Total</small>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-2 d-flex align-items-stretch">
                        <div class="card bg-light text-dark h-100 w-100">
                            <div class="card-body text-center d-flex flex-column justify-content-center">
                                <h6 class="text-secondary">Disk Usage</h6>
                                <?php 
                                $disk_usage_percentage = $total_allocated_disk > 0 ? round(($total_used_disk / $total_allocated_disk) * 100, 1) : 0;
                                ?>
                                <h4 class="<?php echo $disk_usage_percentage > 80 ? 'text-danger' : ($disk_usage_percentage > 60 ? 'text-warning' : 'text-success'); ?>">
                                    <?php echo $disk_usage_percentage; ?>%
                                </h4>
                                <small class="text-muted">Overall</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Edit Resources Modal -->
<div class="modal fade" id="editResourcesModal" tabindex="-1" aria-labelledby="editResourcesModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editResourcesModalLabel">Edit User Resources</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="post">
                <div class="modal-body">
                    <input type="hidden" name="action" value="update_resources">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                    <input type="hidden" name="username" id="edit_username">
                    
                    <div class="mb-3">
                        <label for="edit_max_cpu" class="form-label">Max CPU Allowance (cores)</label>
                        <input type="number" class="form-control" id="edit_max_cpu" name="max_cpu_allowance" 
                               min="0.25" max="8" step="0.25" required>
                        <div class="form-text">Range: 0.25 to 8 cores in 0.25 increments</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="edit_max_memory" class="form-label">Max Memory Allowance (MB)</label>
                        <input type="number" class="form-control" id="edit_max_memory" name="max_memory_allowance" 
                               min="256" max="8192" step="256" required>
                        <div class="form-text">Range: 256 MB to 8192 MB in 256 MB increments</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="edit_max_disk" class="form-label">Max Disk Space (MB)</label>
                        <input type="number" class="form-control" id="edit_max_disk" name="max_disk_space" 
                               min="100" max="100000" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="edit_max_email" class="form-label">Max Email Accounts</label>
                        <input type="number" class="form-control" id="edit_max_email" name="max_email_accounts" 
                               min="0" max="1000" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="edit_max_email_storage" class="form-label">Max Email Storage (MB)</label>
                        <input type="number" class="form-control" id="edit_max_email_storage" name="max_email_storage_mb"
                               min="0" max="100000" required>
                        <div class="form-text">Total storage limit for all email accounts combined</div>
                    </div>

                    <div class="mb-3">
                        <label for="edit_max_archived" class="form-label">Max Archived Mailboxes (Bichon)</label>
                        <input type="number" class="form-control" id="edit_max_archived" name="max_archived_mailboxes"
                               min="0" max="9999" value="0">
                        <div class="form-text" id="edit_max_archived_hint"></div>
                    </div>

                    <div class="mb-3">
                        <label for="edit_account_type" class="form-label">Account Type</label>
                        <select class="form-select" id="edit_account_type" name="account_type">
                            <option value="full">Full Hosting</option>
                            <option value="domain_dns">Domain/DNS</option>
                            <option value="mail_dns">Mail/DNS</option>
                        </select>
                        <div class="form-text">Controls which resources and panel sections are available to this user</div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update Resources</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Handle edit modal data population
document.addEventListener('DOMContentLoaded', function() {
    const editModal = document.getElementById('editResourcesModal');
    if (editModal) {
        editModal.addEventListener('show.bs.modal', function(event) {
            const button = event.relatedTarget;
            const username = button.getAttribute('data-username');
            const cpu = button.getAttribute('data-cpu');
            const memory = button.getAttribute('data-memory');
            const disk = button.getAttribute('data-disk');
            const email = button.getAttribute('data-email');
            const emailStorage = button.getAttribute('data-email-storage');
            const accountType = button.getAttribute('data-account-type') || 'full';
            const archived = button.getAttribute('data-archived') || '0';
            const archivedUsed = parseInt(button.getAttribute('data-archived-used') || '0', 10);

            editModal.querySelector('#edit_username').value = username;
            editModal.querySelector('#edit_max_cpu').value = cpu;
            editModal.querySelector('#edit_max_memory').value = memory;
            editModal.querySelector('#edit_max_disk').value = disk;
            editModal.querySelector('#edit_max_email').value = email;
            editModal.querySelector('#edit_max_email_storage').value = emailStorage;
            editModal.querySelector('#edit_max_archived').value = archived;
            editModal.querySelector('#edit_max_archived').min = archivedUsed; // can't drop below current count
            const hint = editModal.querySelector('#edit_max_archived_hint');
            hint.textContent = archivedUsed > 0
                ? archivedUsed + ' currently archived — value cannot be lower than that.'
                : 'Number of mailboxes this user may push to Bichon archival. 0 disables the addon.';
            editModal.querySelector('#edit_account_type').value = accountType;

            editModal.querySelector('.modal-title').textContent = 'Edit Resources for ' + username;
        });
    }
});
</script> 