<?php
/*
Plugin Name: DripBox Affiliate
Description: Smart affiliate boxes with clean design, quick setup and optimized conversions.
Version: 1.3.0
Author: Rafa de Atlanta
License: GPLv2 or later
*/

// ==========================================================
// 1. AUTOLOADER DO COMPOSER (Stripe SDK)
// ==========================================================
require_once __DIR__ . '/vendor/autoload.php';


// ==========================================================
// 2. SEGURANÇA E CONSTANTES DO PLUGIN
// ==========================================================
if (!defined('ABSPATH')) exit;

if (!defined('DRIPBOX_VERSION')) {
    define('DRIPBOX_VERSION', '5.0.1');
}

if (!defined('DRIPBOX_PLUGIN_FILE')) {
    define('DRIPBOX_PLUGIN_FILE', __FILE__);
}

// ============================================================================
// 2.1 GLOBAL LICENSE CHECKER (Engine Start)
// ============================================================================
// Roda no inicio (priority 1) para garantir que a constante exista antes de qualquer bloqueio.
add_action('plugins_loaded', 'dripbox_initialize_license_status', 1);

function dripbox_initialize_license_status() {
    // Se por acaso já definiram isso em outro lugar, a gente respeita e sai. (Anti-Conflito)
    if (defined('DRIPBOX_IS_PRO')) return;

    global $wpdb;
    $table = $wpdb->prefix . 'dripbox_licenses';

    // Proteção: Se a tabela não existe (instalação nova), considera FREE.
    if ($wpdb->get_var("SHOW TABLES LIKE '$table'") !== $table) {
        define('DRIPBOX_IS_PRO', false);
        return;
    }

    // Identifica o domínio atual (mesma lógica que usamos na tela de licença)
    $raw_host = parse_url(get_site_url(), PHP_URL_HOST);
    $site_domain = str_replace('www.', '', $raw_host);

    // Pergunta pro banco: Tem licença ativa pra esse domínio?
    $license = $wpdb->get_row($wpdb->prepare(
        "SELECT plan_level FROM {$table} WHERE domain LIKE %s AND status = 'active' LIMIT 1",
        '%' . $wpdb->esc_like($site_domain) . '%'
    ));

    // LIGA O INTERRUPTOR
    if ($license) {
        define('DRIPBOX_IS_PRO', true);
        define('DRIPBOX_PLAN_LEVEL', $license->plan_level);
    } else {
        define('DRIPBOX_IS_PRO', false);
        define('DRIPBOX_PLAN_LEVEL', 'free');
    }
}


// ==========================================================
// 3. CONSTANTES DO STRIPE (ATUALIZE COM SUAS CHAVES REAIS)
// ==========================================================
// arquivo .env             

// ==========================================================
// 4. REGISTRO DO ENDPOINT DO WEBHOOK (PARA O STRIPE ENVIAR EVENTOS)
// ==========================================================
add_action('rest_api_init', function () {
    register_rest_route('dripbox/v1', '/stripe-webhook', [
        'methods'             => 'POST',
        'callback'            => 'dripbox_stripe_webhook_handler',
        'permission_callback' => '__return_true', // Necessário p/ Stripe enviar POST sem login
    ]);
});


// ============================================================================
// 5. ENDPOINT HÍBRIDO (TRACKING COMPLETO)
// ============================================================================
add_action('rest_api_init', function () {
    register_rest_route('dripbox/v1', '/track', [
        'methods'  => 'POST',
        'callback' => 'dripbox_track_click_hybrid',
        'permission_callback' => '__return_true'
    ]);
});

function dripbox_track_click_hybrid(WP_REST_Request $request) {
    global $wpdb;
    $params = $request->get_json_params();

    // 1. SALVAR NO ANALYTICS LOCAL (Cliente)
    // Precisamos do ID numérico e do tipo de botão
    $product_id = intval($params['product_id'] ?? 0);
    $platform   = sanitize_text_field($params['platform'] ?? 'other');

    if ($product_id > 0) {
        $table_local = $wpdb->prefix . 'dripbox_clicks';
        $today = current_time('Y-m-d');
        
        // Verifica se já existe contagem hoje para este produto/plataforma
        $row_id = $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM $table_local WHERE product_id=%d AND button_type=%s AND date=%s",
            $product_id, $platform, $today
        ));

        if ($row_id) {
            // Incrementa
            $wpdb->query($wpdb->prepare("UPDATE $table_local SET total_clicks = total_clicks + 1 WHERE id=%d", $row_id));
        } else {
            // Cria novo
            $wpdb->insert($table_local, [
                'product_id'   => $product_id,
                'button_type'  => $platform,
                'date'         => $today,
                'total_clicks' => 1
            ]);
        }
    }
    
    // 2. ENVIAR PARA O GLOBAL (Você)
    // Dispara e esquece (non-blocking) para não deixar o site lento
    wp_remote_post('https://getdripbox.com/wp-json/dripbox/v1/track', [
        'blocking' => false,
        'timeout'  => 5,
        'headers'  => ['Content-Type' => 'application/json'],
        'body'     => json_encode($params),
        'sslverify' => false 
    ]);

    return ['success' => true];
}

// ==========================================================
// 6. IMPORTA SISTEMA DE LICENÇAS
// ==========================================================
require_once plugin_dir_path(__FILE__) . 'includes/license.php';
require_once plugin_dir_path(__FILE__) . 'includes/verify-license.php';


// ==========================================================
// 6.1 LINK CHECKER MODULE
// ==========================================================
require_once plugin_dir_path(__FILE__) . 'includes/link-checker/class-link-checker.php';

// ==========================================================
// 6.2 LINK CHECKER AUTOMATION (CRON)
// ==========================================================
// Ajuste o caminho se você colocou em outra pasta (ex: 'core')
require_once plugin_dir_path(__FILE__) . 'includes/link-checker/core/class-cron.php'; 

// Inicia o Cron (O Motor de Automação)
DripBox_Link_Checker_Cron::get_instance();

// ==========================================================
// 6.3 LASSO IMPORTER
// ==========================================================
// Lasso Importer (after license includes)
require_once plugin_dir_path(__FILE__) . 'includes/lasso-importer/class-lasso-importer.php';

// ==========================================================
// 7. IMPORTA TABELAS / COMPONENTES DO PLUGIN
// ==========================================================
require_once plugin_dir_path(__FILE__) . 'dripbox-table.php';


// ==========================================================
// 8. CRIAÇÃO DA TABELA DE LICENÇAS
// ==========================================================
register_activation_hook(__FILE__, 'dripbox_create_license_table');

// ==========================================================
// 8.1 CRIAÇÃO DA TABELA DE LOGS
// ==========================================================
function dripbox_create_logs_table() {
    global $wpdb;

    $table = $wpdb->prefix . 'dripbox_logs';
    $charset = $wpdb->get_charset_collate();

    $sql = "
    CREATE TABLE IF NOT EXISTS $table (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        event_type VARCHAR(50) NOT NULL,
        license_key VARCHAR(100) NULL,
        email VARCHAR(200) NULL,
        domain VARCHAR(200) NULL,
        details TEXT NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id)
    ) $charset;
    ";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}

register_activation_hook(__FILE__, 'dripbox_create_logs_table');


// ==========================================================
// 8.2 CRIAÇÃO DA TABELA DE DOMÍNIOS
// ==========================================================
function dripbox_create_domain_table() {
    global $wpdb;

    $table = $wpdb->prefix . 'dripbox_domains';
    $charset = $wpdb->get_charset_collate();

    $sql = "
    CREATE TABLE IF NOT EXISTS $table (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        license_key VARCHAR(100) NOT NULL,
        domain VARCHAR(200) NOT NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id)
    ) $charset;
    ";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}

register_activation_hook(__FILE__, 'dripbox_create_domain_table');


