<?php

/*
    Plugin Name:        Dragonizer Advanced Headers
    Plugin URI:         https://www.rtl-theme.com/dragonizer-wordpress-plugin
    Description:        This file sets HTTP security headers for the Dragonizer WordPress Plugin.
    Version:            1.0.0
    Author:             Dynamatic
    Author URI:         https://www.rtl-theme.com/author/mahyardyn
    License:            GPLv3
    License URI:        http://www.gnu.org/licenses/gpl-3.0.html
*/

defined('ABSPATH') or die('No script kiddies please!');

// Function to check if SSL is enabled
function dragonizer_is_ssl()
{
    $sslHeaders = [
        'HTTPS' => 'on',
        'SERVER_PORT' => 443,
        'HTTP_X_FORWARDED_PROTO' => 'https',
        'HTTP_X_FORWARDED_SSL' => 'on',
        'HTTP_FRONT_END_HTTPS' => 'on',
        'HTTP_X_URL_SCHEME' => 'https',
    ];

    // Check for SSL headers
    foreach ($sslHeaders as $header => $value) {
        if (isset($_SERVER[$header]) && strtolower($_SERVER[$header]) === $value) {
            return true;
        }
    }

    return false;
}

// Put headers here dynamically

// Check if the request is a WordPress REST API or AJAX request
$is_rest_or_ajax_request = isset($_SERVER["REQUEST_URI"]) &&
    ((strpos($_SERVER["REQUEST_URI"], "wp-json/") !== false && isset($_SERVER["HTTP_X_WP_NONCE"])) ||
        strpos($_SERVER["REQUEST_URI"], "admin-ajax.php") !== false);

// If it's not a REST or AJAX request, restrict the HTTP methods
if (!$is_rest_or_ajax_request) {
    $allowedMethods = ["GET", "POST", "HEAD", "OPTIONS"];
    $currentMethod = $_SERVER["REQUEST_METHOD"] ?? 'GET';  // Default to 'GET' if not set

    if (!in_array($currentMethod, $allowedMethods, true)) {
        header($_SERVER["SERVER_PROTOCOL"] ?? "HTTP/1.1" . " 405 Method Not Allowed", true, 405);
        exit;
    }
}
