<?php
/**
 * admin/threat-detection.php - Advanced Threat Detection & Management
 */

require_once __DIR__ . '/includes/base.php';

if (!hasAdminPermission('manage_security')) {
    setFlashMessage('Access denied.', 'error');
    header('Location: ' . APP_URL . '/admin/index.php');
    exit();
}

$breadcrumbs = [
    ['title' => 'Security', 'url' => APP_URL . '/admin/security-dashboard.php'],
    ['title' => 'Threat Detection', 'url' => '']
];

renderAdminHeader('Threat Detection', $breadcrumbs);
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-1 fw-bold"><i class="bi bi-radar me-2"></i>Threat Detection</h2>
        <p class="text-muted mb-0">Configure automated threat detection rules</p>
    </div>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addRuleModal">
        <i class="bi bi-plus-circle me-2"></i>Add Detection Rule
    </button>
</div>

<div class="row">
    <div class="col-md-12">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <table class="table" id="rulesTable">
                    <thead>
                        <tr>
                            <th>Rule Name</th>
                            <th>Type</th>
                            <th>Severity</th>
                            <th>Status</th>
                            <th>Threshold</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td colspan="6" class="text-center py-5">
                                <div class="spinner-border text-primary"></div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Add/Edit Rule Modal -->
<div class="modal fade" id="addRuleModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add Detection Rule</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="ruleForm">
                <input type="hidden" name="rule_id" id="rule_id">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Rule Name *</label>
                            <input type="text" class="form-control" name="rule_name" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Threat Type *</label>
                            <select class="form-select" name="threat_type" required>
                                <option value="brute_force">Brute Force</option>
                                <option value="sql_injection">SQL Injection</option>
                                <option value="xss">Cross-Site Scripting (XSS)</option>
                                <option value="ddos">DDoS Attack</option>
                                <option value="suspicious_activity">Suspicious Activity</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Severity *</label>
                            <select class="form-select" name="severity" required>
                                <option value="low">Low</option>
                                <option value="medium">Medium</option>
                                <option value="high">High</option>
                                <option value="critical">Critical</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Detection Threshold</label>
                            <input type="number" class="form-control" name="threshold" value="5">
                            <small class="text-muted">Number of attempts before triggering</small>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Time Window (minutes)</label>
                            <input type="number" class="form-control" name="time_window" value="5">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Auto-Action</label>
                            <select class="form-select" name="auto_action">
                                <option value="log_only">Log Only</option>
                                <option value="block_temp">Temporary Block (1 hour)</option>
                                <option value="block_permanent">Permanent Block</option>
                                <option value="notify_admin">Notify Admin Only</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea class="form-control" name="description" rows="3"></textarea>
                    </div>
                    
                    <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" name="is_active" id="is_active" checked>
                        <label class="form-check-label" for="is_active">Active</label>
                    </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">Save Rule</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    loadRules();
});

function loadRules() {
    $.get(APP_URL + '/api/admin.php?action=get_detection_rules', function(response) {
        if (response.success && response.data.length > 0) {
            let html = '';
            response.data.forEach(rule => {
                html += `
                    <tr>
                        <td><strong>${rule.rule_name}</strong></td>
                        <td><span class="badge bg-secondary">${rule.threat_type}</span></td>
                        <td><span class="badge bg-${rule.severity === 'critical' ? 'danger' : (rule.severity === 'high' ? 'warning' : 'info')}">${rule.severity}</span></td>
                        <td><span class="badge bg-${rule.is_active ? 'success' : 'secondary'}">${rule.is_active ? 'Active' : 'Inactive'}</span></td>
                        <td>${rule.threshold} in ${rule.time_window}min</td>
                        <td>
                            <button class="btn btn-sm btn-outline-primary" onclick="editRule(${rule.id})"><i class="bi bi-pencil"></i></button>
                            <button class="btn btn-sm btn-outline-danger" onclick="deleteRule(${rule.id})"><i class="bi bi-trash"></i></button>
                        </td>
                    </tr>
                `;
            });
            $('#rulesTable tbody').html(html);
        } else {
            $('#rulesTable tbody').html('<tr><td colspan="6" class="text-center">No detection rules configured</td></tr>');
        }
    });
}

$('#ruleForm').submit(function(e) {
    e.preventDefault();
    const formData = $(this).serializeArray();
    formData.push({name: 'action', value: $('#rule_id').val() ? 'update_detection_rule' : 'create_detection_rule'});
    
    showLoading();
    $.post(APP_URL + '/api/admin.php', $.param(formData), function(response) {
        hideLoading();
        if (response.success) {
            showToast(response.message, 'success');
            $('#addRuleModal').modal('hide');
            $('#ruleForm')[0].reset();
            loadRules();
        } else {
            showToast(response.message, 'error');
        }
    });
});

function editRule(id) {
    $.get(APP_URL + '/api/admin.php?action=get_detection_rule&rule_id=' + id, function(response) {
        if (response.success) {
            const rule = response.data;
            $('#rule_id').val(rule.id);
            $('[name="rule_name"]').val(rule.rule_name);
            $('[name="threat_type"]').val(rule.threat_type);
            $('[name="severity"]').val(rule.severity);
            $('[name="threshold"]').val(rule.threshold);
            $('[name="time_window"]').val(rule.time_window);
            $('[name="auto_action"]').val(rule.auto_action);
            $('[name="description"]').val(rule.description);
            $('[name="is_active"]').prop('checked', rule.is_active);
            $('.modal-title').text('Edit Detection Rule');
            $('#addRuleModal').modal('show');
        }
    });
}

function deleteRule(id) {
    Swal.fire({
        title: 'Delete Rule?',
        text: 'This cannot be undone',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#dc3545',
        confirmButtonText: 'Delete'
    }).then((result) => {
        if (result.isConfirmed) {
            $.post(APP_URL + '/api/admin.php', {action: 'delete_detection_rule', rule_id: id}, function(response) {
                if (response.success) {
                    showToast(response.message, 'success');
                    loadRules();
                }
            });
        }
    });
}

$('#addRuleModal').on('hidden.bs.modal', function() {
    $('#ruleForm')[0].reset();
    $('#rule_id').val('');
    $('.modal-title').text('Add Detection Rule');
});
</script>

<?php renderAdminFooter(); ?>