<?php

namespace App\Core;

/**
 * Security Headers - إضافة رؤوس الأمان للاستجابات
 */
class SecurityHeaders
{
    /**
     * إضافة جميع Security Headers
     */
    public static function setAll(): void
    {
        // X-Frame-Options: منع Clickjacking
        header('X-Frame-Options: DENY');
        
        // X-Content-Type-Options: منع MIME sniffing
        header('X-Content-Type-Options: nosniff');
        
        // X-XSS-Protection: تفعيل XSS filter في المتصفح
        header('X-XSS-Protection: 1; mode=block');
        
        // Referrer-Policy: التحكم في معلومات Referrer
        header('Referrer-Policy: strict-origin-when-cross-origin');
        
        // Content-Security-Policy: منع XSS و injection attacks
        $csp = "default-src 'self'; " .
               "script-src 'self' 'unsafe-inline' 'unsafe-eval' https://barcode.tec-it.com; " .
               "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; " .
               "img-src 'self' data: https:; " .
               "font-src 'self' data: https://fonts.gstatic.com; " .
               "connect-src 'self'; " .
               "frame-ancestors 'none'; " .
               "base-uri 'self'; " .
               "form-action 'self'; " .
               "upgrade-insecure-requests;";
        header('Content-Security-Policy: ' . $csp);
        
        // Strict-Transport-Security: إجبار HTTPS (فقط في HTTPS)
        if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
            header('Strict-Transport-Security: max-age=31536000; includeSubDomains; preload');
        }
        
        // Permissions-Policy: التحكم في الميزات المتاحة
        header('Permissions-Policy: geolocation=(), microphone=(), camera=()');
    }
    
    /**
     * إضافة Security Headers للـ API responses
     */
    public static function setForApi(): void
    {
        self::setAll();
        
        // إضافة headers خاصة بالـ API
        header('X-Content-Type-Options: nosniff');
        header('X-API-Version: 1.0');
    }
    
    /**
     * إضافة Security Headers للـ public pages
     */
    public static function setForPublic(): void
    {
        // نفس الـ headers لكن مع CSP أقل تقييداً للـ public pages
        header('X-Frame-Options: SAMEORIGIN');
        header('X-Content-Type-Options: nosniff');
        header('X-XSS-Protection: 1; mode=block');
        header('Referrer-Policy: strict-origin-when-cross-origin');
        
        $csp = "default-src 'self'; " .
               "script-src 'self' 'unsafe-inline' https://barcode.tec-it.com; " .
               "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; " .
               "img-src 'self' data: https:; " .
               "font-src 'self' data: https://fonts.gstatic.com; " .
               "connect-src 'self'; " .
               "form-action 'self';";
        header('Content-Security-Policy: ' . $csp);
    }
}