// ==========================================================
// 8.3 CRIAÇÃO DA TABELA DE ANALYTICS
// ==========================================================
function dripbox_create_clicks_table() {
    global $wpdb;

    $table = $wpdb->prefix . 'dripbox_clicks';
    $charset = $wpdb->get_charset_collate();

    $sql = "
        CREATE TABLE IF NOT EXISTS $table (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            product_id BIGINT UNSIGNED NOT NULL,
            button_type VARCHAR(20) NOT NULL,
            date DATE NOT NULL,
            total_clicks INT NOT NULL DEFAULT 1,
            PRIMARY KEY (id),
            KEY product_button_date (product_id, button_type, date)
        ) $charset;
    ";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}
register_activation_hook(__FILE__, 'dripbox_create_clicks_table');


// ==========================================================
// 9. SISTEMA DE UPDATE CHECKER
// ==========================================================
require_once plugin_dir_path(__FILE__) . 'includes/update-checker.php';
new Dripbox_Update_Checker(__FILE__);


// ============================================================================
// 10.0 FUNÇÃO COMPARTILHADA: Blog Name ========================================
// ============================================================================
function dripbox5_get_blog_name() {
    return apply_filters('dripbox_blog_name', get_bloginfo('name'));
}


function dripbox_is_license_valid() {
    return get_option('dripbox_license_valid') === 'yes';
}


// ============================================================================
// === ASSETS (CSS + JS) ======================================================
// ============================================================================
function dripbox5_enqueue_assets() {

    $dev_buster = (defined('WP_DEBUG') && WP_DEBUG) ? '.' . time() : '';

    wp_enqueue_style(
        'dripbox5-style',
        plugins_url('dripbox.css', __FILE__),
        array(),
        DRIPBOX_VERSION . $dev_buster
    );

    wp_enqueue_style(
        'dripbox5-table-style',
        plugins_url('dripbox-table.css', __FILE__),
        array(),
        DRIPBOX_VERSION . $dev_buster
    );

    // CARREGA O JS UMA ÚNICA VEZ, DO JEITO CERTO, NO FOOTER
    wp_enqueue_script(
        'dripbox5-interactions',
        plugins_url('dripbox-interactions.js', __FILE__),
        array(),
        microtime(),  
        true
    );
}
add_action('wp_enqueue_scripts', 'dripbox5_enqueue_assets', 9999);


// ============================================================================
// === CPT: DRIPBOX PRODUCTS ==================================================
// ============================================================================
function dripbox5_register_cpt() {
    $labels = array(
        'name'               => 'Products',
        'singular_name'      => 'Product',
        'menu_name'          => 'DripBox',
        'add_new'            => 'Add New Product',
        'add_new_item'       => 'Add New Product',
        'edit_item'          => 'Edit Product',
        'new_item'           => 'New Product',
        'view_item'          => 'View Product',
        'search_items'       => 'Search Products',
        'not_found'          => 'No products found',
        'not_found_in_trash' => 'No products found in Trash',
    );

    $args = array(
        'labels'             => $labels,
        'public'             => false,
        'show_ui'            => true,
        'show_in_menu'       => true,
        'menu_icon'          => 'dashicons-products',
        'supports'           => array('title'),
        'capability_type'    => 'post',
    );

    register_post_type('dripbox_product', $args);
}
add_action('init', 'dripbox5_register_cpt');

// ============================================================================
// === ADMIN UI (METABOXES) ===================================================
// ============================================================================
function dripbox5_add_meta_boxes() {
    add_meta_box(
        'dripbox5_details',
        'Product Details',
        'dripbox5_render_fields',
        'dripbox_product',
        'normal',
        'high'
    );
}
add_action('add_meta_boxes', 'dripbox5_add_meta_boxes');
add_action('edit_form_after_title', function($post){
    if ($post->post_type === 'dripbox_product') {
        dripbox5_shortcode_box($post);
    }
});

// ============================================================================
// === ADMIN PAGE: ANALYTICS ==================================================
// ============================================================================
add_action('admin_menu', function() {
    add_submenu_page(
        'edit.php?post_type=dripbox_product',  // parent
        'Analytics',                           // page title
        'Analytics',                           // menu title
        'manage_options',                      // permission
        'dripbox-analytics',                   // slug
        'dripbox_render_analytics_page_full'   // callback
    );
});

function dripbox_render_analytics_page() {
    echo "<div class='wrap'><h1>DripBox Analytics</h1><p>Loading...</p></div>";
}


// === RENDERIZA OS CAMPOS NO ADMIN ===========================================
function dripbox5_render_fields($post) {
    wp_nonce_field('dripbox_save_meta', 'dripbox_nonce');
    $meta = get_post_meta($post->ID);

    // 1. CHAMA O CSS (Conecta o admin.css)
    // wp_enqueue_style('dripbox-admin-styles', plugins_url('admin.css', __FILE__), [], '1.0.2');

?>

    <div class="dripbox-admin-wrap">
    <div class="dripbox-admin-grid">

  <!-- COLUNA ESQUERDA -->
  
        <div>
            <!-- PROS / CONS -->
            
            <div class="dripbox-grid-2">
                <div class="dripbox-field proscons">
                    <label>Pros ✅</label>
                    <textarea name="pros"><?php echo esc_textarea($meta['pros'][0] ?? ''); ?></textarea>
                    <small class="hint-proscons">Each item must be separated by “;”</small>
                </div>
                
                <div class="dripbox-field proscons">
                    <label>Cons ❌</label>
                    <textarea name="cons"><?php echo esc_textarea($meta['cons'][0] ?? ''); ?></textarea>
                    <small class="hint-proscons">Each item must be separated by “;”</small>
                </div>

            </div>
            
            
<!-- PRESETS -->          
            <h3>🎨 Global Button Presets</h3>

                <?php $presets = get_option('dripbox_button_presets', []); ?>
                
                <div style="display:flex; gap:16px; margin-bottom:20px;">
                    <label>Store Amazon
                        <input type="color" name="preset_amazon" value="<?php echo esc_attr($presets['amazon'] ?? '#ff9900'); ?>">
                    </label>
                
                    <label>Store B
                        <input type="color" name="preset_other" value="<?php echo esc_attr($presets['other'] ?? '#0073aa'); ?>">
                    </label>
                
                    <label>Store C
                        <input type="color" name="preset_third" value="<?php echo esc_attr($presets['third'] ?? '#28a745'); ?>">
                    </label>
                
                    <label>Store D
                        <input type="color" name="preset_fourth" value="<?php echo esc_attr($presets['fourth'] ?? '#6f42c1'); ?>">
                    </label>
                </div>


<!-- AFILIADOS -->
            <h3 class="affiliate-links-title">Affiliate Links</h3>
            <div class="dripbox-grid-2 affiliate-cards-container">
                <?php
                $stores = [
                    ['amz','🛒 Amazon', '#ff9900'],
                    ['b','🏬 Store B', '#0073aa'],
                    ['c','🏪 Store C', '#28a745'],
                    ['d','🏷️ Store D', '#6f42c1']
                ];
                
               
                $presets = get_option('dripbox_button_presets', []);
                foreach ($stores as [$key, $label, $defColor]) {

                    $urlName   = $key==='amz'?'amazon':($key==='b'?'other':($key==='c'?'third':'fourth'));
                    $btnName   = $key==='amz'?'btntext_amazon':($key==='b'?'btntext_other':($key==='c'?'btntext_third':'btntext_fourth'));
                    $colorName = $key==='amz'?'color_amazon':($key==='b'?'color_other':($key==='c'?'color_third':'color_fourth'));
                    
                    // Pega a cor salva ou usa o padrão
                    $presets = get_option('dripbox_button_presets', []);
                    $savedColor  = $meta[$colorName][0] ?? '';
                    $presetColor = $presets[$urlName] ?? $defColor;
                    
                    $finalColor = $savedColor ?: $presetColor;

                    
                ?>
                    <div class="affiliate-card <?php echo esc_attr($key); ?>">
                        <div style="display:flex; justify-content:space-between; align-items:center;">
                            <h4><?php echo $label; ?></h4>
                            <div style="display:flex; align-items:center; gap:5px;">
                                <label style="font-size:10px; margin:0; color:#555;">Button Color:</label>
                                <input type="color" name="<?php echo $colorName; ?>" value="<?php echo esc_attr($finalColor); ?>" style="height:25px; width:30px; border:none; padding:0; cursor:pointer;">
                            </div>
                        </div>
                        <div class="dripbox-field">
                            <label>URL</label>
                        
                            <div style="display:flex; gap:6px; align-items:center;">
                                <input 
                                    type="text" 
                                    name="<?php echo $key==='amz'?'amazon':($key==='b'?'other':($key==='c'?'third':'fourth')); ?>"
                                    value="<?php echo esc_attr($meta[$key==='amz'?'amazon':($key==='b'?'other':($key==='c'?'third':'fourth'))][0] ?? ''); ?>"
                                    class="dripbox-url-input"
                                    style="flex:1;"
                                >
                        
                                <button 
                                    type="button" 
                                    class="button dripbox-copy-admin"
                                    data-copy-target="<?php echo $key==='amz'?'amazon':($key==='b'?'other':($key==='c'?'third':'fourth')); ?>"
                                >
                                    Copy Link
                                </button>
                            </div>
                        </div>

                        <div class="dripbox-field">
                            <label>Button Text</label>
                            <input type="text" name="<?php echo $key==='amz'?'btntext_amazon':($key==='b'?'btntext_other':($key==='c'?'btntext_third':'btntext_fourth')); ?>"
                                        value="<?php echo esc_attr($meta[$key==='amz'?'btntext_amazon':($key==='b'?'btntext_other':($key==='c'?'btntext_third':'btntext_fourth'))][0] ?? ''); ?>">
                        </div>
                    </div>
                <?php } ?>
            </div>

<!-- INFO CAMPOS -->

            <div class="dripbox-grid-3 info-fields-container">
                <div class="dripbox-field"><label>Why We Picked It</label><textarea name="why"><?php echo esc_textarea($meta['why'][0] ?? ''); ?></textarea></div>
                <div class="dripbox-field"><label>Who It’s For</label><textarea name="who"><?php echo esc_textarea($meta['who'][0] ?? ''); ?></textarea></div>
                <div class="dripbox-field"><label>Specs (Label: Value | Label: Value)</label><textarea name="specs"><?php echo esc_textarea($meta['specs'][0] ?? ''); ?></textarea></div>
            </div>

<!-- RATING PARA LAYOUT MAG -->
            <div class="dripbox-field rating-field">
                <label><strong>⭐ Rating</strong> <span class="rating-note">(For layout MAG only)</span></label>
                <?php $rating = esc_attr($meta['rating'][0] ?? '3.0'); ?>
                <input 
                    type="number" 
                    name="rating" 
                    step="0.5" 
                    min="3" 
                    max="5" 
                    value="<?php echo esc_attr($meta['rating'][0] ?? '3.0'); ?>"
                    class="rating-input"
                >
                <small class="rating-help-text">
                    If using the MAG layout, this value defines how many dots appear (3 = 3 full dots).
                </small>
            </div>

<!-- LAYOUT -->
            <div class="dripbox-field layout-field">
                <label>Layout</label>
                
                <div class="dripbox-layout-row">

<!-- Bloco de layouts -->

                    <div class="dripbox-layout-options">
                        <?php $current = $meta['layout'][0] ?? 'default'; ?>
                    
                        <label>
                            <input type="radio" name="layout" value="default" <?php checked($current,'default'); ?>>
                            <div>Default</div>
                        </label>
                        <label>
                            <input type="radio" name="layout" value="horizontal" <?php checked($current,'horizontal'); ?>>
                            <div>Horizontal</div>
                        </label>
                        <label>
                            <input type="radio" name="layout" value="banner" <?php checked($current,'banner'); ?>>
                            <div>Banner</div>
                        </label>
                    </div>

<!-- Bloco da Amazon -->                
                    <?php $checked = ($meta['show_disclaimer'][0] ?? '') === 'yes' ? 'checked' : ''; ?>
                    <div class="dripbox-toggle amazon-disclaimer">
                        <div class="toggle-title">Show this message?</div>
                        <label class="toggle-label">
                            <input type="checkbox" name="show_disclaimer" value="yes" <?php echo $checked; ?>>
                            Enable
                        </label>
                        <small class="toggle-help-text">
                            As an Amazon Associate, I earn from qualifying purchases. This helps keep <?php echo esc_html(dripbox5_get_blog_name()); ?> running — thank you for your support.
                        </small>
                    </div>
                </div>
            </div>
        </div>

<!-- COLUNA DIREITA (IMAGEM) -->
<div class="right-column">
    
    <?php 
    // Recupera as variáveis de imagem do meta (upload WordPress e URL externa)
    $img = esc_url($meta['img'][0] ?? ''); 
    $ext_image = esc_url($meta['ext_image'][0] ?? '');
    ?>
    
    <!-- Título da seção de imagem -->
    <label class="image-label" style="font-size:14px; font-weight:bold; margin-bottom:10px; display:block;">Product Image</label>
    
    <!-- OPÇÃO A: URL Externa (Amazon SiteStripe) -->
    <div class="dripbox-option-box">
        <label class="dripbox-option-label">🅰️ Option A: External URL (No API)</label>
        <input 
            type="text" 
            name="ext_image" 
            value="<?php echo $ext_image; ?>" 
            placeholder="Paste Amazon Image URL here..." 
        >
        <p style="font-size:10px; color:#666; margin:4px 0 0;">Use this for Amazon SiteStripe images.</p>
    </div>

    <!-- OPÇÃO B: Upload via Media Library do WordPress -->
    <div class="dripbox-option-box">
        <label class="dripbox-option-label">🅱️ Option B: Upload</label>
        <div class="dripbox-image-uploader-row">
            <input 
                type="text" 
                name="img" 
                id="dripbox_img_input" 
                value="<?php echo $img; ?>" 
                placeholder="https://..." 
            >
            <button type="button" class="button" id="dripbox_upload_btn">Select</button>
        </div>
    </div>

    <!-- Preview da Imagem (prioriza ext_image sobre img) -->
    <div id="dripbox_img_preview_container">
        <?php 
        // Se tiver imagem externa (Option A), usa ela no preview. Senão, usa a do upload (Option B)
        $previewImg = !empty($ext_image) ? $ext_image : $img;
        ?>
        <?php if ($previewImg) : ?>
            <img src="<?php echo $previewImg; ?>" alt="Preview" class="image-preview" style="display:block; width:100%; height:auto; border-radius:8px; border:1px solid #ddd; margin-top:10px;">
        <?php else : ?>
            <div class="no-image-placeholder">
                No Image
            </div>
        <?php endif; ?>
    </div>

    <!-- === CAMPOS DE METADADOS === -->
    <div class="metadata-fields">
        
        <!-- Headline (ex: Best Overall) -->
        <div class="dripbox-field">
            <label><span class="dripbox-icon">🏷️</span> Headline (ex: Best Overall)</label>
            <input type="text" name="dripbox_head"
                    value="<?php echo esc_attr($meta['head'][0] ?? ''); ?>"
                    placeholder="Best Overall"
                    class="metadata-input">
        </div>

        <!-- Verdict (subtítulo curto para tabela) -->
        <div class="dripbox-field">
            <label><span class="dripbox-icon">📝</span> Verdict (short phrase for table view)</label>
            <input type="text" name="verdict"
                    value="<?php echo esc_attr($meta['verdict'][0] ?? ''); ?>"
                    placeholder="The Rock-Solid Workhorse"
                    class="metadata-input">
        </div>

        <!-- TABLE SUMMARY (até 3 versões separadas por ";") -->
        <div class="summary-field-wrap big-top-margin">
            <div class="dripbox-field">
                <label>Table Summary <span class="summary-note">(up to 3 versions separated by ";")</span></label>
                <textarea name="summary" placeholder="Example: Pros and cons overview...; Comparison of key features...; Detailed summary of performance."><?php echo esc_textarea($meta['summary'][0] ?? ''); ?></textarea>
                <small class="summary-help-text">💡 Enter up to 3 short summary variations separated by semicolons. One will be shown randomly below the product box.</small>
            </div>
        </div>
        
    </div>
</div>
</div>
</div>
<?php
}


// === Presets buttons ===
function dripbox_register_default_presets() {
    if (!get_option('dripbox_button_presets')) {
        update_option('dripbox_button_presets', [
            'amazon' => '#ff9900',
            'other'  => '#0073aa',
            'third'  => '#28a745',
            'fourth' => '#6f42c1',
        ]);
    }
}
add_action('admin_init', 'dripbox_register_default_presets');



// === Carregar CSS do Admin para páginas do DripBox ===
add_action('admin_enqueue_scripts', function ($hook) {
    global $post;

    // 1. Carregar no editor do CPT dripbox_product
    if (isset($post->post_type) && $post->post_type === 'dripbox_product') {

        // Carrega a Biblioteca de Mídia
        wp_enqueue_media();

        // CSS do admin
        wp_enqueue_style(
            'dripbox-admin-styles',
            plugins_url('admin.css', __FILE__),
            [],
            time()
        );

        // JS do admin (novo)
        wp_enqueue_script(
            'dripbox-admin-js',
            plugins_url('admin.js', __FILE__),
            array('jquery'), // <--- [IMPORTANTE] Adicionei a dependência do jQuery aqui
            time(),
            true
        );

        return;
    }

    // 2. Carregar nas páginas internas do plugin
    $allowed_pages = [
        'dripbox-license',
        'dripbox-upgrade',
        'dripbox-generate-license',
        'dripbox-analytics'
    ];

    if (isset($_GET['page']) && in_array($_GET['page'], $allowed_pages)) {

        wp_enqueue_style(
            'dripbox-admin-styles',
            plugins_url('admin.css', __FILE__),
            [],
            time()
        );

        wp_enqueue_script(
            'dripbox-admin-js',
            plugins_url('admin.js', __FILE__),
            [],
            time(),
            true
        );
    }
    
    
});


// ============================================================================
// === SALVA METADADOS (ATUALIZADO FASE 1) ===================================
// ============================================================================
function dripbox5_save_fields($post_id) {

    // 1. Nonce obrigatório
    if (!isset($_POST['dripbox_nonce']) ||
        !wp_verify_nonce($_POST['dripbox_nonce'], 'dripbox_save_meta')) {
        return;
    }

    // 2. Permissions
    if (!current_user_can('edit_post', $post_id)) return;

    // 3. Autosave
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;

    // 4. Tipo correto
    if (get_post_type($post_id) !== 'dripbox_product') return;

    // 5. Headline
    if (isset($_POST['dripbox_head'])) {
        update_post_meta($post_id, 'head', sanitize_text_field($_POST['dripbox_head']));
    }

    // 6. Campos normais (ADICIONADOS: ext_image e as cores)
    $keys = [
        'badge','img','ext_image', // Imagens
        'pros','cons',
        'amazon','btntext_amazon','color_amazon', // Botão 1
        'other','btntext_other','color_other',    // Botão 2
        'third','btntext_third','color_third',    // Botão 3
        'fourth','btntext_fourth','color_fourth', // Botão 4
        'why','who','specs','layout','show_disclaimer','rating','verdict','summary'
    ];
    
    if (
    isset($_POST['preset_amazon']) ||
    isset($_POST['preset_other']) ||
    isset($_POST['preset_third']) ||
    isset($_POST['preset_fourth'])
) {
    update_option('dripbox_button_presets', [
        'amazon' => sanitize_hex_color($_POST['preset_amazon'] ?? '#ff9900'),
        'other'  => sanitize_hex_color($_POST['preset_other'] ?? '#0073aa'),
        'third'  => sanitize_hex_color($_POST['preset_third'] ?? '#28a745'),
        'fourth' => sanitize_hex_color($_POST['preset_fourth'] ?? '#6f42c1'),
    ]);
}


    foreach ($keys as $key) {
        if (isset($_POST[$key])) {
            update_post_meta($post_id, $key, sanitize_text_field($_POST[$key]));
        } else {
            // Cuidado: Só deletamos se realmente não vier no POST, 
            // mas como checkbox e outros inputs podem não vir, essa lógica é ok para text inputs
            delete_post_meta($post_id, $key);
        }
    }
}
add_action('save_post_dripbox_product', 'dripbox5_save_fields');


// === VALIDAÇÃO: Pelo menos 1 URL de afiliado ===
function dripbox5_validate_before_save($post_id) {
    if (get_post_type($post_id) !== 'dripbox_product') return;
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    
    $amazon = isset($_POST['amazon']) ? trim($_POST['amazon']) : '';
    $other = isset($_POST['other']) ? trim($_POST['other']) : '';
    $third = isset($_POST['third']) ? trim($_POST['third']) : '';
    $fourth = isset($_POST['fourth']) ? trim($_POST['fourth']) : '';
    
    if (empty($amazon) && empty($other) && empty($third) && empty($fourth)) {
        add_action('admin_notices', function() {
            echo '<div class="notice notice-warning"><p><strong>⚠️ Aviso:</strong> Este produto não tem nenhuma URL de afiliado. Adicione pelo menos uma.</p></div>';
        });
    }
}
add_action('save_post_dripbox_product', 'dripbox5_validate_before_save', 5);


// ============================================================================
// === MOSTRA SHORTCODES NO ADMIN ============================================
// ============================================================================
function dripbox5_shortcode_box($post) {
    $id = $post->ID; ?>
    <div style="background:#f6f7f7;border:1px solid #ccd0d4;padding:14px 16px;border-radius:8px;margin-top:10px;">
        <strong>Shortcodes (copy and paste):</strong>
        <table style="width:100%;margin-top:8px;border-collapse:collapse;font-family:monospace;font-size:13px;">
            <tr>
                <td style="width:60%;padding:6px 4px;">
                    <input type="text" readonly value='[dripbox id="<?php echo $id; ?>" layout="default"]'
                           style="width:100%;padding:6px 8px;border-radius:5px;border:1px solid #ddd;background:#fff;">
                </td>
                <td style="padding-left:10px;color:#444;">⭐ Ideal for <strong>product review sections</strong></td>
            </tr>
            <tr>
                <td style="padding:6px 4px;">
                    <input type="text" readonly value='[dripbox id="<?php echo $id; ?>" layout="horizontal"]'
                           style="width:100%;padding:6px 8px;border-radius:5px;border:1px solid #ddd;background:#fff;">
                </td>
                <td style="padding-left:10px;color:#444;">📄 Great for <strong>end-of-article summaries</strong></td>
            </tr>
            <tr>
                <td style="padding:6px 4px;">
                    <input type="text" readonly value='[dripbox id="<?php echo $id; ?>" layout="banner"]'
                           style="width:100%;padding:6px 8px;border-radius:5px;border:1px solid #ddd;background:#fff;">
                </td>
                <td style="padding-left:10px;color:#444;">🧩 Perfect for <strong>inline banners within text</strong></td>
            </tr>
         <tr>
                    <td style="padding:6px 4px;">
                        <input type="text" readonly value='[dripbox id="<?php echo $id; ?>" layout="mag"]'
                               style="width:100%;padding:6px 8px;border-radius:5px;border:1px solid #ddd;background:#fff;">
                    </td>
                    <td style="padding-left:10px;color:#444;">🏆 Premium <strong>editorial layout</strong></td>
                </tr>

        </table>
        <p style="margin:8px 0 0;font-size:13px;color:#555;">💡 Tip: If <code>layout</code> is omitted, the product’s default layout will be used.</p>
    </div>
<?php }


// ============================================================================
// === COLUNA SHORTCODE NA LISTAGEM ===========================================
// ============================================================================
function dripbox5_add_shortcode_column($columns) {
    $columns['shortcode'] = 'Shortcode';
    return $columns;
}
add_filter('manage_dripbox_product_posts_columns', 'dripbox5_add_shortcode_column');

function dripbox5_render_shortcode_column($column, $post_id) {
    if ($column === 'shortcode') {
        echo '<code>[dripbox id="' . $post_id . '"]</code>';
    }
}
add_action('manage_dripbox_product_posts_custom_column', 'dripbox5_render_shortcode_column', 10, 2);

function dripbox5_shortcode_column_width() {
    echo '<style>.column-shortcode{width:180px;}</style>';
}
add_action('admin_head', 'dripbox5_shortcode_column_width');


// ============================================================================
// === SHORTCODE PRINCIPAL [dripbox] =========================================
// ============================================================================
function dripbox5_shortcode($atts) {
    // 1. Definição dos campos
    $atts = shortcode_atts(array(
        'id' => '', 'title' => '', 'badge' => '', 'img' => '', 
        'ext_image' => '', 'pros' => '', 'cons' => '', 
        'amazon' => '', 'btntext_amazon' => '', 'color_amazon' => '',
        'other' => '', 'btntext_other' => '', 'color_other' => '',
        'third' => '', 'btntext_third' => '', 'color_third' => '',
        'fourth' => '', 'btntext_fourth' => '', 'color_fourth' => '',
        'specs' => '', 'why' => '', 'who' => '', 'summary' => '', 
        'layout' => '', 'show_disclaimer' => '', 'rating' => '', 
        'box_color' => '', 'background' => '', 'head' => '', 'verdict' => ''
    ), $atts);

    // 2. Busca o ID
    if (empty($atts['id']) && get_the_ID()) $atts['id'] = get_the_ID();
    if (empty($atts['id'])) {
        global $post;
        if (isset($post->ID)) $atts['id'] = $post->ID;
    }
    if (empty($atts['id'])) return ''; // Sem ID, não exibe nada

    $post_id = intval($atts['id']);
    
    // 3. Preenche dados do banco (Meta)
    $meta = get_post_meta($post_id);
    foreach ($meta as $key => $value) {
        if (array_key_exists($key, $atts) && empty($atts[$key])) {
            $atts[$key] = is_array($value) ? $value[0] : $value;
        }
    }

    // 4. --- MAPEAMENTO FORÇADO (O SEGREDO PARA AS CORES FUNCIONAREM) ---
    if (!empty($meta['ext_image'][0]))    $atts['ext_image']    = $meta['ext_image'][0];
    if (!empty($meta['color_amazon'][0])) $atts['color_amazon'] = $meta['color_amazon'][0];
    if (!empty($meta['color_other'][0]))  $atts['color_other']  = $meta['color_other'][0];
    if (!empty($meta['color_third'][0]))  $atts['color_third']  = $meta['color_third'][0];
    if (!empty($meta['color_fourth'][0])) $atts['color_fourth'] = $meta['color_fourth'][0];
    // -------------------------------------------------------------------

    if (empty($atts['title'])) $atts['title'] = get_the_title($post_id);

    // 5. Define o Layout
    if (!empty($atts['layout'])) {
        $layout = sanitize_text_field($atts['layout']);
    } else {
        $layout = get_post_meta($post_id, 'layout', true) ?: 'default';
    }
    $atts['layout'] = $layout;

    // 6. Escolhe qual Template chamar
    // IMPORTANTE: Certifique-se que as outras funções (horizontal, banner, mag) 
    // existam no arquivo se você for usar outros layouts.
    switch ($layout) {
        case 'horizontal':
            return dripbox5_template_horizontal($atts);
        case 'banner':
            return dripbox5_template_banner($atts);
        case 'mag':
            return dripbox5_template_mag($atts);
        default:
            return dripbox5_template_default($atts);
    }
}
add_shortcode('dripbox', 'dripbox5_shortcode');


// ============================================================
// LIMPA O CACHE AO SALVAR O PRODUTO
// ============================================================
add_action('save_post_dripbox_product', function($post_id) {
    global $wpdb;
    $pattern = $wpdb->esc_like("dripbox_cache_{$post_id}_") . '%';

    $wpdb->query(
        $wpdb->prepare(
            "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s",
            "_transient_{$pattern}"
        )
    );

    $wpdb->query(
       $wpdb->prepare(
            "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s",
            "_transient_timeout_{$pattern}"
        )
    );
});

;

/**
 * Get random summary version (split by ;)
 */
function dripbox_get_random_summary($summary_text) {
    if (empty($summary_text)) return '';
    $parts = array_filter(array_map('trim', explode(';', $summary_text)));
    if (empty($parts)) return '';
    return $parts[array_rand($parts)];
}


// === FUNÇÃO COMPARTILHADA: Renderiza Pros/Cons ===
function dripbox5_render_proscons($atts) {
    $output = '<div class="mini-pros-cons">';
    
    if (!empty($atts['pros'])) {
        $output .= '<div class="mini-pros"><h4>Pros</h4><ul>';
        foreach (preg_split('/;/', $atts['pros']) as $pro) {
            $pro = trim($pro);
            if ($pro) {
                if (preg_match('/^(.*?)(:|–|—)(.*)$/u', $pro, $m)) {
                    $strong = trim($m[1]);
                    $rest = trim($m[3]);
                    $output .= '<li><span><strong>' . esc_html($strong) . ':</strong> ' . esc_html($rest) . '</span></li>';
                } else {
                    $output .= '<li>' . esc_html($pro) . '</li>';
                }
            }
        }
        $output .= '</ul></div>';
    }
    
    if (!empty($atts['cons'])) {
        $output .= '<div class="mini-cons"><h4>Cons</h4><ul>';
        foreach (preg_split('/;/', $atts['cons']) as $con) {
            $con = trim($con);
            if ($con) {
                if (preg_match('/^(.*?)(:|–|—)(.*)$/u', $con, $m)) {
                    $strong = trim($m[1]);
                    $rest = trim($m[3]);
                    $output .= '<li><span><strong>' . esc_html($strong) . ':</strong> ' . esc_html($rest) . '</span></li>';
                } else {
                    $output .= '<li>' . esc_html($con) . '</li>';
                }
            }
        }
        $output .= '</ul></div>';
    }
    
    $output .= '</div>';
    return $output;
}


// ============================================================================
// === LAYOUT 1: DEFAULT (VERSÃO BLINDADA + CORREÇÃO DB) ======================
// ============================================================================
function dripbox5_template_default($atts) {
    
    // 1. Identificação Cache (Nome novo)
    $product_id = isset($atts['id']) ? $atts['id'] : md5(serialize($atts));
    $cache_key = 'dbx_def_cloud_FIXED_v13_' . $product_id;

    // 2. Cache Check (12 horas)
//    $cached_html = get_transient($cache_key);
//    if (false !== $cached_html) {
//        return $cached_html . '';
//    }

// ✅ ADICIONE ISSO AQUI - BUSCA AS CORES DO BANCO
    if (!empty($atts['id'])) {
        $post_id = intval($atts['id']);
        
        // Busca cores se estiverem vazias
        if (empty($atts['color_amazon'])) {
            $db_val = get_post_meta($post_id, 'color_amazon', true);
            if ($db_val) $atts['color_amazon'] = $db_val;
        }
        if (empty($atts['color_other'])) {
            $db_val = get_post_meta($post_id, 'color_other', true);
            if ($db_val) $atts['color_other'] = $db_val;
        }
        if (empty($atts['color_third'])) {
            $db_val = get_post_meta($post_id, 'color_third', true);
            if ($db_val) $atts['color_third'] = $db_val;
        }
        if (empty($atts['color_fourth'])) {
            $db_val = get_post_meta($post_id, 'color_fourth', true);
            if ($db_val) $atts['color_fourth'] = $db_val;
        }
    }

    // 3. Recupera Licença
    global $wpdb;
    $table = $wpdb->prefix . 'dripbox_licenses';
    $license_row = $wpdb->get_row("SELECT license_key FROM {$table} WHERE status = 'active' LIMIT 1");
    $license_key = $license_row ? $license_row->license_key : '';

    // 4. Chama a API (Nave Mãe)
    $url_api = 'https://getdripbox.com/wp-json/dripbox/v1/render-default';
    
    $response = wp_remote_post($url_api, [
        'timeout' => 15,
        'body'    => json_encode([
            'license_key' => $license_key,
            'domain'      => sanitize_text_field($_SERVER['SERVER_NAME']),
            'atts'        => $atts 
        ]),
        'headers' => ['Content-Type' => 'application/json']
    ]);

    // 5. Tratamento de Erro (Silencioso para produção)
    if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
        // Se der erro, retorna vazio para não quebrar o layout do site
        return '';
    }

    // 6. Processa o HTML
    $data = json_decode(wp_remote_retrieve_body($response), true);
    
    if (empty($data['html'])) {
        return '';
    }

    $html_final = $data['html'];

    // 7. Salva no Cache por 12 horas
//    set_transient($cache_key, $html_final, 6 * HOUR_IN_SECONDS);

    return $html_final;
}


