<?php

if (! defined('ABSPATH')) {

    exit;

}

class CacheMeBaby {

    private static $instance = null;

    /**

     * Singleton instance

     */

    public static function get_instance() {

        if (null === self::$instance) {

            self::$instance = new self();

        }

        return self::$instance;

    }

    /**

     * Constructor: load dependencies, then set up plugin.

     */

    public function __construct() {

        // Load the split-out classes

        $this->load_dependencies();

        // When plugins are loaded, we initialize everything

        add_action('plugins_loaded', [$this, 'initialize_plugin']);

    }

    /**

     * Require our smaller class files

     */

    private function load_dependencies() {

        require_once CACHE_ME_BABY_PATH . 'includes/admin.php';

        require_once CACHE_ME_BABY_PATH . 'includes/cloudflare.php';

        require_once CACHE_ME_BABY_PATH . 'includes/cron.php';

    }

    /**

     * Instantiate classes & set up textdomain, etc.

     */

    public function initialize_plugin() {

        // Instantiate each “sub-class” so its hooks run

        new CacheMeBaby_Admin();

        new CacheMeBaby_Cloudflare();

        new CacheMeBaby_Cron();

        // Load plugin translations

        add_action('init', [$this, 'load_textdomain']);

    }

    /**

     * Load plugin translations

     */

    public function load_textdomain() {

        load_plugin_textdomain('cache-me-baby', false, dirname(plugin_basename(__FILE__)) . '/languages');

    }

    /**

     * Utility: Check if site is on Cloudflare

     * (Used by multiple classes, so we keep it here.)

     */

    public function is_cloudflare_nameservers() {

        $domain = parse_url(home_url(), PHP_URL_HOST);

        if (!$domain) {

            return false;

        }

        // Quick check via shell_exec

        $output = shell_exec("nslookup -type=NS $domain 8.8.8.8");

        if ($output && stripos($output, 'cloudflare') !== false) {

            return true;

        }

        // Fallback check via dns_get_record

        $dns_records = @dns_get_record($domain, DNS_NS);

        if (empty($dns_records)) {

            return false;

        }

        foreach ($dns_records as $record) {

            if (!empty($record['target']) && stripos($record['target'], 'cloudflare') !== false) {

                return true;

            }

        }

        return false;

    }

}