<?php
/*
 * Dripbox Table – módulo de listagem múltipla de produtos
 * Versão 1.1 – com coluna "Our Verdict" e âncora interna no botão
 */

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

// === 1️⃣ REGISTRA NOVO CUSTOM POST TYPE ===
function dripbox_register_cpt_table() {
    $labels = array(
        'name' => 'Dripbox Tables',
        'singular_name' => 'Dripbox Table',
        'menu_name' => 'Tables',
        'add_new' => 'Add New Table',
        'add_new_item' => 'Add New Dripbox Table',
        'edit_item' => 'Edit Table',
        'new_item' => 'New Table',
        'view_item' => 'View Table',
        'search_items' => 'Search Tables',
        'not_found' => 'No tables found',
        'not_found_in_trash' => 'No tables found in Trash',
    );

    $args = array(
        'labels' => $labels,
        'public' => false,
        'show_ui' => true,
        'show_in_menu' => 'edit.php?post_type=dripbox_product',
        'menu_icon' => 'dashicons-list-view',
        'supports' => array('title'),
        'capability_type' => 'post',
    );

    register_post_type('dripbox_table', $args);
}
add_action('init', 'dripbox_register_cpt_table');


// === 2️⃣ ADICIONA METABOX PARA IDS DE PRODUTOS ===
function dripbox_add_table_metabox() {
    add_meta_box(
        'dripbox_table_products',
        'Products in this Table',
        'dripbox_render_table_metabox',
        'dripbox_table',
        'normal',
        'high'
    );
}
add_action('add_meta_boxes', 'dripbox_add_table_metabox');

function dripbox_render_table_metabox($post) {
    $meta = get_post_meta($post->ID);
    $product_ids = esc_textarea($meta['product_ids'][0] ?? '');
    ?>
    <style>
        .dripbox-table-metabox textarea {
            width: 100%;
            height: 100px;
            border-radius: 6px;
            border: 1px solid #ccc;
            font-family: monospace;
            font-size: 14px;
            padding: 8px;
        }
        .dripbox-table-help {
            font-size: 13px;
            color: #555;
            margin-top: 6px;
        }
    </style>
    <div class="dripbox-table-metabox">
        <label for="product_ids"><strong>Enter Product IDs</strong> (comma-separated)</label>
        <textarea name="product_ids" placeholder="Ex: 12, 45, 87, 102"><?php echo $product_ids; ?></textarea>
        <p class="dripbox-table-help">Add the IDs of existing Dripbox Products, separated by commas.</p>
    </div>
    <?php
}

function dripbox_save_table_metabox($post_id) {
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (isset($_POST['product_ids'])) {
        update_post_meta($post_id, 'product_ids', sanitize_text_field($_POST['product_ids']));
    }
}
add_action('save_post_dripbox_table', 'dripbox_save_table_metabox');


// === 3️⃣ SHORTCODE [dripbox_table id="X"] ===
function dripbox_table_shortcode($atts) {
    $atts = shortcode_atts(array(
        'id' => ''
    ), $atts);

    if (empty($atts['id'])) return '<!-- Missing table ID -->';

    $table_id = intval($atts['id']);
    $product_ids_str = get_post_meta($table_id, 'product_ids', true);
    if (empty($product_ids_str)) return '<!-- No products found -->';

    $product_ids = array_map('intval', explode(',', $product_ids_str));
    $products = [];

    foreach ($product_ids as $pid) {
        $post = get_post($pid);
        if (!$post || $post->post_type !== 'dripbox_product') continue;

        $meta = get_post_meta($pid);
        $products[] = array(
            'id'      => $pid,
            'title'   => get_the_title($pid),
            'img'     => esc_url($meta['img'][0] ?? ''),
            'badge'   => esc_html($meta['badge'][0] ?? ''),
            'why'     => esc_html($meta['why'][0] ?? ''),
            'head'    => esc_html($meta['head'][0] ?? ''),
            'verdict' => esc_html($meta['verdict'][0] ?? ''),
            'amazon'  => esc_url($meta['amazon'][0] ?? ''), // ✅ ADICIONADO
        );
    }

    if (empty($products)) return '<!-- No valid products found -->';


// === Renderização visual estilo Wirecutter ===
ob_start(); ?>
<div class="dripbox-wirecutter-wrapper">
    <h3 class="dtw-heading">Top Picks Overview</h3> <!-- nome pode mudar depois -->
    <div class="dtw-list">
<?php foreach ($products as $p) : ?>
   <div class="dtw-item">

    <!-- 1️⃣ IMAGEM PRIMEIRO -->
    <?php if ($p['img']) : ?>
        <div class="dtw-left">
            <img src="<?php echo $p['img']; ?>" alt="<?php echo esc_attr($p['title']); ?>">
        </div>
    <?php endif; ?>

    <!-- 2️⃣ BADGE + TÍTULO -->
    <?php if ($p['head'] || $p['title']) : ?>
        <div class="dtw-center">
            <?php if ($p['head']) : ?>
                <div class="dtw-badge"><?php echo esc_html($p['head']); ?></div>
            <?php endif; ?>
            <h4 class="dtw-title"><?php echo esc_html($p['title']); ?></h4>
        </div>
    <?php endif; ?>

    <!-- 3️⃣ VERDICT -->
    <?php if ($p['verdict']) : ?>
        <div class="dtw-middle">
            <?php echo esc_html($p['verdict']); ?>
        </div>
    <?php endif; ?>

    <!-- 4️⃣ BOTÃO DUPLO -->
    <div class="dtw-right">
        <?php if (!empty($p['amazon'])) : ?>
            <a href="<?php echo esc_url($p['amazon']); ?>" 
               class="dtw-btn" 
               target="_blank" 
               rel="nofollow noopener">
                See It
            </a>
            <a href="javascript:void(0);" 
               class="dtw-review-link see-it-anchor" 
               data-product-id="<?php echo $p['id']; ?>">
                Read our Review ↓
            </a>
        <?php else : ?>
            <a href="javascript:void(0);" 
               class="dtw-btn see-it-anchor" 
               data-product-id="<?php echo $p['id']; ?>">
                See It
            </a>
        <?php endif; ?>
    </div>

</div>
<?php endforeach; ?>

    </div>
</div>
<?php
return ob_get_clean();
}
add_shortcode('dripbox_table', 'dripbox_table_shortcode');



// === 4️⃣ SHORTCODE NO ADMIN ===
function dripbox_table_shortcode_box($post) {
    if ($post->post_type !== 'dripbox_table') return;
    $shortcode = '[dripbox_table id="' . $post->ID . '"]';
    echo '<div style="background:#f6f7f7;border:1px solid #ccd0d4;padding:12px 15px;border-radius:6px;margin-top:10px;">';
    echo '<strong>Shortcode:</strong><br>';
    echo '<input type="text" readonly value="' . esc_attr($shortcode) . '" style="width:100%;font-family:monospace;padding:6px 8px;">';
    echo '<p style="margin:6px 0 0;font-size:13px;color:#555;">Use this shortcode in a post to display the table.</p>';
    echo '</div>';
}
add_action('edit_form_after_title', 'dripbox_table_shortcode_box');


// === 5️⃣ COLUNA SHORTCODE NA LISTAGEM ADMIN ===
function dripbox_table_add_shortcode_column($columns) {
    $columns['shortcode'] = 'Shortcode';
    return $columns;
}
add_filter('manage_dripbox_table_posts_columns', 'dripbox_table_add_shortcode_column');

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

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



?>