// ============================================================================
// === LAYOUT 2: HORIZONTAL (VERSÃO BLINDADA + CORREÇÃO DB) ===================
// ============================================================================
function dripbox5_template_horizontal($atts) {
    
    // 1. Identificação Cache (Nome novo)
    $product_id = isset($atts['id']) ? $atts['id'] : md5(serialize($atts));
    $cache_key = 'dbx_horiz_cloud_FIXED_sD2B1_' . $product_id;
    
    // 2. Cache Check (6 horas)
//    $cached_html = get_transient($cache_key);
//    if (false !== $cached_html) {
//        return $cached_html . '';
//    }
    
    // 3. === CORREÇÃO: BUSCAR DADOS DO DB ===
    if (!empty($atts['id'])) {
        $post_id = intval($atts['id']);
        if (empty($atts['btntext_amazon']) || $atts['btntext_amazon'] === 'Check Price on Amazon') {
            $db_val = get_post_meta($post_id, 'btntext_amazon', true); 
            if ($db_val) $atts['btntext_amazon'] = $db_val;
        }
        if (empty($atts['btntext_other']) || $atts['btntext_other'] === 'Check Price') {
            $db_val = get_post_meta($post_id, 'btntext_other', true); 
            if ($db_val) $atts['btntext_other'] = $db_val;
        }
        if (empty($atts['btntext_third']) || $atts['btntext_third'] === 'Check Price') {
            $db_val = get_post_meta($post_id, 'btntext_third', true); 
            if ($db_val) $atts['btntext_third'] = $db_val;
        }
        if (empty($atts['btntext_fourth']) || $atts['btntext_fourth'] === 'Check Price') {
            $db_val = get_post_meta($post_id, 'btntext_fourth', true); 
            if ($db_val) $atts['btntext_fourth'] = $db_val;
        }
    }
    
    // 4. Pega Licença
    global $wpdb;
    $table = $wpdb->prefix . 'dripbox_licenses';
    $license = $wpdb->get_row("SELECT license_key FROM {$table} WHERE status = 'active' ORDER BY id DESC LIMIT 1");
    $key = $license ? $license->license_key : '';
    
    // 5. Chama a Nave Mãe
    $response = wp_remote_post('https://getdripbox.com/wp-json/dripbox/v1/render-horizontal', [
        'timeout' => 15,
        'body'    => json_encode([
            'license_key' => $key,
            'domain'      => sanitize_text_field($_SERVER['SERVER_NAME']),
            'atts'        => $atts 
        ]),
        'headers' => ['Content-Type' => 'application/json']
    ]);
    
    // 6. Erro ou Sucesso
    if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
        // Fallback simples caso a API falhe
        $fallback = '<div class="dripbox-fallback" style="padding:20px; border:1px solid #ddd; border-radius:8px; text-align:center; background:#f9f9f9;">
            <h3 style="margin:0 0 10px; font-size:18px; color:#333;">'.esc_html($atts['title']).'</h3>';
        if (!empty($atts['amazon'])) {
            $fallback .= '<a href="'.esc_url($atts['amazon']).'" target="_blank" rel="nofollow noopener" style="display:inline-block; padding:12px 24px; background:#0073e6; color:#fff; text-decoration:none; border-radius:6px; font-weight:600; margin-top:10px;">Check Price on Amazon</a>';
        }
        $fallback .= '</div>';
        return $fallback;
    }
    
    $data = json_decode(wp_remote_retrieve_body($response), true);
    if (empty($data['html'])) return '';
    
    $html_final = $data['html'];
