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

// Check if user is logged in and is admin
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header('Location: ../login.php');
    exit;
}

// Get PHP security settings
$php_settings = [
    'display_errors' => ini_get('display_errors'),
    'log_errors' => ini_get('log_errors'),
    'error_reporting' => error_reporting(),
    'session.cookie_httponly' => ini_get('session.cookie_httponly'),
    'session.cookie_secure' => ini_get('session.cookie_secure'),
    'session.use_strict_mode' => ini_get('session.use_strict_mode'),
    'expose_php' => ini_get('expose_php'),
    'allow_url_fopen' => ini_get('allow_url_fopen'),
    'allow_url_include' => ini_get('allow_url_include'),
    'file_uploads' => ini_get('file_uploads'),
    'upload_max_filesize' => ini_get('upload_max_filesize'),
    'post_max_size' => ini_get('post_max_size'),
    'max_execution_time' => ini_get('max_execution_time'),
    'memory_limit' => ini_get('memory_limit'),
];

// Check file permissions
$critical_files = [
    '../../config/database.php',
    '../../.htaccess',
    '../.htaccess',
];

$file_permissions = [];
foreach ($critical_files as $file) {
    if (file_exists($file)) {
        $perms = fileperms($file);
        $file_permissions[$file] = [
            'exists' => true,
            'readable' => is_readable($file),
            'writable' => is_writable($file),
            'permissions' => substr(sprintf('%o', $perms), -4)
        ];
    } else {
        $file_permissions[$file] = ['exists' => false];
    }
}

// Check database connection security
$database = new Database();
$db = $database->getConnection();

// Security recommendations
$security_checks = [
    [
        'name' => 'عرض الأخطاء',
        'status' => !ini_get('display_errors'),
        'message' => ini_get('display_errors') ? 'يجب إيقاف عرض الأخطاء في بيئة الإنتاج' : 'معطل بشكل صحيح',
        'severity' => ini_get('display_errors') ? 'high' : 'safe'
    ],
    [
        'name' => 'تسجيل الأخطاء',
        'status' => ini_get('log_errors'),
        'message' => ini_get('log_errors') ? 'مفعل بشكل صحيح' : 'يجب تفعيل تسجيل الأخطاء',
        'severity' => ini_get('log_errors') ? 'safe' : 'medium'
    ],
    [
        'name' => 'HttpOnly Cookies',
        'status' => ini_get('session.cookie_httponly'),
        'message' => ini_get('session.cookie_httponly') ? 'مفعل بشكل صحيح' : 'يجب تفعيل HttpOnly للحماية من XSS',
        'severity' => ini_get('session.cookie_httponly') ? 'safe' : 'high'
    ],
    [
        'name' => 'Secure Cookies',
        'status' => ini_get('session.cookie_secure'),
        'message' => ini_get('session.cookie_secure') ? 'مفعل بشكل صحيح' : 'يجب تفعيل Secure Cookies عند استخدام HTTPS',
        'severity' => ini_get('session.cookie_secure') ? 'safe' : 'medium'
    ],
    [
        'name' => 'إخفاء معلومات PHP',
        'status' => !ini_get('expose_php'),
        'message' => ini_get('expose_php') ? 'يجب إخفاء معلومات PHP من الهيدر' : 'مخفي بشكل صحيح',
        'severity' => ini_get('expose_php') ? 'low' : 'safe'
    ],
    [
        'name' => 'allow_url_include',
        'status' => !ini_get('allow_url_include'),
        'message' => ini_get('allow_url_include') ? 'يجب تعطيل allow_url_include لمنع هجمات RFI' : 'معطل بشكل صحيح',
        'severity' => ini_get('allow_url_include') ? 'high' : 'safe'
    ],
];

