<?php
// Security tab — API Key Management (root-only).
// Variables ($apiKeys) are prepared in the parent server-settings.php before
// the include.
?>

<?php if (defined('AUTH_USER') && AUTH_USER === 'root'): ?>
<!-- API Key Management (Root Only) -->
<div class="row">
    <div class="col-md-12">
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">API Key Management</h5>
                <p class="text-muted small mb-0">Manage API keys for external integrations like WHMCS</p>
            </div>
            <div class="card-body">

                <!-- Display new API key if just created -->
                <?php if (isset($_SESSION['new_api_key']) && isset($_SESSION['new_api_secret'])): ?>
                <div class="alert alert-success alert-dismissible">
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    <h5><i class="fa fa-check-circle"></i> API Key Created Successfully</h5>
                    <p><strong>API Key:</strong> <code><?php echo htmlspecialchars($_SESSION['new_api_key']); ?></code></p>
                    <p><strong>API Secret:</strong> <code id="api-secret-display"><?php echo htmlspecialchars($_SESSION['new_api_secret']); ?></code>
                    <button type="button" class="btn btn-sm btn-outline-secondary ms-2" onclick="copyToClipboard('api-secret-display')">
                        <i class="fa fa-copy"></i> Copy
                    </button></p>
                    <p class="text-danger"><strong>Important:</strong> Please copy the API secret now. It will not be shown again for security reasons.</p>
                </div>
                <?php
                // Clear the session variables after displaying
                unset($_SESSION['new_api_key'], $_SESSION['new_api_secret']);
                endif;
                ?>

                <!-- Create New API Key Form -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h6 class="card-title mb-0">Create New API Key</h6>
                    </div>
                    <div class="card-body">
                        <form method="post">
                            <input type="hidden" name="action" value="create_api_key">
                            <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="key_name" class="form-label">Key Name</label>
                                        <input type="text" class="form-control" id="key_name" name="key_name"
                                               placeholder="WHMCS Integration Key" required>
                                        <div class="form-text text-muted">Descriptive name for this API key</div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="rate_limit" class="form-label">Rate Limit (per hour)</label>
                                        <input type="number" class="form-control" id="rate_limit" name="rate_limit"
                                               value="1000" min="1" max="10000">
                                        <div class="form-text text-muted">Maximum API requests per hour</div>
                                    </div>
                                </div>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Permissions</label>
                                <div class="row">
                                    <div class="col-md-3">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="permissions[user_management]" value="1" id="perm-user">
                                            <label class="form-check-label" for="perm-user">User Management</label>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="permissions[resource_management]" value="1" id="perm-resources">
                                            <label class="form-check-label" for="perm-resources">Resource Management</label>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="permissions[sso_access]" value="1" id="perm-sso">
                                            <label class="form-check-label" for="perm-sso">SSO Access</label>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="permissions[system_stats]" value="1" id="perm-stats">
                                            <label class="form-check-label" for="perm-stats">System Statistics</label>
                                        </div>
                                    </div>
                                </div>
                                <div class="row mt-2">
                                    <div class="col-md-3">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="permissions[ai_monitor_management]" value="1" id="perm-ai-monitor">
                                            <label class="form-check-label" for="perm-ai-monitor">AI Monitor Management</label>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="mb-3">
                                <label for="ip_whitelist" class="form-label">IP Whitelist (optional)</label>
                                <input type="text" class="form-control" id="ip_whitelist" name="ip_whitelist"
                                       placeholder="192.168.1.100, 10.0.0.50">
                                <div class="form-text text-muted">Comma-separated list of allowed IP addresses (leave empty for no restrictions)</div>
                            </div>

                            <div class="mb-3">
                                <label for="notes" class="form-label">Notes (optional)</label>
                                <textarea class="form-control" id="notes" name="notes" rows="2"
                                          placeholder="Additional notes about this API key"></textarea>
                            </div>

                            <button type="submit" class="btn btn-primary">
                                <i class="fa fa-plus"></i> Create API Key
                            </button>
                        </form>
                    </div>
                </div>

                <!-- Existing API Keys -->
                <div class="card">
                    <div class="card-header">
                        <h6 class="card-title mb-0">Existing API Keys</h6>
                    </div>
                    <div class="card-body">
                        <?php if (!empty($apiKeys)): ?>
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Name</th>
                                        <th>API Key</th>
                                        <th>Permissions</th>
                                        <th>Rate Limit</th>
                                        <th>Status</th>
                                        <th>Last Used</th>
                                        <th>Usage Count</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($apiKeys as $key): ?>
                                    <tr>
                                        <td>
                                            <strong><?php echo htmlspecialchars($key['key_name']); ?></strong>
                                            <?php if ($key['notes']): ?>
                                            <br><small class="text-muted"><?php echo htmlspecialchars($key['notes']); ?></small>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <code class="small"><?php echo htmlspecialchars(substr($key['api_key'], 0, 20) . '...'); ?></code>
                                            <button type="button" class="btn btn-sm btn-outline-secondary ms-1"
                                                    onclick="copyToClipboard('<?php echo htmlspecialchars($key['api_key']); ?>')">
                                                <i class="fa fa-copy"></i>
                                            </button>
                                        </td>
                                        <td>
                                            <?php if (!empty($key['permissions'])): ?>
                                                <?php foreach ($key['permissions'] as $perm => $enabled): ?>
                                                    <?php if ($enabled): ?>
                                                        <span class="badge bg-info me-1"><?php echo ucwords(str_replace('_', ' ', $perm)); ?></span>
                                                    <?php endif; ?>
                                                <?php endforeach; ?>
                                            <?php else: ?>
                                                <span class="text-muted">None</span>
                                            <?php endif; ?>
                                        </td>
                                        <td><?php echo number_format($key['rate_limit_per_hour']); ?>/hour</td>
                                        <td>
                                            <span class="badge <?php echo $key['is_active'] ? 'bg-success' : 'bg-danger'; ?>">
                                                <?php echo $key['is_active'] ? 'Active' : 'Inactive'; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php if ($key['last_used_at']): ?>
                                                <small><?php echo date('M j, Y g:i A', strtotime($key['last_used_at'])); ?></small>
                                            <?php else: ?>
                                                <small class="text-muted">Never</small>
                                            <?php endif; ?>
                                        </td>
                                        <td><?php echo number_format($key['usage_count']); ?></td>
                                        <td>
                                            <?php if ($key['is_active']): ?>
                                            <form method="post" class="d-inline" onsubmit="return confirm('Are you sure you want to deactivate this API key?');">
                                                <input type="hidden" name="action" value="deactivate_api_key">
                                                <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                                                <input type="hidden" name="key_id" value="<?php echo $key['id']; ?>">
                                                <button type="submit" class="btn btn-sm btn-outline-danger">
                                                    <i class="fa fa-times"></i> Deactivate
                                                </button>
                                            </form>
                                            <?php else: ?>
                                                <span class="text-muted small">Deactivated</span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        <?php else: ?>
                        <div class="text-center text-muted py-4">
                            <i class="fa fa-key fa-3x mb-3"></i>
                            <h5>No API Keys</h5>
                            <p>Create your first API key to enable external integrations.</p>
                        </div>
                        <?php endif; ?>

                        <!-- Utility Actions -->
                        <hr>
                        <div class="d-flex gap-2">
                            <form method="post" class="d-inline">
                                <input type="hidden" name="action" value="cleanup_sso_tokens">
                                <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                                <button type="submit" class="btn btn-sm btn-outline-warning">
                                    <i class="fa fa-trash"></i> Cleanup Expired SSO Tokens
                                </button>
                            </form>
                        </div>

                        <div class="mt-3">
                            <small class="text-muted">
                                <strong>API Usage:</strong><br>
                                • <strong>User Management:</strong> Create, delete, and modify user accounts<br>
                                • <strong>Resource Management:</strong> Update user resource limits and quotas<br>
                                • <strong>SSO Access:</strong> Generate single sign-on tokens for auto-login<br>
                                • <strong>System Statistics:</strong> Access server stats and health information<br>
                                • API keys are used with X-API-Key and X-API-Secret headers<br>
                                • Documentation: <code>/api/external/</code> endpoints
                            </small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>
