<?php

if (!defined('ABSPATH')) exit;
// ✅ FORÇA REGISTRO DE ROTAS
add_action('init', function() {
    if (isset($_GET['dripbox_flush'])) {
        flush_rewrite_rules();
        wp_die('Routes refreshed! Close this tab.');
    }
});

// ==========================================================
// FUNÇÃO GLOBAL DE LOG
// ==========================================================
function dripbox_db_log($type, $data = []) {
    global $wpdb;
    $table = $wpdb->prefix . 'dripbox_logs';

    $wpdb->insert($table, [
        'event_type'  => $type,
        'license_key' => $data['license_key'] ?? null,
        'email'       => $data['email'] ?? null,
        'domain'      => $data['domain'] ?? null,
        'details'     => isset($data['details']) ? json_encode($data['details']) : null
    ]);
}


// ============================================================================
// DATABASE: CREATE OR UPDATE LICENSE TABLE
// ============================================================================
function dripbox_create_license_table() {
    global $wpdb;

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

    // 1. Cria a tabela se não existir (para instalações novas)
    $sql = "
    CREATE TABLE IF NOT EXISTS {$table} (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        license_key VARCHAR(150) NOT NULL,
        plan_type VARCHAR(20) NOT NULL,            -- annual | lifetime
        plan_level VARCHAR(20) NOT NULL,           -- starter | pro | agency
        domain TEXT DEFAULT NULL,                  -- TEXT para aguentar JSON
        domain_limit INT DEFAULT 1,                -- 1 | 5 | 10
        email VARCHAR(200) DEFAULT NULL,
        expires_at DATETIME DEFAULT NULL,
        status VARCHAR(20) NOT NULL DEFAULT 'active',
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        UNIQUE KEY license_key (license_key)
    ) {$charset};
    ";

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

    // 2. Garante colunas novas em atualizações antigas
    $columns = [
        'plan_level'   => "ALTER TABLE {$table} ADD plan_level VARCHAR(20) DEFAULT 'starter'",
        'domain_limit' => "ALTER TABLE {$table} ADD domain_limit INT DEFAULT 1"
    ];

    foreach ($columns as $column => $alter) {
        $exists = $wpdb->get_results("SHOW COLUMNS FROM {$table} LIKE '{$column}'");
        if (empty($exists)) {
            $wpdb->query($alter);
        }
    }
    
    // 3. 🔥 FIX CRÍTICO: Força a conversão de VARCHAR para TEXT 
    // (Isso deve ficar FORA do loop 'if empty', senão nunca atualiza quem já tem a coluna)
    $wpdb->query("ALTER TABLE {$table} MODIFY domain TEXT");
}
register_activation_hook(__FILE__, 'dripbox_create_license_table');





// ============================================================================
// PART 2/7 — LICENSE PAGE (ADMIN) + ACTIVATION LOGIC
// ============================================================================


// ============================================================================
// ADMIN MENU → LICENSE PAGE
// ============================================================================
add_action('admin_menu', 'dripbox_add_license_page');

function dripbox_add_license_page() {
    add_submenu_page(
        'edit.php?post_type=dripbox_product',
        'DripBox License',
        'License',
        'manage_options',
        'dripbox-license',
        'dripbox_license_page_html'
    );
}