//    set_transient($cache_key, $html_final, 6 * HOUR_IN_SECONDS);
    
    return $html_final . '';
}


// ============================================================================
// === LAYOUT 3: BANNER (VERSÃO V5 - FIX BADGE & HEADLINE) ====================
// ============================================================================
function dripbox5_template_banner($atts) {
    
    // 1. Identificação Cache
    $product_id = isset($atts['id']) ? $atts['id'] : md5(serialize($atts));
    
    // 2. === BUSCAR DADOS DO DB ===
    if (!empty($atts['id'])) {
        $post_id = intval($atts['id']);
        
        // --- [CORREÇÃO] MAPEAMENTO INTELIGENTE DO BADGE ---
        if (empty($atts['badge'])) {
            // Tenta achar 'badge' primeiro
            $found = get_post_meta($post_id, 'badge', true);
            // Se não achar, tenta 'head' (que é o campo Headline do seu admin)
            if (empty($found)) {
                $found = get_post_meta($post_id, 'head', true);
            }
            $atts['badge'] = $found;
        }
        // --------------------------------------------------

        if (empty($atts['rating'])) {
            $atts['rating'] = get_post_meta($post_id, 'rating', true);
        }

        // Botões (mantido igual)
        if (empty($atts['btntext_amazon']) || $atts['btntext_amazon'] === 'Check Price on Amazon') {
            $db_val = get_post_meta($post_id, 'btntext_amazon', true); 
            if ($db_val) $atts['btntext_amazon'] = $db_val;
        }
        if (empty($atts['btntext_other']) || $atts['btntext_other'] === 'Check Price') {
            $db_val = get_post_meta($post_id, 'btntext_other', true); 
            if ($db_val) $atts['btntext_other'] = $db_val;
        }
        if (empty($atts['btntext_third']) || $atts['btntext_third'] === 'Check Price') {
            $db_val = get_post_meta($post_id, 'btntext_third', true); 
            if ($db_val) $atts['btntext_third'] = $db_val;
        }
        if (empty($atts['btntext_fourth']) || $atts['btntext_fourth'] === 'Check Price') {
            $db_val = get_post_meta($post_id, 'btntext_fourth', true); 
            if ($db_val) $atts['btntext_fourth'] = $db_val;
        }
    }

    // 4. Pega Licença
    global $wpdb;
    $table = $wpdb->prefix . 'dripbox_licenses';
    $license = $wpdb->get_row("SELECT license_key FROM {$table} WHERE status = 'active' ORDER BY id DESC LIMIT 1");
    $key = $license ? $license->license_key : '';

    // 5. Chama a Nave Mãe
    $response = wp_remote_post('https://getdripbox.com/wp-json/dripbox/v1/render-banner', [
        'timeout' => 15,
        'body'    => json_encode([
            'license_key' => $key,
            'domain'      => sanitize_text_field($_SERVER['SERVER_NAME']),
            'atts'        => $atts 
        ]),
        'headers' => ['Content-Type' => 'application/json']
    ]);

    // 6. Erro ou Sucesso
    if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
        // Fallback simples
        $fallback = '<div class="dripbox-fallback" style="padding:20px; border:1px solid #ddd; border-radius:8px; text-align:center;"><h3>'.esc_html($atts['title']).'</h3></div>';
        return $fallback;
    }

    $data = json_decode(wp_remote_retrieve_body($response), true);
    if (empty($data['html'])) return '';

    return $data['html'] . '';
}


