<?php
/**
 * Class Check_Status_Cloudflare
 * 
 * Memeriksa status akses ke situs target (terutama untuk mendeteksi pemblokiran Cloudflare)
 * dan menampilkan notifikasi yang sesuai (dengan atau tanpa API key)
 */
class Check_Status_Cloudflare {

    private $demo_url;
    private $source_domain;
    private $protocol;
    private $curl_handler;
    private $api_keys;
    private $allowed_statuses = [200, 201];

    /**
     * Constructor
     *
     * @param Go_Curl $curl_instance Instance dari class Go_Curl
     * @param string $demo_url URL contoh untuk pengecekan (harus merupakan halaman valid)
     * @param string $source_domain Domain target (contoh: '5play.org/en/')
     * @param array $api_keys Array API keys dari setting ($opt_themes['api_key_scrape'])
     */
    public function __construct(Go_Curl $curl_instance, $demo_url, $source_domain, $api_keys = []) {
        $this->curl_handler   = $curl_instance;
        $this->demo_url       = rtrim($demo_url, '/');
        $this->source_domain  = $source_domain;
        $this->api_keys       = (array) $api_keys;
        $this->protocol       = 'https://' . rtrim($source_domain, '/');
        
        // Ambil domain dari demo url untuk tampilan
        $this->target_host = parse_url($this->demo_url, PHP_URL_HOST) ?: 'target site';
    }

    /**
     * Jalankan pengecekan status
     * 
     * @return void
     */
    public function check_and_display() {
        $status_code = $this->curl_handler->http_responsex($this->demo_url);

        // Jika status sudah OK → tidak perlu tampilkan apa-apa
        if (in_array($status_code, $this->allowed_statuses)) {
            return;
        }

        // Status yang biasanya menandakan Cloudflare protection / redirect / error
        $cloudflare_like_codes = [301, 302, 303, 307, 308, 403];

        if (in_array($status_code, $cloudflare_like_codes)) {
            $this->display_cloudflare_blocked_message($status_code);
        } else {
            $this->display_general_error_message($status_code);
        }
    }

    /**
     * Tampilkan pesan ketika terdeteksi Cloudflare block
     */
    private function display_cloudflare_blocked_message($code) {
        $has_api_key = !empty($this->api_keys);

        ?>
        <div class="wrap">
            <div class="containerX" style="text-align:center; margin-top:40px;">
				<h2></h2>
				<h3></h3>	 
				<h2>Warning: Access Issue Detected</h2>

                <?php if ($has_api_key) : ?>
                    <div class="toast-notification" style="position:fixed; top:70px; right:20px; background:#333; color:#fff; padding:12px 20px; border-radius:8px; box-shadow:0 4px 12px rgba(0,0,0,0.2); z-index:9999; animation:toast 30s forwards;">
                        <p style="text-align:center; margin:5px 0;">Target site (<?= esc_html($this->target_host) ?>) is protected by Cloudflare</p>
                        <p style="text-align:center; margin:5px 0;">You're using API Key mode</p>
                        <input onclick="this.select()" readonly type="text" id="api_key_scrape" name="api_key_scrape" 
                               value="<?= esc_attr($this->get_random_api_key()) ?>" class="regular-text" 
                               style="text-align:center; display:block; margin:10px auto; width:280px;"/>
                    </div>
                <?php else : ?>
                    <div class="toast-notification" style="position:fixed; top:70px; right:20px; background:#c0392b; color:#fff; padding:12px 20px; border-radius:8px; box-shadow:0 4px 12px rgba(0,0,0,0.3); z-index:9999; animation:toast 40s forwards;">
                        <p style="text-align:center; margin:5px 0;"><strong>Sorry...</strong></p>
                        <p style="text-align:center; margin:5px 0;"><?= esc_html($this->target_host) ?> is blocked by Cloudflare</p>
                        <p style="text-align:center; margin:10px 0;">Please add your API key to continue scraping</p>
                        <p style="text-align:center; margin:5px 0;">
                            <a href="<?= esc_url(apikey_page) ?>" target="_blank" style="color:#fff; text-decoration:underline;">
                                → Click HERE to add API key ←
                            </a>
                        </p>
                    </div>
                <?php endif; ?>

                <h5 style="text-align:center;">
                    Status: <?= $code ?> 
                    <?php 
                    if ($code === 403) echo 'Forbidden (Cloudflare protection)';
                    elseif ($code === 301 || $code === 302) echo 'Redirect (possible Cloudflare check)';
                    else echo 'Other protection/redirect';
                    ?>
                </h5>
            </div>
        </div>
        <?php
    }

    /**
     * Tampilkan pesan error umum (bukan Cloudflare)
     */
    private function display_general_error_message($code) {
        $messages = [
            400 => 'Bad Request',
            404 => 'Not Found',
            500 => 'Internal Server Error',
            502 => 'Bad Gateway',
            503 => 'Service Unavailable',
        ];

        $message = $messages[$code] ?? 'Unknown Error';

        ?>
        <div class="wrap">
            <div class="containerX" style="text-align:center; margin-top:40px;">
				<h2></h2>
				<h3></h3>	 
                <h3 style="color:#e74c3c;">Connection Problem Detected</h3>
                <h5 style="color:#c0392b;">
                    Status: <?= esc_html($code) ?> — <?= esc_html($message) ?>
                </h5>
                <p style="color:#555; margin-top:15px;">
                    Target site may be down, moved, or has changed protection method.
                </p>
            </div>
        </div>
        <?php
    }

    /**
     * Ambil satu API key secara acak
     */
    private function get_random_api_key() {
        if (empty($this->api_keys)) {
            return '';
        }
        $rand_key = array_rand($this->api_keys);
        return $this->api_keys[$rand_key];
    }
}