// ============================================================================
// LICENSE PAGE HTML (LÓGICA ORIGINAL + UI MODERNA)
// ============================================================================
function dripbox_license_page_html() {
    if (!current_user_can('manage_options')) return;

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

    $raw_host = parse_url(get_site_url(), PHP_URL_HOST);
    $site_domain = str_replace('www.', '', $raw_host);
    $is_server_home = ($site_domain === 'getdripbox.com'); 

    $license = $wpdb->get_row($wpdb->prepare(
        "SELECT * FROM {$table} WHERE domain LIKE %s ORDER BY id DESC LIMIT 1",
        '%' . $wpdb->esc_like($site_domain) . '%'
    ));

    $alert_message = '';

    // --- AÇÃO: SYNC ---
    if (isset($_POST['dripbox_sync_license']) && $license) {
        $api_url = 'https://getdripbox.com/wp-json/dripbox/v2/validate?t=' . time();
        $response = wp_remote_post($api_url, ['body' => ['license_key' => $license->license_key, 'email' => $license->email, 'domain' => $site_domain], 'timeout' => 15]);
        if (!is_wp_error($response)) {
            $data = json_decode(wp_remote_retrieve_body($response), true);
            if (!empty($data['valid']) && !empty($data['used_domains'])) {
                $new_list_str = implode(',', array_filter(array_map('trim', $data['used_domains'])));
                if (!$is_server_home) {
                    $wpdb->update($table, ['domain' => $new_list_str], ['id' => $license->id]);
                    $license = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$table} WHERE id = %d", $license->id));
                }
                $alert_message = '<div class="dripbox-toast success">List synchronized successfully! 🔄</div>';
            }
        }
    }

    // --- AÇÃO: ATIVAR ---
    if (isset($_POST['dripbox_activate_license'])) {
        $license_key = sanitize_text_field($_POST['license_key']);
        $email       = sanitize_email($_POST['email']);
        $api_url = 'https://getdripbox.com/wp-json/dripbox/v2/validate?t=' . time();
        $response = wp_remote_post($api_url, ['body' => ['license_key' => $license_key, 'email' => $email, 'domain' => $site_domain], 'timeout' => 15]);

        if (is_wp_error($response)) {
            $alert_message = '<div class="dripbox-toast error">Connection failed.</div>';
        } else {
            $data = json_decode(wp_remote_retrieve_body($response), true);
            if (empty($data['valid'])) {
                $alert_message = '<div class="dripbox-toast error">' . ($data['message'] ?? 'Error') . '</div>';
            } else {
                $alert_message = '<div class="dripbox-toast success">License activated successfully! 🚀</div>';
                if (!$is_server_home) {
                    $existing = $wpdb->get_row($wpdb->prepare("SELECT id, domain FROM {$table} WHERE license_key = %s", $license_key));
                    $local_list = ($existing && !empty($existing->domain)) ? explode(',', $existing->domain) : [];
                    if (!empty($data['used_domains'])) $local_list = $data['used_domains']; 
                    elseif (!in_array($site_domain, $local_list)) $local_list[] = $site_domain;
                    
                    $db_data = ['license_key' => $license_key, 'plan_type' => $data['plan_type'], 'plan_level' => $data['plan_level'], 'domain_limit' => $data['domain_limit'], 'email' => $email, 'expires_at' => $data['expires_at'] ?? null, 'status' => 'active', 'domain' => implode(',', array_filter(array_map('trim', $local_list)))];

                    if ($existing) $wpdb->update($table, $db_data, ['id' => $existing->id]);
                    else { $db_data['created_at'] = current_time('mysql'); $wpdb->insert($table, $db_data); }
                }
                $license = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$table} WHERE license_key = %s", $license_key));
                if(!empty($data['used_domains'])) $license->temp_used_domains = $data['used_domains'];
            }
        }
    }

    // --- AÇÃO: DESATIVAR ---
    if (isset($_POST['dripbox_deactivate_domain'])) {
        $target_domain = sanitize_text_field($_POST['target_domain']);
        wp_remote_post('https://getdripbox.com/wp-json/dripbox/v2/deactivate?t='.time(), ['body' => ['license_key' => $license->license_key, 'domain_to_remove' => $target_domain], 'timeout' => 15]);

        if ($target_domain === $site_domain) {
            if (!$is_server_home) {
                $curr = explode(',', $license->domain);
                $new = array_filter($curr, function($d) use ($site_domain) { return trim($d) !== $site_domain; });
                if (empty($new)) $wpdb->delete($table, ['id' => $license->id]);
                else $wpdb->update($table, ['domain' => implode(',', $new)], ['id' => $license->id]);
            }
            $license = null;
            $alert_message = '<div class="dripbox-toast success">License deactivated.</div>';
        } else {
            if (!$is_server_home) {
                $curr = explode(',', $license->domain);
                $new = array_filter($curr, function($d) use ($target_domain) { return trim($d) !== $target_domain; });
                $wpdb->update($table, ['domain' => implode(',', $new)], ['id' => $license->id]);
                $license = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$table} WHERE id = %d", $license->id));
            }
            $alert_message = '<div class="dripbox-toast success">Remote domain removed.</div>';
        }
    }

    // ============================================================
    // HTML & CSS VISUAL PREMIUM (REFINADO V3)
    // ============================================================
    ?>
   

    <div class="dripbox-license-wrapper">
        <div class="license-header-hero">
            <h1>
                <svg xmlns="http://www.w3.org/2000/svg" class="header-icon" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
                </svg>
                DripBox License
            </h1>
            <p>Manage your license key to unlock premium features and get updates.</p>
        </div>

        <?php if (!empty($alert_message)) echo $alert_message; ?>

        <div class="license-modern-card">
            <?php if ($license && isset($license->status) && $license->status === 'active'): ?>
                
                <div class="active-header-banner">
                    <div class="banner-status">
                        <span class="pulse"></span> Active
                    </div>
                    <div class="plan-info-banner">
                        <h2><?php echo ucfirst($license->plan_level); ?> Plan</h2>
                        <span class="plan-tag-premium"><?php echo ucfirst($license->plan_type); ?></span>
                    </div>
                </div>

                <div class="license-content-body">
                    <div class="license-details-highlight-box">
                        <div class="detail-item">
                            <span class="label">License Key</span>
                            <div class="code-box"><code><?php echo esc_html($license->license_key); ?></code></div>
                        </div>
                        <div class="detail-item">
                            <span class="label">Registered Email</span>
                            <span class="value"><?php echo esc_html($license->email); ?></span>
                        </div>
                        <div class="detail-item">
                            <span class="label">Renewal Date</span>
                            <span class="value"><?php echo !empty($license->expires_at) ? date('F j, Y', strtotime($license->expires_at)) : 'Lifetime'; ?></span>
                        </div>
                        <div class="detail-item">
                            <span class="label">Domain Limit</span>
                            <span class="value"><?php echo intval($license->domain_limit); ?> Sites</span>
                        </div>
                    </div>

                    <div class="domain-section-wrapper">
                        <?php 
                        if (isset($license->temp_used_domains)) $arr = $license->temp_used_domains;
                        elseif (!empty($license->domain)) $arr = explode(',', $license->domain);
                        else $arr = [$site_domain];
                        $used_domains = array_filter(array_map('trim', $arr));
                        $used_count = count($used_domains);
                        $limit = intval($license->domain_limit);
                        $hub_domain = isset($used_domains[0]) ? $used_domains[0] : '';
                        $am_i_the_hub = ($site_domain === $hub_domain);
                        $slot_counter = 1; 
                        ?>
                        
                        <div class="domain-section-title">
                            <span>Active Installations (<?php echo $used_count; ?> / <?php echo $limit; ?>)</span>
                            <form method="post" style="margin:0;">
                                <button type="submit" name="dripbox_sync_license" class="sync-btn">
                                    <svg xmlns="http://www.w3.org/2000/svg" style="height:14px; width:14px; margin-right:6px;" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" /></svg>
                                    Sync List
                                </button>
                            </form>
                        </div>

                        <div class="active-domains-grid">
                            <?php foreach ($used_domains as $index => $dom): 
                                $is_current = ($dom === $site_domain);
                                $show_button = ($is_current || $am_i_the_hub);
                            ?>
                                <div class="domain-grid-row">
                                    <div class="col-domain">
                                        <span class="slot-number"><?php echo $slot_counter; ?>.</span>
                                        <span><?php echo esc_html($dom); ?></span>
                                    </div>
                                    <div class="col-badges">
                                        <?php if($is_current): ?><span class="badge-premium badge-current">Current Site</span><?php endif; ?>
                                        <?php if($index === 0): ?><span class="badge-premium badge-hub">Main Hub</span><?php endif; ?>
                                    </div>
                                    <div class="col-actions">
                                        <?php if ($show_button): ?>
                                            <form method="post" style="margin:0;">
                                                <input type="hidden" name="target_domain" value="<?php echo esc_attr($dom); ?>">
                                                <button type="submit" name="dripbox_deactivate_domain" class="btn-premium-deactivate" onclick="return confirm('Confirm action for <?php echo $dom; ?>?');">
                                                    <?php echo $is_current ? 'Deactivate' : 'Remote Remove'; ?>
                                                </button>
                                            </form>
                                        <?php else: ?>
                                            <span class="status-text-active">Active</span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php $slot_counter++; endforeach; ?>
                            
                            <?php $remaining = $limit - $used_count;
                            if ($remaining > 0): for ($i = 0; $i < $remaining; $i++): ?>
                                <div class="empty-slot-row">
                                    <span class="slot-number"><?php echo $slot_counter; ?>.</span>
                                    <span class="empty-slot-text">Available Slot</span>
                                </div>
                            <?php $slot_counter++; endfor; endif; ?>
                        </div>
                    </div>
                </div>

            <?php else: ?>
                <div class="license-content-body" style="text-align:center; padding: 60px 30px;">
                    <div style="background:#fff7ed; width:80px; height:80px; border-radius:50%; display:flex; align-items:center; justify-content:center; margin:0 auto 20px auto;">
                        <svg xmlns="http://www.w3.org/2000/svg" style="height:40px; width:40px; color:#f97316;" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z" /></svg>
                    </div>
                    <h3 style="font-size:1.5rem; margin-bottom:10px; color:#111827;">Activate your License</h3>
                    <p style="color:#6b7280; margin-bottom:30px; font-size:1.05rem;">Enter your license key to verify and unlock DripBox Pro.</p>
                    <form method="post" style="max-width:400px; margin:0 auto;">
                        <div style="margin-bottom:15px; text-align:left;"><label style="font-weight:700; display:block; margin-bottom:6px; font-size:0.85rem; color:#374151;">License Key</label><input type="text" name="license_key" placeholder="DBX-XXXX-XXXX-XXXX" required style="width:100%; padding:12px; border:1px solid #d1d5db; border-radius:8px; font-size:1rem;"></div>
                        <div style="margin-bottom:25px; text-align:left;"><label style="font-weight:700; display:block; margin-bottom:6px; font-size:0.85rem; color:#374151;">Email Address</label><input type="email" name="email" placeholder="your@email.com" required style="width:100%; padding:12px; border:1px solid #d1d5db; border-radius:8px; font-size:1rem;"></div>
                        <button type="submit" name="dripbox_activate_license" style="width:100%; background:#f97316; color:white; padding:14px; border:none; border-radius:8px; font-weight:700; cursor:pointer; font-size:1rem; transition: background 0.2s;">Activate License</button>
                    </form>
                </div>
            <?php endif; ?>
        </div>
    </div> 
    <?php
}


