<?php
/**
 * ================================================================
 * DRIPBOX LINK CHECKER - CRON WITH DEBUG LOGS
 * ================================================================
 */

if (!defined('ABSPATH')) {
    exit;
}

class DripBox_Link_Checker_Cron {
    
    private static $instance = null;
    
    // Configurações do Batch
    const BATCH_SIZE = 15; 
    const BATCH_INTERVAL = 120; // 2 minutos
    
    public static function get_instance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        add_action('dripbox_weekly_scan_event', [$this, 'init_weekly_scan']);
        add_action('dripbox_process_batch_event', [$this, 'process_batch']);
        add_filter('wp_mail_content_type', function() { return 'text/html'; });
    }
    
    private function log($message) {
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('[DripBox Cron] ' . $message);
        }
    }
    
    public function init_weekly_scan() {
        $this->log('>>> INICIANDO SCAN SEMANAL <<<');
        
        $enabled = get_option('dripbox_auto_scan_enabled', 0);
        if (!$enabled) {
            $this->log('Abortado: Auto-Scan está desligado nas opções.');
            return;
        }

        // === CORREÇÃO: Carrega o Scanner manualmente ===
        // O Cron não carrega arquivos de admin nativamente, então forçamos aqui.
        if (!class_exists('DripBox_Link_Checker_Scanner')) {
            // Sobe um nível (../) e entra em admin/class-scanner.php
            require_once dirname( __DIR__ ) . '/admin/class-scanner.php';
        }

        $scanner = DripBox_Link_Checker_Scanner::get_instance();
        $links = $scanner->find_all_links();
        
        if (empty($links)) {
            $this->log('Abortado: Nenhum link encontrado no scanner.');
            return;
        }
        
        $this->log('Links encontrados para processar: ' . count($links));
        
        update_option('dripbox_scan_queue', $links, 'no');
        update_option('dripbox_scan_results_temp', [], 'no');
        update_option('dripbox_scan_in_progress', true, 'no');
        
        if (!wp_next_scheduled('dripbox_process_batch_event')) {
            wp_schedule_single_event(time(), 'dripbox_process_batch_event');
            $this->log('Evento de lote (Batch) agendado para AGORA.');
        }
    }
    
    public function process_batch() {
        $this->log('--- Processando Lote ---');
        $queue = get_option('dripbox_scan_queue', []);
        
        if (empty($queue)) {
            $this->log('Fila vazia. Finalizando scan.');
            $this->finish_scan();
            return;
        }
        
        $batch = array_slice($queue, 0, self::BATCH_SIZE);
        $remaining = array_slice($queue, self::BATCH_SIZE);
        $current_results = get_option('dripbox_scan_results_temp', []);
        
        $this->log('Processando ' . count($batch) . ' links neste lote.');
        
        foreach ($batch as $link_data) {
            // Verifica URL
            $check_result = $this->verify_url_internal($link_data['url']);
            
            $this->log('Link verificado: ' . $link_data['url'] . ' | Status: ' . $check_result['status']);
            
            $final_result = array_merge($check_result, [
                'post_id'    => $link_data['post_id'],
                'post_title' => $link_data['post_title'],
                'post_url'   => $link_data['post_url'],
                'url'        => $link_data['url']
            ]);
            
            $current_results[] = $final_result;
        }
        
        update_option('dripbox_scan_results_temp', $current_results, 'no');
        update_option('dripbox_scan_queue', $remaining, 'no');
        
        if (!empty($remaining)) {
            wp_schedule_single_event(time() + self::BATCH_INTERVAL, 'dripbox_process_batch_event');
            $this->log('Ainda restam ' . count($remaining) . ' links. Próximo lote agendado.');
        } else {
            $this->log('Todos os links processados. Finalizando.');
            $this->finish_scan();
        }
    }
    
    private function finish_scan() {
        $final_results = get_option('dripbox_scan_results_temp', []);
        
        $db = DripBox_Link_Checker_DB::get_instance();
        $db->save_results($final_results);
        
        delete_option('dripbox_scan_queue');
        delete_option('dripbox_scan_results_temp');
        delete_option('dripbox_scan_in_progress');
        
        $this->log('Resultados salvos no banco.');
        
        $email_enabled = get_option('dripbox_email_alerts_enabled', 0);
        if ($email_enabled) {
            $this->log('Email Alerts está LIGADO. Verificando necessidade de envio...');
            $this->maybe_send_email($final_results);
        } else {
            $this->log('Email Alerts está DESLIGADO. Nenhum e-mail será enviado.');
        }
    }
    
    /**
     * Lógica de E-mail (PREMIUM TEMPLATE)
     */