// Calculate security score
$total_checks = count($security_checks);
$passed_checks = count(array_filter($security_checks, fn($check) => $check['status']));
$security_score = round(($passed_checks / $total_checks) * 100);
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>الأمان والحماية - Roz Skin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body {
            font-family: 'Tajawal', sans-serif;
        }
        .security-card {
            transition: all 0.3s ease;
        }
        .security-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">

    <!-- Header -->
    <header class="bg-white shadow-sm border-b border-gray-200 sticky top-0 z-20">
        <div class="flex items-center justify-between px-6 py-4">
            <div class="flex items-center space-x-4 space-x-reverse">
                <a href="../dashboard.php" class="text-gray-600 hover:text-gray-900">
                    <i class="fas fa-arrow-right text-xl"></i>
                </a>
                <div>
                    <h1 class="text-2xl font-bold text-gray-900">الأمان والحماية</h1>
                    <p class="text-sm text-gray-500">مراقبة وإدارة إعدادات الأمان</p>
                </div>
            </div>
            <div class="flex items-center space-x-4 space-x-reverse">
                <a href="../../public/index.php" class="text-gray-600 hover:text-gray-900" title="المتجر">
                    <i class="fas fa-store text-xl"></i>
                </a>
                <a href="../logout.php" class="text-gray-600 hover:text-red-600" title="تسجيل الخروج">
                    <i class="fas fa-sign-out-alt text-xl"></i>
                </a>
            </div>
        </div>
    </header>

    <!-- Main Content -->
    <div class="max-w-7xl mx-auto p-6">
        
        <!-- Security Score -->
        <div class="bg-gradient-to-br from-blue-500 to-purple-600 rounded-xl shadow-lg p-8 mb-8 text-white">
            <div class="flex items-center justify-between">
                <div>
                    <h2 class="text-3xl font-bold mb-2">درجة الأمان</h2>
                    <p class="text-blue-100">تقييم شامل لإعدادات الأمان في النظام</p>
                </div>
                <div class="text-center">
                    <div class="relative inline-flex items-center justify-center w-32 h-32">
                        <svg class="transform -rotate-90 w-32 h-32">
                            <circle cx="64" cy="64" r="56" stroke="rgba(255,255,255,0.2)" stroke-width="8" fill="none" />
                            <circle cx="64" cy="64" r="56" stroke="white" stroke-width="8" fill="none"
                                    stroke-dasharray="<?php echo 2 * 3.14159 * 56; ?>"
                                    stroke-dashoffset="<?php echo 2 * 3.14159 * 56 * (1 - $security_score / 100); ?>"
                                    stroke-linecap="round" />
                        </svg>
                        <div class="absolute">
                            <span class="text-4xl font-bold"><?php echo $security_score; ?>%</span>
                        </div>
                    </div>
                    <p class="mt-2 text-sm">
                        <?php 
                        if ($security_score >= 80) echo 'ممتاز';
                        elseif ($security_score >= 60) echo 'جيد';
                        elseif ($security_score >= 40) echo 'متوسط';
                        else echo 'يحتاج تحسين';
                        ?>
                    </p>
                </div>
            </div>
        </div>

        <!-- Security Checks -->
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-8">
            <h3 class="text-xl font-semibold text-gray-900 mb-6 flex items-center">
                <i class="fas fa-shield-alt text-blue-600 ml-3"></i>
                فحوصات الأمان
            </h3>
            <div class="space-y-4">
                <?php foreach ($security_checks as $check): ?>
                    <div class="security-card flex items-start p-4 rounded-lg border <?php 
                        echo $check['severity'] === 'safe' ? 'border-green-200 bg-green-50' : 
                             ($check['severity'] === 'high' ? 'border-red-200 bg-red-50' : 
                             ($check['severity'] === 'medium' ? 'border-orange-200 bg-orange-50' : 
                             'border-yellow-200 bg-yellow-50'));
                    ?>">
                        <div class="flex-shrink-0 ml-4">
                            <?php if ($check['status']): ?>
                                <i class="fas fa-check-circle text-green-600 text-2xl"></i>
                            <?php else: ?>
                                <i class="fas fa-exclamation-triangle text-<?php 
                                    echo $check['severity'] === 'high' ? 'red' : 
                                         ($check['severity'] === 'medium' ? 'orange' : 'yellow'); 
                                ?>-600 text-2xl"></i>
                            <?php endif; ?>
                        </div>
                        <div class="flex-1">
                            <h4 class="font-semibold text-gray-900 mb-1"><?php echo $check['name']; ?></h4>
                            <p class="text-sm text-gray-600"><?php echo $check['message']; ?></p>
                        </div>
                        <div class="flex-shrink-0">
                            <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium <?php 
                                echo $check['severity'] === 'safe' ? 'bg-green-100 text-green-800' : 
                                     ($check['severity'] === 'high' ? 'bg-red-100 text-red-800' : 
                                     ($check['severity'] === 'medium' ? 'bg-orange-100 text-orange-800' : 
                                     'bg-yellow-100 text-yellow-800'));
                            ?>">
                                <?php 
                                echo $check['severity'] === 'safe' ? 'آمن' : 
                                     ($check['severity'] === 'high' ? 'خطر عالي' : 
                                     ($check['severity'] === 'medium' ? 'خطر متوسط' : 'خطر منخفض'));
                                ?>
                            </span>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <!-- PHP Settings -->
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                <h3 class="text-xl font-semibold text-gray-900 mb-6 flex items-center">
                    <i class="fab fa-php text-purple-600 ml-3 text-2xl"></i>
                    إعدادات PHP
                </h3>
                <div class="space-y-3">
                    <?php foreach ($php_settings as $setting => $value): ?>
                        <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                            <span class="text-sm font-medium text-gray-700"><?php echo $setting; ?></span>
                            <code class="text-sm px-3 py-1 bg-gray-200 rounded font-mono">
                                <?php 
                                if (is_bool($value)) {
                                    echo $value ? 'مفعل' : 'معطل';
                                } else {
                                    echo htmlspecialchars($value);
                                }
                                ?>
                            </code>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- File Permissions -->
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                <h3 class="text-xl font-semibold text-gray-900 mb-6 flex items-center">
                    <i class="fas fa-lock text-red-600 ml-3"></i>
                    صلاحيات الملفات الحساسة
                </h3>
                <div class="space-y-3">
                    <?php foreach ($file_permissions as $file => $perms): ?>
                        <div class="p-3 bg-gray-50 rounded-lg">
                            <div class="flex items-center justify-between mb-2">
                                <span class="text-sm font-medium text-gray-700 truncate" title="<?php echo $file; ?>">
                                    <?php echo basename($file); ?>
                                </span>
                                <?php if ($perms['exists']): ?>
                                    <code class="text-xs px-2 py-1 bg-gray-200 rounded font-mono">
                                        <?php echo $perms['permissions']; ?>
                                    </code>
                                <?php else: ?>
                                    <span class="text-xs px-2 py-1 bg-red-100 text-red-800 rounded">غير موجود</span>
                                <?php endif; ?>
                            </div>
                            <?php if ($perms['exists']): ?>
                                <div class="flex items-center space-x-3 space-x-reverse text-xs">
                                    <span class="<?php echo $perms['readable'] ? 'text-green-600' : 'text-red-600'; ?>">
                                        <i class="fas fa-<?php echo $perms['readable'] ? 'check' : 'times'; ?> ml-1"></i>
                                        قراءة
                                    </span>
                                    <span class="<?php echo $perms['writable'] ? 'text-orange-600' : 'text-green-600'; ?>">
                                        <i class="fas fa-<?php echo $perms['writable'] ? 'exclamation-triangle' : 'check'; ?> ml-1"></i>
                                        كتابة
                                    </span>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Security Resources -->
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                <h3 class="text-xl font-semibold text-gray-900 mb-6 flex items-center">
                    <i class="fas fa-book text-blue-600 ml-3"></i>
                    مصادر الأمان
                </h3>
                <div class="space-y-3">
                    <a href="https://www.php.net/manual/en/security.php" target="_blank" 
                       class="flex items-center p-3 bg-blue-50 rounded-lg hover:bg-blue-100 transition-colors">
                        <i class="fab fa-php text-blue-600 text-xl ml-3"></i>
                        <div>
                            <div class="font-medium text-gray-900">دليل أمان PHP</div>
                            <div class="text-xs text-gray-600">التوثيق الرسمي لأمان PHP</div>
                        </div>
                        <i class="fas fa-external-link-alt text-gray-400 mr-auto"></i>
                    </a>

                    <a href="https://owasp.org/www-project-top-ten/" target="_blank" 
                       class="flex items-center p-3 bg-red-50 rounded-lg hover:bg-red-100 transition-colors">
                        <i class="fas fa-shield-alt text-red-600 text-xl ml-3"></i>
                        <div>
                            <div class="font-medium text-gray-900">OWASP Top 10</div>
                            <div class="text-xs text-gray-600">أهم 10 مخاطر أمنية في تطبيقات الويب</div>
                        </div>
                        <i class="fas fa-external-link-alt text-gray-400 mr-auto"></i>
                    </a>

                    <a href="https://cheatsheetseries.owasp.org/" target="_blank" 
                       class="flex items-center p-3 bg-green-50 rounded-lg hover:bg-green-100 transition-colors">
                        <i class="fas fa-file-alt text-green-600 text-xl ml-3"></i>
                        <div>
                            <div class="font-medium text-gray-900">OWASP Cheat Sheets</div>
                            <div class="text-xs text-gray-600">أدلة سريعة لأفضل ممارسات الأمان</div>
                        </div>
                        <i class="fas fa-external-link-alt text-gray-400 mr-auto"></i>
                    </a>

                    <a href="https://www.cloudflare.com/learning/security/what-is-web-application-security/" target="_blank" 
                       class="flex items-center p-3 bg-orange-50 rounded-lg hover:bg-orange-100 transition-colors">
                        <i class="fas fa-graduation-cap text-orange-600 text-xl ml-3"></i>
                        <div>
                            <div class="font-medium text-gray-900">تعلم أمان تطبيقات الويب</div>
                            <div class="text-xs text-gray-600">دروس ومقالات تعليمية</div>
                        </div>
                        <i class="fas fa-external-link-alt text-gray-400 mr-auto"></i>
                    </a>
                </div>
            </div>

            <!-- Security Best Practices -->
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                <h3 class="text-xl font-semibold text-gray-900 mb-6 flex items-center">
                    <i class="fas fa-lightbulb text-yellow-600 ml-3"></i>
                    أفضل الممارسات
                </h3>
                <div class="space-y-3">
                    <div class="flex items-start p-3 bg-gray-50 rounded-lg">
                        <i class="fas fa-check-circle text-green-600 ml-3 mt-1"></i>
                        <div>
                            <div class="font-medium text-gray-900 text-sm">استخدم HTTPS دائماً</div>
                            <div class="text-xs text-gray-600">تشفير جميع الاتصالات بين المستخدم والخادم</div>
                        </div>
                    </div>

                    <div class="flex items-start p-3 bg-gray-50 rounded-lg">
                        <i class="fas fa-check-circle text-green-600 ml-3 mt-1"></i>
                        <div>
                            <div class="font-medium text-gray-900 text-sm">تحديث النظام بانتظام</div>
                            <div class="text-xs text-gray-600">حافظ على تحديث PHP والمكتبات</div>
                        </div>
                    </div>

                    <div class="flex items-start p-3 bg-gray-50 rounded-lg">
                        <i class="fas fa-check-circle text-green-600 ml-3 mt-1"></i>
                        <div>
                            <div class="font-medium text-gray-900 text-sm">استخدم Prepared Statements</div>
                            <div class="text-xs text-gray-600">للحماية من هجمات SQL Injection</div>
                        </div>
                    </div>

                    <div class="flex items-start p-3 bg-gray-50 rounded-lg">
                        <i class="fas fa-check-circle text-green-600 ml-3 mt-1"></i>
                        <div>
                            <div class="font-medium text-gray-900 text-sm">تحقق من المدخلات</div>
                            <div class="text-xs text-gray-600">تحقق من جميع بيانات المستخدم قبل معالجتها</div>
                        </div>
                    </div>

                    <div class="flex items-start p-3 bg-gray-50 rounded-lg">
                        <i class="fas fa-check-circle text-green-600 ml-3 mt-1"></i>
                        <div>
                            <div class="font-medium text-gray-900 text-sm">نسخ احتياطي منتظم</div>
                            <div class="text-xs text-gray-600">احتفظ بنسخ احتياطية من قاعدة البيانات والملفات</div>
                        </div>
                    </div>

                    <div class="flex items-start p-3 bg-gray-50 rounded-lg">
                        <i class="fas fa-check-circle text-green-600 ml-3 mt-1"></i>
                        <div>
                            <div class="font-medium text-gray-900 text-sm">مراقبة السجلات</div>
                            <div class="text-xs text-gray-600">راقب سجلات الأخطاء والأنشطة المشبوهة</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- System Info -->
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mt-6">
            <h3 class="text-xl font-semibold text-gray-900 mb-6 flex items-center">
                <i class="fas fa-server text-gray-600 ml-3"></i>
                معلومات النظام
            </h3>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div class="p-4 bg-gray-50 rounded-lg">
                    <div class="text-sm text-gray-600 mb-1">إصدار PHP</div>
                    <div class="text-lg font-semibold text-gray-900"><?php echo phpversion(); ?></div>
                </div>
                <div class="p-4 bg-gray-50 rounded-lg">
                    <div class="text-sm text-gray-600 mb-1">نظام التشغيل</div>
                    <div class="text-lg font-semibold text-gray-900"><?php echo PHP_OS; ?></div>
                </div>
                <div class="p-4 bg-gray-50 rounded-lg">
                    <div class="text-sm text-gray-600 mb-1">الخادم</div>
                    <div class="text-lg font-semibold text-gray-900"><?php echo $_SERVER['SERVER_SOFTWARE'] ?? 'غير معروف'; ?></div>
                </div>
            </div>
        </div>
    </div>

</body>
</html>