// ============================================================================
// === COMPATIBILIDADE COM VERSÕES ANTERIORES ================================
if (!function_exists('dripbox_render_shortcode')) {
    function dripbox_render_shortcode($atts) { return dripbox5_shortcode($atts); }
}
if (!function_exists('dripbox_render_horizontal')) {
    function dripbox_render_horizontal($atts) { return dripbox5_template_horizontal($atts); }
}
if (!function_exists('dripbox_render_banner')) {
    function dripbox_render_banner($atts) { return dripbox5_template_banner($atts); }
}


// ============================================================================
// === LAYOUT 5: MAG (VERSÃO BLINDADA + CORREÇÃO DB) ==========================
// ============================================================================
function dripbox5_template_mag($atts) {
    
    // 1. Identificação Cache (Nome novo)
    $product_id = isset($atts['id']) ? $atts['id'] : md5(serialize($atts));
    $cache_key = 'dbx_mag_cloud_FIXED_D2Bss1_' . $product_id;
    
    // 2. Cache Check (6 horas)
//    $cached_html = get_transient($cache_key);
//    if (false !== $cached_html) {
//        return $cached_html . '';
//    }
    
    // 3. === CORREÇÃO: BUSCAR DADOS DO DB ===
    if (!empty($atts['id'])) {
        $post_id = intval($atts['id']);
        if (empty($atts['btntext_amazon']) || $atts['btntext_amazon'] === 'Check Price on Amazon') {
            $db_val = get_post_meta($post_id, 'btntext_amazon', true); 
            if ($db_val) $atts['btntext_amazon'] = $db_val;
        }
        if (empty($atts['btntext_other']) || $atts['btntext_other'] === 'Check Price') {
            $db_val = get_post_meta($post_id, 'btntext_other', true); 
            if ($db_val) $atts['btntext_other'] = $db_val;
        }
        if (empty($atts['btntext_third']) || $atts['btntext_third'] === 'Check Price') {
            $db_val = get_post_meta($post_id, 'btntext_third', true); 
            if ($db_val) $atts['btntext_third'] = $db_val;
        }
        if (empty($atts['btntext_fourth']) || $atts['btntext_fourth'] === 'Check Price') {
            $db_val = get_post_meta($post_id, 'btntext_fourth', true); 
            if ($db_val) $atts['btntext_fourth'] = $db_val;
        }
    }
    
    // 4. Pega Licença
    global $wpdb;
    $table = $wpdb->prefix . 'dripbox_licenses';
    $license = $wpdb->get_row("SELECT license_key FROM {$table} WHERE status = 'active' ORDER BY id DESC LIMIT 1");
    $key = $license ? $license->license_key : '';
    
    // 5. Chama a Nave Mãe
    $response = wp_remote_post('https://getdripbox.com/wp-json/dripbox/v1/render-mag', [
        'timeout' => 15,
        'body'    => json_encode([
            'license_key' => $key,
            'domain'      => sanitize_text_field($_SERVER['SERVER_NAME']),
            'atts'        => $atts 
        ]),
        'headers' => ['Content-Type' => 'application/json']
    ]);
    
    // 6. Erro ou Sucesso
    if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
        // Fallback
        $fallback = '<div class="dripbox-fallback" style="padding:20px; border:1px solid #ddd; border-radius:8px; text-align:center; background:#f9f9f9;">
            <h3 style="margin:0 0 10px; font-size:18px; color:#333;">'.esc_html($atts['title']).'</h3>';
        if (!empty($atts['amazon'])) {
            $fallback .= '<a href="'.esc_url($atts['amazon']).'" target="_blank" rel="nofollow noopener" style="display:inline-block; padding:12px 24px; background:#0073e6; color:#fff; text-decoration:none; border-radius:6px; font-weight:600; margin-top:10px;">Check Price on Amazon</a>';
        }
        $fallback .= '</div>';
        return $fallback;
    }
    
    $data = json_decode(wp_remote_retrieve_body($response), true);
    if (empty($data['html'])) return '';
    
    $html_final = $data['html'];
