<?php
/**
 * Template Etapa 2: Seleção de Posts
 * Checkout em Página - Baseado em select-posts.php
 */

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

// Verificar se há itens no carrinho
$cart = WC()->cart;
if ($cart->is_empty()) {
    $checkout_page_id = get_option('upgram_checkout_page_id', 0);
    $checkout_page_url = $checkout_page_id ? get_permalink($checkout_page_id) : '';
    echo '<div style="max-width: 800px; margin: 40px auto; padding: 30px; background: #fff; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
        <h2 style="margin-top: 0; color: #333;">Carrinho vazio</h2>
        <p>Por favor, complete a etapa 1 primeiro.</p>
        <a href="' . esc_url($checkout_page_url ? $checkout_page_url . '?step=1' : '') . '" style="display: inline-block; margin-top: 15px; padding: 12px 24px; background: #7C51F3; color: #fff; text-decoration: none; border-radius: 8px;">Voltar para etapa 1</a>
    </div>';
    return;
}

// Obter primeiro item do carrinho (assumindo que há apenas um produto principal)
$cart_items = $cart->get_cart();
$first_cart_item = reset($cart_items);
$cart_item_key = key($cart_items);
$cart_item = $first_cart_item;
$product = $cart_item['data'];

if (!$product) {
    echo '<div style="max-width: 800px; margin: 40px auto; padding: 30px; background: #fff; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
        <h2 style="margin-top: 0; color: #333;">Produto não encontrado</h2>
        <p>O produto no carrinho não existe mais.</p>
    </div>';
    return;
}

$product_id = $product->get_parent_id();
$service_type = get_post_meta($product_id, '_upgram_service_type', true);
$social_media = get_post_meta($product_id, '_upgram_social_media', true);
$is_stories = $service_type === 'visualizacoes_story';
$is_instagram = $social_media === 'instagram';

// Verificar se precisa selecionar posts
$allows_select_posts = $is_instagram && in_array($service_type, ['curtidas', 'visualizacoes', 'visualizacoes_story']);
$strategy = isset($cart_item['strategy']) ? $cart_item['strategy'] : 'select_posts';

// Se não precisa selecionar posts, pular para etapa 3
if (!$allows_select_posts || $strategy !== 'select_posts') {
    $checkout_page_id = get_option('upgram_checkout_page_id', 0);
    $checkout_page_url = $checkout_page_id ? get_permalink($checkout_page_id) : '';
    if ($checkout_page_url) {
        wp_redirect($checkout_page_url . '?step=3');
        exit;
    }
}

$total_likes_count = max(1, intval(get_post_meta($product->get_id(), '_total_quantity', true)));
$min_likes_per_post = max(1, intval(get_post_meta($product->get_id(), '_min_per_post_instagram', true)));

// Obter URL da página de checkout
$checkout_page_id = get_option('upgram_checkout_page_id', 0);
$checkout_page_url = $checkout_page_id ? get_permalink($checkout_page_id) : '';

// Cores do checkout
$background_color = get_option('upgram_checkout_background_color');
$text_color = get_option('upgram_checkout_text_color');
$button_color1 = get_option('upgram_checkout_button_color1') ?: '#2161DF';
$button_color2 = get_option('upgram_checkout_button_color2') ?: '#DB265C';
?>

<div class="upgram-checkout-page" style="max-width: 800px; margin: 40px auto; padding: 30px; background: #fff; border-radius: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);
     <?php echo $background_color ? "--upgram-checkout-background-color: $background_color;" : ''; ?>
     <?php echo $text_color ? "--upgram-checkout-text-color: $text_color;" : ''; ?>