// ============================================================================
// PART 3/7 — LICENSE VALIDATION ON PLUGIN LOAD + CONSTANT DEFINITIONS
// ============================================================================


add_action('plugins_loaded', 'dripbox_check_license_status');

function dripbox_check_license_status() {
    global $wpdb;

    $table = $wpdb->prefix . 'dripbox_licenses';
    $site_domain = sanitize_text_field($_SERVER['SERVER_NAME']);

    // Fetch license for this domain
    $license = $wpdb->get_row(
        $wpdb->prepare("
            SELECT *
            FROM {$table}
            WHERE domain = %s AND status = 'active'
            ORDER BY id DESC
            LIMIT 1
        ", $site_domain)
    );

// =============================
    // NO LICENSE -> FREE MODE
    // =============================
    if (!$license) {
        if (!defined('DRIPBOX_IS_PRO')) {
            define('DRIPBOX_IS_PRO', false);
        }
        
        if (!defined('DRIPBOX_PLAN_TYPE')) {
            define('DRIPBOX_PLAN_TYPE', 'free');
        }
        
        if (!defined('DRIPBOX_PLAN_LEVEL')) {
            define('DRIPBOX_PLAN_LEVEL', 'free');
        }
        
        if (!defined('DRIPBOX_DOMAIN_LIMIT')) {
            define('DRIPBOX_DOMAIN_LIMIT', 0);
        }
        
        if (!defined('DRIPBOX_IS_EXPIRED')) {
            define('DRIPBOX_IS_EXPIRED', false);
        }
        return;
    }

    // =============================
    // LIFETIME LICENSE
    // =============================
    if ($license->plan_type === 'lifetime') {

        define('DRIPBOX_IS_PRO', true);
        define('DRIPBOX_PLAN_TYPE', 'lifetime');
        define('DRIPBOX_PLAN_LEVEL', $license->plan_level);
        define('DRIPBOX_DOMAIN_LIMIT', intval($license->domain_limit));
        define('DRIPBOX_IS_EXPIRED', false);
        return;
    }

// =============================
    // ANNUAL LICENSE
    // =============================
    if ($license->plan_type === 'annual') {

        $now      = current_time('timestamp');
        $expires = strtotime($license->expires_at);

        if ($expires >= $now) {

            // ACTIVE ANNUAL LICENSE
            define('DRIPBOX_IS_PRO', true);
            define('DRIPBOX_PLAN_TYPE', 'annual');
            define('DRIPBOX_PLAN_LEVEL', $license->plan_level);
            define('DRIPBOX_DOMAIN_LIMIT', intval($license->domain_limit));
            define('DRIPBOX_IS_EXPIRED', false);
            return;

        } else {

            // =============================
            // LICENSE EXPIRED — DOWNGRADE
            // =============================
            $wpdb->update(
                $table,
                ['status' => 'expired'],
                ['id' => $license->id]
            );
            
            // LOG: licença expirada automaticamente
            dripbox_db_log('auto_expired', [
                'license_key' => $license->license_key,
                'domain'      => $license->domain,
                'details'     => ['expired_at' => $license->expires_at]
            ]);


            define('DRIPBOX_IS_PRO', false);
            define('DRIPBOX_PLAN_TYPE', 'free');
            define('DRIPBOX_PLAN_LEVEL', 'free');
            define('DRIPBOX_DOMAIN_LIMIT', 0);
            define('DRIPBOX_IS_EXPIRED', true);
            return;
        }
    }

    // =============================
    // SAFETY FALLBACK
    // =============================
    define('DRIPBOX_IS_PRO', false);
    define('DRIPBOX_PLAN_TYPE', 'free');
    define('DRIPBOX_PLAN_LEVEL', 'free');
    define('DRIPBOX_DOMAIN_LIMIT', 0);
    define('DRIPBOX_IS_EXPIRED', false);
}



// ============================================================================
// FREE MODE LIMITATIONS (LIMIT TO 2 PRODUCTS)
// ============================================================================

add_action('init', 'dripbox_apply_free_rules');

function dripbox_apply_free_rules() {

    // PRO → libera tudo
    if (defined('DRIPBOX_IS_PRO') && DRIPBOX_IS_PRO === true) {
        dripbox_unlock_all_products();
        return;
    }

    // FREE MODE — trava acima de 2 produtos
    dripbox_lock_extra_products();
}



// ============================================================================
// LOCK EXTRA PRODUCTS ABOVE LIMIT
// ============================================================================
function dripbox_lock_extra_products() {
    // Busca todos os produtos ordenados por data
    $products = get_posts([
        'post_type'      => 'dripbox_product',
        'posts_per_page' => -1,
        'orderby'        => 'date',
        'order'          => 'ASC'
    ]);

    if (!$products) return;

    // Separa os 2 primeiros (permitidos) do resto (bloqueados)
    $allowed = array_slice($products, 0, 2);
    $blocked = array_slice($products, 2);

    foreach ($allowed as $p) {
        update_post_meta($p->ID, 'dripbox_locked', '0');
    }

    foreach ($blocked as $p) {
        update_post_meta($p->ID, 'dripbox_locked', '1');
    }
}

// ============================================================================
// UNLOCK ALL PRODUCTS WHEN PRO
// ============================================================================
function dripbox_unlock_all_products() {
    $products = get_posts([
        'post_type'      => 'dripbox_product',
        'posts_per_page' => -1
    ]);

    if (!$products) return;

    foreach ($products as $p) {
        update_post_meta($p->ID, 'dripbox_locked', '0');
    }
}

// ============================================================================
// ADMIN WARNING WHEN FREE LIMIT REACHED
// ============================================================================
add_action('admin_notices', 'dripbox_free_limit_notice');

function dripbox_free_limit_notice() {
    // Se for PRO, não mostra nada
    if (defined('DRIPBOX_IS_PRO') && DRIPBOX_IS_PRO === true) return;

    // Só mostra na tela de listagem de produtos ou no dashboard
    $screen = get_current_screen();
    if ($screen->id !== 'edit-dripbox_product' && $screen->id !== 'dashboard') return;

    $count = wp_count_posts('dripbox_product')->publish;

    // =============================
    // FREE PLAN OK (0 ou 1 produto)
    // =============================
    if ($count < 2) {
        ?>
        <div class="notice dripbox-notice success">
            <span class="icon">✅</span>
            <div>
                You are using the <strong>Free plan</strong>.<br>
                You can create up to <strong>2 products</strong>.
            </div>
        </div>
        <?php
        return;
    }

    // =============================
    // FREE PLAN LIMIT REACHED (2+)
    // =============================
    if ($count >= 2) {
        ?>
        <div class="notice dripbox-notice warning">
            <span class="icon">⚠️</span>
            <div>
                You have reached the limit of 2 products in the Free plan. 
                <a href="<?php echo admin_url('edit.php?post_type=dripbox_product&page=dripbox-upgrade'); ?>">
                    Upgrade now
                </a> 
                to unlock unlimited products.
            </div>
        </div>
        <?php
    }
}




// ============================================================================
// PART 4/7 — PRODUCT LOCKING RULES, FREE LIMITS, ADMIN RESTRICTIONS
// ============================================================================

// ============================================================================
// 1. HIDE "ADD NEW" BUTTON (CSS CLASS METHOD)
// ============================================================================
add_filter('admin_body_class', function($classes) {
    // Só roda na tela do nosso post type
    $screen = get_current_screen();
    if (!$screen || $screen->post_type !== 'dripbox_product') return $classes;

    // Se for PRO, vida normal
    if (defined('DRIPBOX_IS_PRO') && DRIPBOX_IS_PRO === true) return $classes;

    // Se for FREE e estourou o limite
    $count = wp_count_posts('dripbox_product')->publish;
    if ($count >= 2) {
        $classes .= ' dripbox-limit-reached'; // O CSS esconde o botão
    }

    return $classes;
});

// ============================================================================
// 2. BLOCK ACCESS TO "ADD NEW" PAGE (REDIRECT)
// ============================================================================
add_action('load-post-new.php', function() {
    if (!isset($_GET['post_type']) || $_GET['post_type'] !== 'dripbox_product') return;

    if (defined('DRIPBOX_IS_PRO') && DRIPBOX_IS_PRO === true) return;

    $count = wp_count_posts('dripbox_product')->publish;

    if ($count >= 2) {
        wp_redirect(admin_url('edit.php?post_type=dripbox_product&page=dripbox-upgrade'));
        exit;
    }
});

// ============================================================================
// 3. PREVENT SAVE (SECURITY BACKUP)
// ============================================================================
add_action('save_post_dripbox_product', function($post_id, $post, $update){
    // Permite atualizações de produtos existentes
    if ($update === true) return;

    // Se for PRO, libera
    if (defined('DRIPBOX_IS_PRO') && DRIPBOX_IS_PRO === true) return;

    $count = wp_count_posts('dripbox_product')->publish;

    // Se tentar salvar o 3º produto via código ou hack
    if ($count >= 2) {
        // Deleta o rascunho imediatamente
        wp_delete_post($post_id, true);

        wp_die(
            '<h1>Limit Reached</h1>
             <p>You have reached the limit of 2 products in the FREE plan.</p>
             <p><a href="' . admin_url('edit.php?post_type=dripbox_product&page=dripbox-upgrade') . '" class="button button-primary">Upgrade to PRO</a></p>'
        );
    }
}, 10, 3);

// ============================================================================
// 4. SHOW WARNING INSIDE LOCKED PRODUCTS
// ============================================================================
add_action('edit_form_after_title', function($post) {
    if ($post->post_type !== 'dripbox_product') return;

    $locked = get_post_meta($post->ID, 'dripbox_locked', true);

    if ($locked === '1') {
        ?>
        <div class="dripbox-locked-banner">
            <strong>🔒 This product is locked.</strong>
            <span>Your plan allows only 2 products in the Free version. This product is currently inactive on the frontend.</span><br>
            <a href="<?php echo admin_url('edit.php?post_type=dripbox_product&page=dripbox-upgrade'); ?>">
                Upgrade to unlock all products instantly.
            </a>
        </div>
        <?php
    }
});

// ============================================================================
// HELPER: CENTRAL PERMISSION CHECK
// ============================================================================
function dripbox_is_premium_allowed() {
    if (!defined('DRIPBOX_IS_PRO')) return false;
    return (DRIPBOX_IS_PRO === true);
}

// ============================================================================
// HELPER: REQUIRE PRO FEATURE (OR SHOW NOTICE)
// ============================================================================
function dripbox_require_pro_feature() {
    if (dripbox_is_premium_allowed()) {
        return true; // allowed
    }

    add_action('admin_notices', function() {
        ?>
        <div class="notice notice-error is-dismissible">
            <p>
                <strong>PRO Feature:</strong> This feature is available only in the premium version. 
                <a href="<?php echo admin_url('edit.php?post_type=dripbox_product&page=dripbox-upgrade'); ?>">Upgrade Now</a>
            </p>
        </div>
        <?php
    });

    return false;
}




// ============================================================================
// PART 6/7 — UPGRADE PAGE (STRIPE CHECKOUT)
// ============================================================================

// Add submenu "Upgrade to PRO" under DripBox license menu
add_action('admin_menu', 'dripbox_register_upgrade_page');

function dripbox_register_upgrade_page() {
    // Não mostrar "Upgrade to PRO" se já for lifetime
    if (defined('DRIPBOX_PLAN_TYPE') && DRIPBOX_PLAN_TYPE === 'lifetime') {
        return;
    }

    add_submenu_page(
        'edit.php?post_type=dripbox_product',
        'Upgrade to PRO',
        'Upgrade to PRO',
        'manage_options',
        'dripbox-upgrade',
        'dripbox_upgrade_page_html'
    );
}

// ============================================================================
// UPGRADE PAGE HTML
// ============================================================================
function dripbox_upgrade_page_html() {
    // Links de Pagamento do Stripe (Gere no Stripe Dashboard -> Payment Links)
    // Substitua os # abaixo pelos seus links reais (ex: https://buy.stripe.com/...)
    
    // Anuais
    $link_starter_annual = '#'; 
    $link_pro_annual     = '#'; 
    $link_agency_annual  = '#'; 

    // Lifetime
    $link_starter_life   = '#'; 
    $link_pro_life       = '#'; 
    $link_agency_life    = '#'; 

    ?>
    <div class="wrap dripbox-upgrade-premium view-lifetime" id="pricing-container">

        <div class="header-upgrade">
            <h1>Upgrade to DripBox <span class="text-orange">PRO</span></h1>
            <p class="subtitle">
                Unlock unlimited products, premium layouts, and remove all limits.
            </p>

            <div class="pricing-toggle-wrapper">
                <span class="toggle-label">Annual</span>
                <label class="switch">
                    <input type="checkbox" id="plan-toggle" checked>
                    <span class="slider round"></span>
                </label>
                <span class="toggle-label active-label">
                    Lifetime 
                    <span class="save-badge">One-time Payment</span>
                </span>
            </div>
        </div>

        <div class="plan-grid">

            <div class="plan-card">
                <div class="card-header">
                    <h3>Starter</h3>
                    <p class="desc">For single site owners</p>
                </div>
                
                <div class="pricing-display">
                    <div class="price-box lifetime-content">
                        <span class="currency">$</span>149<span class="period">/once</span>
                    </div>
                    <div class="price-box annual-content">
                        <span class="currency">$</span>49<span class="period">/year</span>
                    </div>
                </div>

                <ul class="features">
                    <li><strong>1 Site</strong> license</li>
                    <li>Unlimited products</li>
                    <li>Premium layouts</li>
                    <li>Standard Support</li>
                </ul>

                <div class="action-area">
                    <a href="<?php echo $link_starter_life; ?>" target="_blank" class="btn-upgrade btn-outline lifetime-content">Get Starter Lifetime</a>
                    <a href="<?php echo $link_starter_annual; ?>" target="_blank" class="btn-upgrade btn-outline annual-content">Get Starter Annual</a>
                </div>
            </div>

            <div class="plan-card featured-card">
                <div class="best-value-badge">BEST VALUE</div>
                <div class="card-header">
                    <h3>Pro</h3>
                    <p class="desc">For growing portfolios</p>
                </div>
                
                <div class="pricing-display">
                    <div class="price-box lifetime-content">
                        <span class="currency">$</span>299<span class="period">/once</span>
                    </div>
                    <div class="price-box annual-content">
                        <span class="currency">$</span>99<span class="period">/year</span>
                    </div>
                </div>

                <ul class="features">
                    <li><strong>5 Sites</strong> license</li>
                    <li><strong>All Premium Layouts</strong></li>
                    <li><strong>Priority Support</strong></li>
                    <li>Remove Branding</li>
                </ul>

                <div class="action-area">
                    <a href="<?php echo $link_pro_life; ?>" target="_blank" class="btn-upgrade btn-orange lifetime-content">Get Pro Lifetime</a>
                    <a href="<?php echo $link_pro_annual; ?>" target="_blank" class="btn-upgrade btn-orange annual-content">Get Pro Annual</a>
                </div>
            </div>

            <div class="plan-card">
                <div class="card-header">
                    <h3>Agency</h3>
                    <p class="desc">Volume & Client sites</p>
                </div>
                
                <div class="pricing-display">
                    <div class="price-box lifetime-content">
                        <span class="currency">$</span>499<span class="period">/once</span>
                    </div>
                    <div class="price-box annual-content">
                        <span class="currency">$</span>199<span class="period">/year</span>
                    </div>
                </div>

                <ul class="features">
                    <li><strong>10 Sites</strong> license</li>
                    <li>All Pro Features</li>
                    <li>Client Management</li>
                    <li>VIP Support</li>
                </ul>

                <div class="action-area">
                    <a href="<?php echo $link_agency_life; ?>" target="_blank" class="btn-upgrade btn-outline lifetime-content">Get Agency Lifetime</a>
                    <a href="<?php echo $link_agency_annual; ?>" target="_blank" class="btn-upgrade btn-outline annual-content">Get Agency Annual</a>
                </div>
            </div>

        </div>
        
        <p class="garantee-text">30-Day Money Back Guarantee. Secure payment via Stripe.</p>

    </div>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const toggle = document.getElementById('plan-toggle');
        const container = document.getElementById('pricing-container');
        
        toggle.addEventListener('change', function() {
            if(this.checked) {
                // Modo Lifetime
                container.classList.remove('view-annual');
                container.classList.add('view-lifetime');
            } else {
                // Modo Annual
                container.classList.remove('view-lifetime');
                container.classList.add('view-annual');
            }
        });
    });
    </script>
    <?php
}