//    set_transient($cache_key, $html_final, 6 * HOUR_IN_SECONDS);
    
    return $html_final . '';
}


// ============================================================================
// Página de ativação (admin menu + formulário) 
// ============================================================================
function dripbox_license_page() {
    ?>
    <div class="wrap">
        <h1>Activate Your DripBox License</h1>

        <input id="dripbox_email" type="text" placeholder="Your email" style="width: 300px;">
        <br><br>
        <input id="dripbox_key" type="text" placeholder="License key" style="width: 300px;">
        <br><br>
        <button id="dripbox_activate" class="button button-primary">Activate</button>

        <script>
        document.getElementById('dripbox_activate').onclick = async () => {
            const email = document.getElementById('dripbox_email').value;
            const key = document.getElementById('dripbox_key').value;
            const domain = window.location.hostname;

            const res = await fetch('/wp-json/dripbox/v1/verify-license', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ email, license: key, domain })
            });

            const json = await res.json();

            if (json.valid) {
                alert("License activated!");
                location.reload();
            } else {
                alert("Activation failed: " + json.reason);
            }
        };
        </script>
    </div>
    <?php
}


// ============================================================================
// AVISO DE EXPIRACAO DA LICENSA
// ============================================================================
add_action('admin_init', function() {

    $status = get_option('dripbox_license_status');

    if ($status === 'expired') {
        // força reload 1 vez
        if (!isset($_GET['dripbox_refreshed'])) {
            wp_redirect(add_query_arg('dripbox_refreshed', '1'));
            exit;
        }
    }
});