">
    <!-- Indicador de Etapas -->
    <div class="upgram-checkout-steps" style="display: flex; justify-content: space-between; margin-bottom: 30px; position: relative;">
        <div class="step-indicator completed" style="flex: 1; text-align: center; position: relative; z-index: 2;">
            <div style="width: 40px; height: 40px; border-radius: 50%; background: #22c55e; color: #fff; display: flex; align-items: center; justify-content: center; margin: 0 auto 10px; font-weight: bold;">✓</div>
            <span style="font-size: 14px; color: #22c55e;">Informações</span>
        </div>
        <div class="step-indicator active" style="flex: 1; text-align: center; position: relative; z-index: 2;">
            <div style="width: 40px; height: 40px; border-radius: 50%; background: linear-gradient(to right, <?php echo $button_color1; ?>, <?php echo $button_color2; ?>); color: #fff; display: flex; align-items: center; justify-content: center; margin: 0 auto 10px; font-weight: bold;">2</div>
            <span style="font-size: 14px; color: var(--upgram-checkout-text-color, #333);">Selecionar Posts</span>
        </div>
        <div class="step-indicator" style="flex: 1; text-align: center; position: relative; z-index: 2;">
            <div style="width: 40px; height: 40px; border-radius: 50%; background: #e0e0e0; color: #999; display: flex; align-items: center; justify-content: center; margin: 0 auto 10px; font-weight: bold;">3</div>
            <span style="font-size: 14px; color: #999;">Pagamento</span>
        </div>
        <div style="position: absolute; top: 20px; left: 0; right: 0; height: 2px; background: #e0e0e0; z-index: 1;"></div>
        <div style="position: absolute; top: 20px; left: 0; width: 50%; height: 2px; background: linear-gradient(to right, <?php echo $button_color1; ?>, <?php echo $button_color2; ?>); z-index: 1;"></div>
    </div>

    <div class="row d-flex justify-content-center">
        <div class="col-auto" style="width: 100%;">
            <div class="d-flex mb-3">
                <div style="margin-right: auto;">
                    <a href="<?php echo esc_url($checkout_page_url ? $checkout_page_url . '?step=1' : ''); ?>" style="text-decoration: none;">
                        <i class="bi bi-arrow-left-circle-fill" style="font-size: xx-large; color:#614DDD; cursor: pointer;"></i>
                    </a>
                </div>
                <div style="margin-left: auto; opacity:0.25;position: relative;">
                    <i class="bi bi-cart-fill" style="font-size:xx-large; color:#2161DF;"></i>
                    <span id="cart-icon-count" style="position: absolute; top: auto; right: -4px; background-color: #14B811; color: white; border-radius: 50%; padding: 1px 6px; width: 20px; height: 20px; font-size: 12px; display: inline-flex; justify-content: center; align-items: center;">
                        <?php echo esc_attr($cart->get_cart_contents_count()); ?>
                    </span>
                </div>
            </div>

            <?php
            foreach ($cart_items as $cart_item_key => $cart_item) {
                $cart_item_product = $cart_item['data'];
                $item_service_type = get_post_meta($cart_item_product->get_parent_id(), '_upgram_service_type', true);
                $item_social_media = get_post_meta($cart_item_product->get_parent_id(), '_upgram_social_media', true);
                $has_custom_social_media_symbol = $item_social_media === 'youtube' && $item_service_type === 'visualizacoes';
            ?>
                <div class="gap-3 p-3 p-lg-4 border rounded mb-3" style="display: grid; grid-template-columns: auto 1fr;">
                    <div class="d-flex align-items-center justify-content-center rounded-circle" style="height: 56px; width: 56px; background: #6A51B0; border: 2.8px solid #C8B9F0">
                        <svg width="28" height="28" color="white">
                            <use xlink:href="<?php echo esc_attr(UPGRAM_URL . 'assets/images/service-symbol-sprite.svg#' . $item_service_type . ($has_custom_social_media_symbol ? "_{$item_social_media}" : '')); ?>" />
                        </svg>
                    </div>
                    <div class="flex-shrink-1">
                        <p style="font-family: Manrope, 'sans-serif'; font-size: large; color: var(--upgram-checkout-text-color, #202029); font-weight: 700; margin-bottom: 0rem;">
                            <?php echo esc_html(implode(' - ', $cart_item_product->get_attributes())); ?>
                        </p>
                        <a style="font-family: Manrope, 'sans-serif'; font-weight: 500; font-size: 18px; color: var(--upgram-checkout-text-color, #515063);">
                            <?php echo wc_price($cart_item_product->get_price()); ?>
                        </a>
                    </div>
                </div>
            <?php } ?>

            <!-- Instruções -->
            <div class="mt-3 w-100 mb-3">
                <p class="text-select-imagens" style="font-size: 16px; color: var(--upgram-checkout-text-color, #333);">
                    Clique em cima das <?php echo $is_stories ? 'stories' : 'imagens'; ?> que deseja receber o serviço <b><?php echo esc_html(implode(' - ', $product->get_attributes())); ?></b>.
                </p>
                <?php 
                $cache_info_message = get_option('upgram_cache_info_message', 'ℹ️ Informação: Para que novas postagens apareçam, é necessário clicar no botão "Limpar cache" abaixo.');
                ?>
                <div class="upgram-cache-info-message" style="background: #f0f9ff; border: 1px solid #bae6fd; border-radius: 8px; padding: 12px; margin-top: 12px; font-size: 13px; color: #0369a1;">
                    <?php echo wp_kses_post($cache_info_message); ?>
                </div>
            </div>

            <!-- Posts Section -->
            <div id="upgram-posts" x-data="{ selected: [], total: <?php echo esc_attr($total_likes_count); ?>, min: <?php echo esc_attr($min_likes_per_post); ?>}" class="container col-auto d-flex insta-posts-list p-0 justify-content-center" style="margin-bottom: 20px;">
                <?php 
                if ($is_stories) {
                    include UPGRAM_PATH . 'templates/stories.php';
                } else {
                    include UPGRAM_PATH . 'templates/posts.php';
                }
                ?>
            </div>

            <div class="loading-state d-none">
                <div class="loading"></div>
            </div>

            <!-- Botão Limpar Cache -->
            <div class="d-flex align-items-stretch justify-content-center flex-column mt-2 mb-2">
                <button id="upgram-clear-posts-cache" type="button" class="btn btn-outline-primary" style="margin-bottom: 10px;">
                    <?php echo esc_html(get_option('upgram_clear_cache_button_text', '🔄 Limpar Cache')); ?>
                </button>
            </div>

            <!-- Botão Continuar -->
            <div class="d-flex align-items-stretch justify-content-center flex-column w-100 mt-3">
                <a href="<?php echo esc_url($checkout_page_url ? $checkout_page_url . '?step=3' : ''); ?>" class="btn d-flex w-100 align-items-center justify-content-center mb-2" style="border-radius: 12px; background-image: linear-gradient(to right, <?php echo $button_color1; ?>, <?php echo $button_color2; ?>); height: 67px; box-shadow: 0px 4px 32px 0px #00000040; text-decoration: none;">
                    <span style="color: #FFFFFF; font-weight: bold; margin-right: 10px">Continuar</span>
                    <img src="<?php echo esc_attr(UPGRAM_URL); ?>/assets/images/arrow-right.svg" alt="arrow-right">
                </a>
                <div class="mt-3">
                    <div class="mx-auto d-flex justify-content-center align-items-center gap-3">
                        <img width="35" height="35" src="<?php echo esc_attr(UPGRAM_URL); ?>/assets/images/safety.png">
                        <span style="color: var(--upgram-checkout-text-color, #4A2F9473);"><?php echo esc_attr(get_option('upgram_safe_purchase_text') ?: 'Compra 100% segura'); ?></span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

