<?php
require_once '../config/database.php';
require_once '../config/auth.php';
require_once '../config/payment_security.php';
require_once '../includes/functions.php';

requireLogin();

// Check if user is admin
$currentUser = getCurrentUser();
if ($currentUser['role'] !== 'admin') {
    header('Location: dashboard.php');
    exit;
}

$success = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['run_compliance_check'])) {
    try {
        $report = PCICompliance::generateComplianceReport();
        $success = 'PCI DSS compliance check completed successfully.';
    } catch (Exception $e) {
        $error = 'Error running compliance check: ' . $e->getMessage();
    }
}

// Get latest compliance report
$db = getDB();
$stmt = $db->query("
    SELECT * FROM payment_logs
    WHERE action = 'pci_compliance_check'
    ORDER BY created_at DESC LIMIT 1
");
$latestReport = $stmt->fetch();

$complianceData = null;
if ($latestReport) {
    $complianceData = json_decode($latestReport['context'], true);
}

$page_title = 'PCI DSS Compliance';
include 'includes/admin_header.php';
?>

<?php if ($error): ?>
    <div class="alert alert-error">
        <?php echo htmlspecialchars($error); ?>
    </div>
<?php endif; ?>

<?php if ($success): ?>
    <div class="alert alert-success">
        <?php echo htmlspecialchars($success); ?>
    </div>
<?php endif; ?>

<div class="compliance-section">
    <h2>PCI DSS Compliance Dashboard</h2>
    <p class="settings-description">Monitor and maintain PCI DSS compliance for payment processing. This system implements SAQ A compliance level for merchants not storing card data.</p>

    <!-- Compliance Status Overview -->
    <div class="settings-card">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h3>Compliance Status</h3>
            <form method="POST" class="d-inline">
                <button type="submit" name="run_compliance_check" class="btn btn-primary">
                    <i class="fas fa-sync-alt me-2"></i>Run Compliance Check
                </button>
            </form>
        </div>

        <?php if ($complianceData): ?>
            <div class="compliance-status">
                <div class="status-indicator <?php echo $complianceData['compliant'] ? 'compliant' : 'non-compliant'; ?>">
                    <i class="fas fa-<?php echo $complianceData['compliant'] ? 'check-circle' : 'exclamation-triangle'; ?>"></i>
                    <span><?php echo $complianceData['compliant'] ? 'Compliant' : 'Non-Compliant'; ?></span>
                </div>
                <div class="compliance-details">
                    <div class="detail-item">
                        <strong>Compliance Level:</strong> <?php echo htmlspecialchars($complianceData['compliance_level']); ?>
                    </div>
                    <div class="detail-item">
                        <strong>Last Check:</strong> <?php echo date('M j, Y H:i', strtotime($complianceData['check_date'])); ?>
                    </div>
                    <div class="detail-item">
                        <strong>Issues Found:</strong> <?php echo count($complianceData['issues']); ?>
                    </div>
                </div>
            </div>

            <?php if (!empty($complianceData['issues'])): ?>
                <div class="compliance-issues">
                    <h4>Compliance Issues</h4>
                    <ul class="issues-list">
                        <?php foreach ($complianceData['issues'] as $issue): ?>
                            <li class="issue-item">
                                <i class="fas fa-exclamation-circle text-warning"></i>
                                <?php echo htmlspecialchars($issue); ?>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>
        <?php else: ?>
            <div class="no-data">
                <i class="fas fa-info-circle fa-3x text-muted mb-3"></i>
                <h4>No Compliance Check Run</h4>
                <p>Click "Run Compliance Check" to perform a PCI DSS compliance assessment.</p>
            </div>
        <?php endif; ?>
    </div>

    <!-- Security Measures Overview -->
    <div class="settings-card">
        <h3>Implemented Security Measures</h3>
        <div class="security-measures">
            <div class="measure-category">
                <h4><i class="fas fa-shield-alt text-primary"></i> Data Protection</h4>
                <ul>
                    <li><i class="fas fa-check text-success"></i> No sensitive card data stored</li>
                    <li><i class="fas fa-check text-success"></i> Encrypted temporary data storage</li>
                    <li><i class="fas fa-check text-success"></i> Secure data sanitization</li>
                    <li><i class="fas fa-check text-success"></i> Input validation and filtering</li>
                </ul>
            </div>

            <div class="measure-category">
                <h4><i class="fas fa-lock text-primary"></i> Access Control</h4>
                <ul>
                    <li><i class="fas fa-check text-success"></i> HTTPS enforcement</li>
                    <li><i class="fas fa-check text-success"></i> Rate limiting on payment requests</li>
                    <li><i class="fas fa-check text-success"></i> CSRF protection</li>
                    <li><i class="fas fa-check text-success"></i> Session-based security</li>
                </ul>
            </div>

            <div class="measure-category">
                <h4><i class="fas fa-eye text-primary"></i> Monitoring & Logging</h4>
                <ul>
                    <li><i class="fas fa-check text-success"></i> Comprehensive audit logging</li>
                    <li><i class="fas fa-check text-success"></i> Security event tracking</li>
                    <li><i class="fas fa-check text-success"></i> Failed payment notifications</li>
                    <li><i class="fas fa-check text-success"></i> Automated compliance checks</li>
                </ul>
            </div>

            <div class="measure-category">
                <h4><i class="fas fa-network-wired text-primary"></i> Network Security</h4>
                <ul>
                    <li><i class="fas fa-check text-success"></i> Security headers (HSTS, CSP, etc.)</li>
                    <li><i class="fas fa-check text-success"></i> XSS protection</li>
                    <li><i class="fas fa-check text-success"></i> Clickjacking prevention</li>
                    <li><i class="fas fa-check text-success"></i> Content type validation</li>
                </ul>
            </div>
        </div>
    </div>

    <!-- Security Recommendations -->
    <div class="settings-card">
        <h3>Security Recommendations</h3>
        <div class="recommendations">
            <div class="recommendation-item">
                <h5><i class="fas fa-server text-info"></i> Server Configuration</h5>
                <ul>
                    <li>Ensure SSL/TLS certificates are valid and up-to-date</li>
                    <li>Configure web server to use only secure protocols (TLS 1.2+)</li>
                    <li>Implement regular security updates and patches</li>
                    <li>Use a web application firewall (WAF)</li>
                </ul>
            </div>

            <div class="recommendation-item">
                <h5><i class="fas fa-key text-info"></i> Payment Gateway Security</h5>
                <ul>
                    <li>Regularly rotate API keys and credentials</li>
                    <li>Use separate sandbox and production environments</li>
                    <li>Monitor payment gateway security advisories</li>
                    <li>Implement webhook signature verification</li>
                </ul>
            </div>

            <div class="recommendation-item">
                <h5><i class="fas fa-user-shield text-info"></i> Access Management</h5>
                <ul>
                    <li>Implement multi-factor authentication for admin accounts</li>
                    <li>Use strong password policies</li>
                    <li>Regularly review and revoke unnecessary access</li>
                    <li>Implement session timeouts</li>
                </ul>
            </div>

            <div class="recommendation-item">
                <h5><i class="fas fa-database text-info"></i> Data Protection</h5>
                <ul>
                    <li>Regular database backups with encryption</li>
                    <li>Implement database access controls</li>
                    <li>Regular security audits and penetration testing</li>
                    <li>Data minimization - only store necessary information</li>
                </ul>
            </div>
        </div>
    </div>

    <!-- Recent Security Events -->
    <div class="settings-card">
        <h3>Recent Security Events</h3>
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Event Type</th>
                        <th>Message</th>
                        <th>IP Address</th>
                        <th>Date/Time</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $stmt = $db->query("
                        SELECT * FROM payment_logs
                        WHERE level = 'warning' AND action LIKE 'security_%'
                        ORDER BY created_at DESC LIMIT 10
                    ");
                    $securityEvents = $stmt->fetchAll();

                    if (empty($securityEvents)): ?>
                        <tr>
                            <td colspan="4" class="text-center py-4">
                                <i class="fas fa-shield-alt fa-3x text-success mb-3"></i>
                                <p class="text-muted">No security events detected. System is secure.</p>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($securityEvents as $event): ?>
                            <tr>
                                <td>
                                    <span class="badge bg-warning">
                                        <?php echo htmlspecialchars(str_replace('security_', '', $event['action'])); ?>
                                    </span>
                                </td>
                                <td><?php echo htmlspecialchars($event['message']); ?></td>
                                <td><?php echo htmlspecialchars($event['ip_address'] ?: 'N/A'); ?></td>
                                <td><?php echo date('M j, Y H:i', strtotime($event['created_at'])); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<style>
.compliance-section {
    max-width: 1400px;
}

.settings-description {
    color: #64748b;
    margin-bottom: 2rem;
    font-size: 0.875rem;
}

.settings-card {
    background: white;
    padding: 2rem;
    border-radius: 0.75rem;
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
    margin-bottom: 2rem;
}

.settings-card h3 {
    font-size: 1.25rem;
    font-weight: 600;
    color: #1f2937;
    margin-bottom: 1.5rem;
}

.compliance-status {
    display: flex;
    align-items: center;
    gap: 2rem;
    margin-bottom: 2rem;
}

.status-indicator {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 1rem;
    border-radius: 0.5rem;
    font-weight: 600;
    font-size: 1.125rem;
}

.status-indicator.compliant {
    background-color: #d1fae5;
    color: #10b981;
}

.status-indicator.non-compliant {
    background-color: #fee2e2;
    color: #dc2626;
}

.compliance-details {
    display: flex;
    gap: 2rem;
}

.detail-item {
    font-size: 0.875rem;
    color: #6b7280;
}

.compliance-issues {
    background-color: #fef3c7;
    border: 1px solid #f59e0b;
    border-radius: 0.5rem;
    padding: 1.5rem;
}

.compliance-issues h4 {
    color: #92400e;
    margin-bottom: 1rem;
}

.issues-list {
    list-style: none;
    padding: 0;
    margin: 0;
}

.issue-item {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.5rem 0;
    color: #92400e;
}

.no-data {
    text-align: center;
    padding: 3rem;
}

.security-measures {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 2rem;
}

.measure-category h4 {
    color: #1f2937;
    margin-bottom: 1rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.measure-category ul {
    list-style: none;
    padding: 0;
    margin: 0;
}

.measure-category li {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.25rem 0;
    color: #374151;
}

.recommendations {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 2rem;
}

.recommendation-item {
    background-color: #f8f9fa;
    padding: 1.5rem;
    border-radius: 0.5rem;
    border-left: 4px solid #3b82f6;
}

.recommendation-item h5 {
    color: #1f2937;
    margin-bottom: 1rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.recommendation-item ul {
    margin: 0;
    padding-left: 1.5rem;
}

.recommendation-item li {
    margin-bottom: 0.5rem;
    color: #6b7280;
}

.table {
    margin-bottom: 0;
}

.table th {
    background-color: #f8f9fa;
    font-weight: 600;
    color: #374151;
    border-top: none;
    padding: 1rem;
}

.table td {
    padding: 1rem;
    vertical-align: middle;
}

.badge {
    display: inline-block;
    padding: 0.25rem 0.5rem;
    font-size: 0.75rem;
    font-weight: 600;
    border-radius: 0.25rem;
}

.btn {
    padding: 0.5rem 1rem;
    border: none;
    border-radius: 0.375rem;
    font-size: 0.875rem;
    font-weight: 500;
    cursor: pointer;
    text-decoration: none;
    display: inline-block;
}

.btn-primary {
    background-color: #2563eb;
    color: white;
}

.btn-primary:hover {
    background-color: #1d4ed8;
}

.alert {
    padding: 1rem;
    border-radius: 0.5rem;
    margin-bottom: 1rem;
}

.alert-error {
    background-color: #fef2f2;
    border: 1px solid #fecaca;
    color: #dc2626;
}

.alert-success {
    background-color: #f0fdf4;
    border: 1px solid #bbf7d0;
    color: #16a34a;
}

@media (max-width: 768px) {
    .compliance-status {
        flex-direction: column;
        align-items: flex-start;
        gap: 1rem;
    }

    .compliance-details {
        flex-direction: column;
        gap: 0.5rem;
    }

    .security-measures,
    .recommendations {
        grid-template-columns: 1fr;
    }
}
</style>

<?php include 'includes/admin_footer.php'; ?>