<?php
session_start();
require_once '../config.php';

requireAdmin();

$page_title = 'Security & Audit';

// Get security statistics
$security_stats = [
    'total_logins_today' => $conn->query("SELECT COUNT(*) as count FROM audit_logs WHERE action LIKE '%login%' AND DATE(created_at) = CURDATE()")->fetch_assoc()['count'],
    'failed_logins_today' => $conn->query("SELECT COUNT(*) as count FROM audit_logs WHERE action = 'login_failed' AND DATE(created_at) = CURDATE()")->fetch_assoc()['count'],
    'total_activities_today' => $conn->query("SELECT COUNT(*) as count FROM audit_logs WHERE DATE(created_at) = CURDATE()")->fetch_assoc()['count'],
    'unique_ips_today' => $conn->query("SELECT COUNT(DISTINCT ip_address) as count FROM audit_logs WHERE DATE(created_at) = CURDATE()")->fetch_assoc()['count'],
    'doctor_verifications_pending' => $conn->query("SELECT COUNT(*) as count FROM doctors WHERE verification_status = 'pending'")->fetch_assoc()['count'],
    'total_audit_logs' => $conn->query("SELECT COUNT(*) as count FROM audit_logs")->fetch_assoc()['count']
];

// Get recent security activities
$security_activities = $conn->query("
    SELECT al.*, 
           CASE 
               WHEN al.user_type = 'patient' THEN p.full_name
               WHEN al.user_type = 'doctor' THEN d.full_name
               WHEN al.user_type = 'admin' THEN a.full_name
           END as user_name
    FROM audit_logs al
    LEFT JOIN patients p ON al.user_type = 'patient' AND al.user_id = p.id
    LEFT JOIN doctors d ON al.user_type = 'doctor' AND al.user_id = d.id
    LEFT JOIN admin_users a ON al.user_type = 'admin' AND al.user_id = a.id
    WHERE al.action IN ('login_success', 'login_failed', 'password_changed', 'account_locked', 'data_breach_attempt')
    ORDER BY al.created_at DESC
    LIMIT 20
")->fetch_all(MYSQLI_ASSOC);

// Get system health metrics
$system_health = [
    'database_size' => $conn->query("SELECT ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS size_mb FROM information_schema.tables WHERE table_schema = DATABASE()")->fetch_assoc()['size_mb'],
    'total_files' => is_dir('../uploads') ? count(glob('../uploads/**/*', GLOB_BRACE)) : 0,
    'php_version' => phpversion(),
    'mysql_version' => $conn->server_info,
    'disk_usage' => round(disk_total_space('.') / 1024 / 1024 / 1024, 2),
    'memory_usage' => memory_get_usage(true) / 1024 / 1024
];

// Recent suspicious activities
$suspicious_activities = $conn->query("
    SELECT al.*, 
           CASE 
               WHEN al.user_type = 'patient' THEN p.full_name
               WHEN al.user_type = 'doctor' THEN d.full_name
               WHEN al.user_type = 'admin' THEN a.full_name
           END as user_name
    FROM audit_logs al
    LEFT JOIN patients p ON al.user_type = 'patient' AND al.user_id = p.id
    LEFT JOIN doctors d ON al.user_type = 'doctor' AND al.user_id = d.id
    LEFT JOIN admin_users a ON al.user_type = 'admin' AND al.user_id = a.id
    WHERE al.action IN ('login_failed', 'suspicious_activity', 'unauthorized_access')
    ORDER BY al.created_at DESC
    LIMIT 10
")->fetch_all(MYSQLI_ASSOC);

include 'header.php';
?>

                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">
                        <i class="fas fa-shield-alt text-primary"></i> Security & Audit
                    </h1>
                </div>
            
            <h3><i class="fas fa-shield-alt text-danger"></i> Security & Audit Dashboard</h3>
            
            <!-- Security Stats -->
            <div class="row mb-4">
                <div class="col-md-2 mb-3">
                    <div class="card bg-primary text-white">
                        <div class="card-body">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h4><?= number_format($security_stats['total_logins_today']) ?></h4>
                                    <p class="small">Logins Today</p>
                                </div>
                                <i class="fas fa-sign-in-alt fa-2x"></i>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-2 mb-3">
                    <div class="card bg-danger text-white">
                        <div class="card-body">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h4><?= number_format($security_stats['failed_logins_today']) ?></h4>
                                    <p class="small">Failed Logins</p>
                                </div>
                                <i class="fas fa-exclamation-triangle fa-2x"></i>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-2 mb-3">
                    <div class="card bg-info text-white">
                        <div class="card-body">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h4><?= number_format($security_stats['total_activities_today']) ?></h4>
                                    <p class="small">Activities Today</p>
                                </div>
                                <i class="fas fa-activity fa-2x"></i>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-2 mb-3">
                    <div class="card bg-success text-white">
                        <div class="card-body">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h4><?= number_format($security_stats['unique_ips_today']) ?></h4>
                                    <p class="small">Unique IPs</p>
                                </div>
                                <i class="fas fa-globe fa-2x"></i>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-2 mb-3">
                    <div class="card bg-warning text-white">
                        <div class="card-body">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h4><?= number_format($security_stats['doctor_verifications_pending']) ?></h4>
                                    <p class="small">Pending Verifications</p>
                                </div>
                                <i class="fas fa-user-check fa-2x"></i>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-2 mb-3">
                    <div class="card bg-secondary text-white">
                        <div class="card-body">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h4><?= number_format($security_stats['total_audit_logs']) ?></h4>
                                    <p class="small">Total Audit Logs</p>
                                </div>
                                <i class="fas fa-file-alt fa-2x"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row">
                <!-- System Health -->
                <div class="col-lg-4 mb-4">
                    <div class="card">
                        <div class="card-header">
                            <h6><i class="fas fa-heartbeat text-success"></i> System Health</h6>
                        </div>
                        <div class="card-body">
                            <div class="list-group list-group-flush">
                                <div class="list-group-item d-flex justify-content-between align-items-center">
                                    <span><i class="fas fa-database text-primary"></i> Database Size</span>
                                    <span class="badge bg-primary"><?= $system_health['database_size'] ?> MB</span>
                                </div>
                                <div class="list-group-item d-flex justify-content-between align-items-center">
                                    <span><i class="fas fa-file text-info"></i> Uploaded Files</span>
                                    <span class="badge bg-info"><?= number_format($system_health['total_files']) ?></span>
                                </div>
                                <div class="list-group-item d-flex justify-content-between align-items-center">
                                    <span><i class="fab fa-php text-success"></i> PHP Version</span>
                                    <span class="badge bg-success"><?= $system_health['php_version'] ?></span>
                                </div>
                                <div class="list-group-item d-flex justify-content-between align-items-center">
                                    <span><i class="fas fa-database text-warning"></i> MySQL Version</span>
                                    <span class="badge bg-warning"><?= $system_health['mysql_version'] ?></span>
                                </div>
                                <div class="list-group-item d-flex justify-content-between align-items-center">
                                    <span><i class="fas fa-memory text-danger"></i> Memory Usage</span>
                                    <span class="badge bg-danger"><?= round($system_health['memory_usage'], 2) ?> MB</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Security Tools -->
                <div class="col-lg-4 mb-4">
                    <div class="card">
                        <div class="card-header">
                            <h6><i class="fas fa-tools text-warning"></i> Security Tools</h6>
                        </div>
                        <div class="card-body">
                            <div class="d-grid gap-2">
                                <button class="btn btn-outline-primary" onclick="scanSecurity()">
                                    <i class="fas fa-search"></i> Run Security Scan
                                </button>
                                <button class="btn btn-outline-success" onclick="backupSystem()">
                                    <i class="fas fa-download"></i> Create Backup
                                </button>
                                <button class="btn btn-outline-info" onclick="checkUpdates()">
                                    <i class="fas fa-sync"></i> Check Updates
                                </button>
                                <button class="btn btn-outline-warning" onclick="clearLogs()">
                                    <i class="fas fa-trash"></i> Clear Old Logs
                                </button>
                                <button class="btn btn-outline-danger" onclick="enableMaintenance()">
                                    <i class="fas fa-lock"></i> Maintenance Mode
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Security Compliance -->
                <div class="col-lg-4 mb-4">
                    <div class="card">
                        <div class="card-header">
                            <h6><i class="fas fa-check-circle text-success"></i> Security Compliance</h6>
                        </div>
                        <div class="card-body">
                            <div class="list-group list-group-flush">
                                <div class="list-group-item d-flex justify-content-between align-items-center">
                                    <span>SSL Certificate</span>
                                    <i class="fas fa-check text-success"></i>
                                </div>
                                <div class="list-group-item d-flex justify-content-between align-items-center">
                                    <span>Data Encryption</span>
                                    <i class="fas fa-check text-success"></i>
                                </div>
                                <div class="list-group-item d-flex justify-content-between align-items-center">
                                    <span>Password Policy</span>
                                    <i class="fas fa-check text-success"></i>
                                </div>
                                <div class="list-group-item d-flex justify-content-between align-items-center">
                                    <span>Audit Logging</span>
                                    <i class="fas fa-check text-success"></i>
                                </div>
                                <div class="list-group-item d-flex justify-content-between align-items-center">
                                    <span>File Upload Security</span>
                                    <i class="fas fa-check text-success"></i>
                                </div>
                                <div class="list-group-item d-flex justify-content-between align-items-center">
                                    <span>SQL Injection Protection</span>
                                    <i class="fas fa-check text-success"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row">
                <!-- Recent Security Activities -->
                <div class="col-lg-8 mb-4">
                    <div class="card">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h6><i class="fas fa-shield-alt text-primary"></i> Recent Security Activities</h6>
                            <button class="btn btn-sm btn-outline-primary" onclick="exportLogs()">
                                <i class="fas fa-download"></i> Export Logs
                            </button>
                        </div>
                        <div class="card-body" style="max-height: 400px; overflow-y: auto;">
                            <?php if (empty($security_activities)): ?>
                                <div class="text-center text-muted py-4">
                                    <i class="fas fa-shield-alt fa-3x mb-3"></i>
                                    <p>No security activities recorded</p>
                                </div>
                            <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-sm">
                                        <thead>
                                            <tr>
                                                <th>Time</th>
                                                <th>User</th>
                                                <th>Action</th>
                                                <th>IP Address</th>
                                                <th>Status</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($security_activities as $activity): ?>
                                                <tr>
                                                    <td>
                                                        <small><?= date('M d, h:i A', strtotime($activity['created_at'])) ?></small>
                                                    </td>
                                                    <td>
                                                        <div class="d-flex align-items-center">
                                                            <i class="fas fa-<?= 
                                                                $activity['user_type'] === 'patient' ? 'user' : 
                                                                ($activity['user_type'] === 'doctor' ? 'user-md' : 'user-shield')
                                                            ?> me-2 text-<?= 
                                                                $activity['user_type'] === 'patient' ? 'primary' : 
                                                                ($activity['user_type'] === 'doctor' ? 'success' : 'danger')
                                                            ?>"></i>
                                                            <small><?= htmlspecialchars($activity['user_name'] ?: 'Unknown') ?></small>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <small><?= htmlspecialchars($activity['action']) ?></small>
                                                    </td>
                                                    <td>
                                                        <code class="small"><?= htmlspecialchars($activity['ip_address']) ?></code>
                                                    </td>
                                                    <td>
                                                        <span class="badge bg-<?= strpos($activity['action'], 'failed') !== false ? 'danger' : 'success' ?>">
                                                            <?= strpos($activity['action'], 'failed') !== false ? 'Failed' : 'Success' ?>
                                                        </span>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- Suspicious Activities -->
                <div class="col-lg-4 mb-4">
                    <div class="card">
                        <div class="card-header">
                            <h6><i class="fas fa-exclamation-triangle text-danger"></i> Suspicious Activities</h6>
                        </div>
                        <div class="card-body" style="max-height: 400px; overflow-y: auto;">
                            <?php if (empty($suspicious_activities)): ?>
                                <div class="text-center text-muted py-4">
                                    <i class="fas fa-check-circle fa-2x mb-2"></i>
                                    <p class="small">No suspicious activities detected</p>
                                </div>
                            <?php else: ?>
                                <?php foreach ($suspicious_activities as $activity): ?>
                                    <div class="alert alert-danger alert-sm p-2 mb-2">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div>
                                                <strong class="small"><?= htmlspecialchars($activity['action']) ?></strong><br>
                                                <small>
                                                    IP: <?= htmlspecialchars($activity['ip_address']) ?><br>
                                                    <?= date('M d, h:i A', strtotime($activity['created_at'])) ?>
                                                </small>
                                            </div>
                                            <button class="btn btn-sm btn-outline-danger" onclick="investigateActivity(<?= $activity['id'] ?>)">
                                                <i class="fas fa-search"></i>
                                            </button>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

<?php include 'footer.php'; ?>