// ============================================================================
// TABELA ANALYTICS DO CLICK
// ============================================================================
function dripbox_register_click($product_id, $button_type) {
    global $wpdb;

    $table = $wpdb->prefix . 'dripbox_clicks';
    $today = current_time('mysql'); // retorna YYYY-MM-DD HH:MM, mas filtramos só a data
    $today_date = substr($today, 0, 10);

    // Verificar se já existe registro para product + button + dia
    $existing_id = $wpdb->get_var($wpdb->prepare(
        "SELECT id FROM $table WHERE product_id=%d AND button_type=%s AND date=%s",
        $product_id, $button_type, $today_date
    ));

    if ($existing_id) {
        // Incrementar
        $wpdb->query($wpdb->prepare(
            "UPDATE $table SET total_clicks = total_clicks + 1 WHERE id=%d",
            $existing_id
        ));
    } else {
        // Criar nova linha
        $wpdb->insert($table, [
            'product_id'   => $product_id,
            'button_type'  => $button_type,
            'date'         => $today_date,
            'total_clicks' => 1
        ]);
    }
}


// ============================================================================
// BOTAO MENU ANALYTICS DO CLICK
// ============================================================================
function dripbox_render_analytics_page_full() {
    global $wpdb;
    
    $products = get_posts([
        'post_type' => 'dripbox_product',
        'posts_per_page' => -1,
        'orderby' => 'title',
        'order' => 'ASC'
    ]);
    
    echo "<div class='wrap'><h1>DripBox Analytics</h1>";
    echo "<p>Basic click analytics for all DripBox products.</p>";
    
    echo "
    <table class='dripbox-analytics-table widefat striped'>
        <thead>
            <tr>
                <th class='dripbox-col-product'>Product</th>
                <th class='sortable' data-col='total'>Total Clicks</th>
                <th class='sortable' data-col='last7'>Last 7 Days</th>
                <th class='sortable' data-col='last30'>Last 30 Days</th>
                <th class='sortable' data-col='top'>Top Button</th>
            </tr>
        </thead>
        <tbody>
    ";
    
    foreach ($products as $p) {
        $id = $p->ID;
        $total = $wpdb->get_var("SELECT SUM(total_clicks) FROM {$wpdb->prefix}dripbox_clicks WHERE product_id=$id");
        $last7 = $wpdb->get_var("SELECT SUM(total_clicks) FROM {$wpdb->prefix}dripbox_clicks WHERE product_id=$id AND date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)");
        $last30 = $wpdb->get_var("SELECT SUM(total_clicks) FROM {$wpdb->prefix}dripbox_clicks WHERE product_id=$id AND date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)");
        $top = $wpdb->get_row("SELECT button_type, SUM(total_clicks) as clicks FROM {$wpdb->prefix}dripbox_clicks WHERE product_id=$id GROUP BY button_type ORDER BY clicks DESC LIMIT 1");
        
        echo "<tr>
                <td><strong>{$p->post_title}</strong></td>
                <td>".intval($total)."</td>
                <td>".intval($last7)."</td>
                <td>".intval($last30)."</td>
                <td>" . ($top ? ucfirst($top->button_type) . " ({$top->clicks})" : "-") . "</td>
              </tr>";
    }
    
    echo "</tbody></table>";
    
    echo '<script>
    document.addEventListener("DOMContentLoaded", function() {
        document.querySelectorAll("th.sortable").forEach(th => {
            th.style.cursor = "pointer";
            th.style.textDecoration = "underline";
            
            // Guarda o estado atual de ordenação
            th.dataset.order = "desc";
            
            th.addEventListener("click", () => {
                const table = th.closest("table");
                const tbody = table.querySelector("tbody");
                const rows = Array.from(tbody.querySelectorAll("tr"));
                const index = Array.from(th.parentNode.children).indexOf(th);
                
                // Alternar ordem
                const isDesc = th.dataset.order === "desc";
                th.dataset.order = isDesc ? "asc" : "desc";
                
                const sorted = rows.sort((a, b) => {
                    const A = a.children[index].innerText.replace(/[^0-9]/g, "") || "0";
                    const B = b.children[index].innerText.replace(/[^0-9]/g, "") || "0";
                    
                    if (isDesc) {
                        return Number(B) - Number(A); // maior para menor
                    } else {
                        return Number(A) - Number(B); // menor para maior
                    }
                });
                
                tbody.innerHTML = "";
                sorted.forEach(r => tbody.appendChild(r));
            });
        });
    });
    </script>';
    
    echo "</div>";
}