/**
     * Lógica de E-mail (FINAL ADJUSTMENT - V2 Structure + Dark Mode & Styling)
     */
    private function maybe_send_email($results) {
        $broken = array_filter($results, function($r) { return $r['status'] === 'broken'; });
        $risky  = array_filter($results, function($r) { return $r['status'] === 'risky'; });
        
        $count_broken = count($broken);
        $count_risky = count($risky);
        
        $this->log("Resumo: Quebrados ($count_broken) | Risky ($count_risky)");
        
        if ($count_broken === 0 && $count_risky === 0) return;
        
        $admin_email = get_option('admin_email');
        $site_name = get_bloginfo('name');
        
        // Cores
        $logo_url = 'http://getdripbox.com/wp-content/uploads/2025/12/logo_grande_preta_transparente.webp';
        $color_orange_btn = '#f55e00';
        $color_bg_body = '#fff'; // Fundo Escuro
        
        $subject = "⚠️ Action Required: DripBox found {$count_broken} broken links on {$site_name}";
        
        // === EMAIL START ===
        // Fonte Helvetica Neue Light (fina)
        $message  = '<div style="background-color: ' . $color_bg_body . '; padding: 60px 0; font-family: \'Helvetica Neue\', Helvetica, Arial, sans-serif; font-weight: 300; color: #374151;">';
        $message .= '<div style="max-width: 600px; margin: 0 auto; background: #ffffff; border-radius: 12px; box-shadow: 0 10px 30px rgba(0,0,0,0.3); overflow: hidden;">';
        
        // 1. HEADER (Faixa Laranja Translúcida + Logo Grande)
        // Usando RGBA para transparência, com fallback
        $message .= '<div style="background-color: #ff9900; background-color: rgba(255, 153, 0, 0.5); padding: 40px 20px; text-align: center;">';
        $message .= '<img src="' . $logo_url . '" alt="DripBox" style="height: 90px; width: auto; display: block; margin: 0 auto;">';
        $message .= '</div>';
        
        // 2. BODY PADDING
        $message .= '<div style="padding: 40px;">';
        
        // Título H1 (Abaixo do header)
        $message .= '<h1 style="margin: 0 0 25px 0; font-size: 24px; font-weight: 300; color: #111; text-align: center; letter-spacing: -0.5px;">Revenue Protection Alert</h1>';
        
        // Copy Original (V2)
        $message .= '<p style="font-size: 16px; line-height: 1.6; margin-top: 0;">Hey there,</p>';
        $message .= '<p style="font-size: 16px; line-height: 1.6;">I have some bad news and some good news.</p>';
        $message .= '<p style="font-size: 16px; line-height: 1.6;">The bad news is we found broken links on your site. The good news is that <strong>DripBox</strong> caught them before you lost any revenue.</p>';
        
        // 3. STATS BOX (Estilo "Print 2": Centralizado com Divisor)
        $message .= '<div style="background: #ffffff; border: 1px solid #e5e7eb; border-radius: 12px; padding: 25px 0; margin: 30px 0; display: flex; align-items: center; justify-content: center;">';
        
        // Coluna 1: Broken (Com borda na direita servindo de divisor)
        $message .= '<div style="text-align: center; width: 50%; border-right: 1px solid #e5e7eb;">';
        $message .= '<span style="font-size: 36px; font-weight: 700; color: #dc2626; display: block; line-height: 1; margin-bottom: 6px;">' . $count_broken . '</span>';
        $message .= '<span style="font-size: 11px; font-weight: 700; color: #6b7280; text-transform: uppercase; letter-spacing: 0.5px;">Broken Links</span>';
        $message .= '</div>';

        // Coluna 2: Risky
        $message .= '<div style="text-align: center; width: 50%;">';
        $message .= '<span style="font-size: 36px; font-weight: 700; color: #d97706; display: block; line-height: 1; margin-bottom: 6px;">' . $count_risky . '</span>';
        $message .= '<span style="font-size: 11px; font-weight: 700; color: #6b7280; text-transform: uppercase; letter-spacing: 0.5px;">Risky Links</span>';
        $message .= '</div>';
        
        $message .= '</div>';
        
        // 4. THE LIST (Estilo V2 restaurado: Borda Vermelha na Esquerda + Centralizado)
        if ($count_broken > 0) {
            $message .= '<h3 style="font-size: 16px; font-weight: 700; color: #111; margin-bottom: 15px;">🔥 Revenue at Risk</h3>';
            
            $preview = array_slice($broken, 0, 5);
            foreach ($preview as $item) {
                $shortcode = '[dripbox id="' . $item['post_id'] . '"]';
                
                // Container com Borda Vermelha (V2)
                $message .= '<div style="background: #fff; border: 1px solid #e5e7eb; border-left: 4px solid #dc2626; border-radius: 4px; padding: 20px; margin-bottom: 12px; text-align: center;">';
                
                // URL (Vermelha)
                $message .= '<div style="color: #dc2626; font-weight: 600; font-size: 14px; margin-bottom: 8px; word-break: break-all; font-family: monospace;">❌ ' . esc_html($item['url']) . '</div>';
                
                // Info (Centralizada)
                $message .= '<div style="font-size: 13px; color: #6b7280;">';
                $message .= 'Found in: <strong style="color: #374151;">' . esc_html($item['post_title']) . '</strong> ';
                $message .= '<span style="background: #f3f4f6; padding: 2px 6px; border-radius: 4px; font-family: monospace; font-size: 11px; margin-left: 5px; border: 1px solid #ddd;">' . $shortcode . '</span>';
                $message .= '</div>';
                
                $message .= '</div>'; // End Card
            }
            
            if ($count_broken > 5) {
                $message .= '<div style="text-align: center; font-size: 13px; color: #9ca3af; margin-top: 10px;">...and ' . ($count_broken - 5) . ' more links.</div>';
            }
        }
        
        // 5. CTA BUTTON
        $admin_link = admin_url('admin.php?page=dripbox-link-checker');
        $message .= '<div style="text-align: center; margin-top: 40px; margin-bottom: 30px;">';
        $message .= '<a href="' . $admin_link . '" style="background-color: ' . $color_orange_btn . '; color: #ffffff; text-decoration: none; padding: 15px 35px; border-radius: 6px; font-weight: 700; font-size: 16px; display: inline-block; box-shadow: 0 4px 6px rgba(245, 94, 0, 0.2);">Fix Broken Links Now</a>';
        $message .= '<p style="margin-top: 15px; font-size: 14px; color: #646970;">Secure your commissions.</p>';
        $message .= '</div>';
        
        // 6. SIGN OFF (Estilo Original V2 restaurado)
        $message .= '<p style="font-size: 16px; line-height: 1.6; color: #374151; margin-bottom: 0;">Cheers,</p>';
        $message .= '<p style="font-size: 16px; line-height: 1.6; font-weight: 700; margin-top: 5px; color: #111;">Rafa<br><span style="font-weight: 400; font-size: 14px; color: #6b7280;">CEO, DripBox</span></p>';
        
        $message .= '</div>'; // End Content Padding
        
        // 7. FOOTER
        $message .= '<div style="background-color: #f9fafb; padding: 20px; text-align: center; border-top: 1px solid #e5e7eb; font-size: 12px; color: #9ca3af;">';
        $message .= '<p style="margin: 0;">You received this email because <strong>Email Alerts</strong> is enabled in DripBox settings.</p>';
        $message .= '</div>';
        
        $message .= '</div>'; // End White Card
        $message .= '</div>'; // End Background
        
        wp_mail($admin_email, $subject, $message);
    }
    
    private function verify_url_internal($url) {
        // ... (MANTENHA A MESMA LÓGICA DE VERIFICAÇÃO QUE JÁ ESTAVA AQUI) ...
        // Vou resumir para não ficar gigante, mas use a mesma função de antes
        // Só certifique-se de copiar a função verify_url_internal do código anterior
        
        // REPETINDO A FUNÇÃO PARA FACILITAR:
        $current_domain = parse_url(get_site_url(), PHP_URL_HOST);
        $is_server = ($current_domain === 'getdripbox.com');
        
        if ($is_server && function_exists('dripbox_server_verify_link')) {
            return dripbox_server_verify_link($url);
        }
        
        $license_key = get_option('dripbox_license_key', '');
        if (empty($license_key)) {
            return ['status' => 'broken', 'http_code' => 0, 'label' => 'License missing'];
        }
        
        $response = wp_remote_post('https://getdripbox.com/wp-json/dripbox/v1/check-link', [
            'timeout' => 15,
            'headers' => ['Content-Type' => 'application/json'],
            'body' => json_encode(['license_key' => $license_key, 'url' => $url])
        ]);
        
        if (is_wp_error($response)) {
            return ['status' => 'broken', 'http_code' => 0, 'label' => 'Connection error'];
        }
        
        return json_decode(wp_remote_retrieve_body($response), true);
    }
}