// ==========================================================
// DRIPBOX TRACKING FINAL (COM ID NUMÉRICO PARA O LOCAL)
// ==========================================================
add_action('wp_footer', function() {
    ?>
<script>
document.addEventListener('click', function(e) {
    // 1. Verifica se é um clique na DripBox
    const link = e.target.closest('.dripbox-container a');
    if (!link) return;

    const box = link.closest('.dripbox-container');
    
    // Extrai ID Numérico
    let rawId = box.getAttribute('id') || ''; 
    let numericId = rawId.replace(/\D/g, ''); 

    // Pega o texto do botão (Limpo)
    let btnText = link.innerText || link.textContent || 'Check Price';
    btnText = btnText.trim();

    // --- INTELIGÊNCIA DE PLATAFORMA ---
    let detectedPlatform = 'other';
    const targetUrl = link.href.toLowerCase();
    const buttonTextLower = btnText.toLowerCase();

    // Dicionário de Plataformas (Adicione quantas quiser aqui)
    const platforms = {
        'amazon': ['amazon', 'amzn.to'],
        'clickbank': ['clickbank', 'hop.clickbank'],
        'buygoods': ['buygoods'],
        'ebay': ['ebay'],
        'hotmart': ['hotmart'],
        'shopee': ['shopee'],
        'aliexpress': ['aliexpress'],
        'walmart': ['walmart'],
        'bestbuy': ['bestbuy'],
        'target': ['target.com']
    };

    // 1. Tenta achar na URL ou no Texto do Botão
    for (const [key, keywords] of Object.entries(platforms)) {
        if (keywords.some(k => targetUrl.includes(k) || buttonTextLower.includes(k))) {
            detectedPlatform = key;
            break; 
        }
    }
    // ----------------------------------

    const payload = {
        product_id: numericId,
        domain: window.location.hostname,
        post_url: window.location.href,
        template_id: box.getAttribute('data-template-id') || 'default',
        license_key: box.getAttribute('data-license-key') || 'unknown',
        plugin_version: '1.1.0', 
        product_name: box.querySelector('h3')?.innerText || 'Product',
        event_type: 'click',
        platform: detectedPlatform, // <--- Enviando a plataforma correta
        target_url: link.href,
        button_text: btnText
    };

    // Envia para o Endpoint V2 (Anti-Cache)
    const endpoint = '/wp-json/dripbox/v1/track-v2';
    
    if (navigator.sendBeacon) {
        const blob = new Blob([JSON.stringify(payload)], {type: 'application/json'});
        navigator.sendBeacon(endpoint, blob);
    } else {
        fetch(endpoint, {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(payload),
            keepalive: true
        });
    }
});
</script>
    <?php
}, 99);


// ==========================================================
// ADICIONA LINK "GET PRO" NA LISTA DE PLUGINS
// ==========================================================
add_filter('plugin_action_links_' . plugin_basename(__FILE__), function($links) {
    
    // 1. Verifica se o usuário já é PRO
    $is_pro = defined('DRIPBOX_IS_PRO') && DRIPBOX_IS_PRO;

    if (!$is_pro) {
        // --- MODO FREE: MOSTRA O BOTÃO VERDE ---
        $upgrade_url = admin_url('edit.php?post_type=dripbox_product&page=dripbox-upgrade');
        
        // Estilo igual ao do WPCode (Verde e Negrito)
        $get_pro_link = '<a href="' . esc_url($upgrade_url) . '" style="color:#00a32a; font-weight:700;" title="Unlock all features">Get DripBox Pro</a>';
        
        // array_unshift coloca o link no INÍCIO da lista (antes de "Desativar")
        array_unshift($links, $get_pro_link);
        
    } else {
        // --- MODO PRO: MOSTRA LINK DE SETTINGS ---
        $settings_url = admin_url('edit.php?post_type=dripbox_product');
        $settings_link = '<a href="' . esc_url($settings_url) . '">Settings</a>';
        
        array_unshift($links, $settings_link);
    }

    return $links;
});



// === EMERGENCY CACHE CLEAR (use quando precisar) ===  https://getdripbox.com/?clear_dripbox_cache=1
// === EMERGENCY CACHE CLEAR (DEV) ===
add_action('init', function() {
    if (isset($_GET['clear_dripbox_cache']) && current_user_can('manage_options')) {
        global $wpdb;

        $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_dbx_%'");
        $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_timeout_dbx_%'");

        wp_die('Cache DBX limpo! <a href="javascript:history.back()">Voltar</a>');
    }
});





