<?php
/**
 * Template Etapa 1: Coleta de Informações
 * Checkout em Página - Baseado em initial-modal.php
 */

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

// Obter variation_id da URL
$variation_id = isset($_GET['variation_id']) ? intval($_GET['variation_id']) : 0;
if (empty($variation_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;">Produto não encontrado</h2>
        <p>Por favor, selecione um produto na página do produto.</p>
        <a href="' . esc_url(wc_get_page_permalink('shop')) . '" style="display: inline-block; margin-top: 15px; padding: 12px 24px; background: #7C51F3; color: #fff; text-decoration: none; border-radius: 8px;">Voltar para a loja</a>
    </div>';
    return;
}

$product = wc_get_product($variation_id);
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 selecionado não existe mais.</p>
        <a href="' . esc_url(wc_get_page_permalink('shop')) . '" style="display: inline-block; margin-top: 15px; padding: 12px 24px; background: #7C51F3; color: #fff; text-decoration: none; border-radius: 8px;">Voltar para a loja</a>
    </div>';
    return;
}

// Carregar funções auxiliares do initial-modal
require_once UPGRAM_PATH . 'templates/initial-modal.php';

// Preparar variáveis necessárias (similar a load_initial_modal)
$related_products = $product->get_cross_sell_ids();
$parent_product_id = $product->get_parent_id();
$social_media = get_post_meta($parent_product_id, '_upgram_social_media', true);
$service_type = get_post_meta($parent_product_id, '_upgram_service_type', true);
$is_instagram = $social_media === 'instagram';
$is_comments = $service_type === 'comentarios';
$is_subscription = get_post_meta($parent_product_id, '_upgram_is_subscription_service', true) === 'yes';
$package_total_quantity = max(1, intval(get_post_meta($variation_id, '_total_quantity', 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';
$skip_seguidores_instructions = true;
?>

<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 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;">1</div>
            <span style="font-size: 14px; color: var(--upgram-checkout-text-color, #333);">Informações</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;">2</div>
            <span style="font-size: 14px; color: #999;">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>

    <form id="upgram-checkout-form-step1" x-data="{ additional: {} }" method="POST" action="<?php echo esc_url($checkout_page_url ? $checkout_page_url . '?step=2' : ''); ?>">
        <div class="form-check mb-3" style="display:flex;align-items:center;gap:4px;">
            <input class="form-check-input" type="checkbox" id="remember-checkout" style="border-radius:100%" checked name="remember">
            <label class="form-check-label save-info-label" for="remember-checkout">
                Salvar informações para próximas compras
            </label>
        </div>
        
        <div>
            <?php if (get_option('upgram_enable_field_name', true)): ?>
                <div class="title-main d-flex gap-3 mb-3">
                    <label class="upgram-input">
                        <span><i class="bi bi-person" style="color: #614DDD; font-size: 24px;"></i></span>
                        <input required name="name" type="text" placeholder="Nome" aria-label="Nome" value="<?php echo esc_attr(isset($_SESSION['name']) ? $_SESSION['name'] : ''); ?>">
                    </label>
                </div>
            <?php endif ?>

            <?php echo render_links_fields($product, ['required' => true]); ?>

            <?php if (isset($is_subscription) && $is_subscription): ?>
                <?php echo render_subscription_fields($product, isset($package_total_quantity) ? $package_total_quantity : 0); ?>
            <?php endif; ?>

            <?php if ($is_comments): ?>
                <?php echo render_comments_field($product, 'comments'); ?>
            <?php endif; ?>

            <?php if (!empty($related_products)): ?>
                <div class="upgram-other-products mb-3">
                    <div style="width: 100%;">
                        <h5 style="font-weight: 500; font-size: 18px; font-family: 'Poppins', sans-serif; color: var(--upgram-checkout-text-color);" class="mb-3">Outros produtos</h5>
                        <?php
                        $total_items = count($related_products);
                        foreach ($related_products as $index => $related_product_id):
                            $related_product = wc_get_product($related_product_id);
                            if (!$related_product) continue;
                            
                            if ($related_product->is_type('variation')) {
                                $parent_id = $related_product->get_parent_id();
                                $related_service_type = get_post_meta($parent_id, '_upgram_service_type', true);
                                $related_social_media = get_post_meta($parent_id, '_upgram_social_media', true);
                            } else {
                                $related_service_type = get_post_meta($related_product_id, '_upgram_service_type', true);
                                $related_social_media = get_post_meta($related_product_id, '_upgram_social_media', true);
                            }
                            $item_id = 'product_' . $related_product_id;
                            $item_fields_id = $item_id . '_fields';
                            $is_last = $index === ($total_items - 1);
                            $social_media_symbol_color = ['tiktok' => 'black', 'youtube' => 'red'][$related_social_media] ?: '#2161DF';
                            $has_custom_social_media_symbol = $related_social_media === 'youtube' && $related_service_type === 'visualizacoes';
                        ?>
                            <div id="<?php echo esc_attr($item_id); ?>" data-product-price="<?php echo esc_attr($related_product->get_price()); ?>" class="d-flex gap-2 align-items-center <?php echo $is_last ? '' : 'mb-3'; ?>">
                                <svg style="width: 28px; height: 28px; color: <?php echo esc_attr($social_media_symbol_color); ?>">
                                    <use xlink:href="<?php echo esc_attr(UPGRAM_URL . 'assets/images/service-symbol-sprite.svg#' . $related_service_type . ($has_custom_social_media_symbol ? "_{$related_social_media}" : '')); ?>" />
                                </svg>
                                <span style="font-size: 16px; color: var(--upgram-checkout-text-color, #202029);">
                                    <?php echo esc_html(implode(' - ', $related_product->get_attributes())); ?>
                                </span>
                                <button type="button" @click="additional[<?php echo $parent_id; ?>]={ id: <?php echo esc_attr($related_product_id); ?>, price: <?php echo esc_attr($related_product->get_price()); ?>}" class="btn btn-outline-primary align-items-center justify-content-center upgram-other-products-add">
                                    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <path d="M10.5007 0.0839844H5.50065C2.51732 0.0839844 0.0839844 2.51732 0.0839844 5.50065V10.5007C0.0839844 13.484 2.51732 15.9173 5.50065 15.9173H10.5007C13.484 15.9173 15.9173 13.484 15.9173 10.5007V5.50065C15.9173 2.51732 13.484 0.0839844 10.5007 0.0839844ZM11.334 8.83398H8.83398V11.334C8.83398 11.7923 8.45898 12.1673 8.00065 12.1673C7.54232 12.1673 7.16732 11.7923 7.16732 11.334V8.83398H4.66732C4.20898 8.83398 3.83398 8.45898 3.83398 8.00065C3.83398 7.54232 4.20898 7.16732 4.66732 7.16732H7.16732V4.66732C7.16732 4.20898 7.54232 3.83398 8.00065 3.83398C8.45898 3.83398 8.83398 4.20898 8.83398 4.66732V7.16732H11.334C11.7923 7.16732 12.1673 7.54232 12.1673 8.00065C12.1673 8.45898 11.7923 8.83398 11.334 8.83398Z" fill="url(#paint0_linear_2004_1994)" />
                                        <defs>
                                            <linearGradient id="paint0_linear_2004_1994" x1="0.0839844" y1="0.0839844" x2="19.2319" y2="0.814403" gradientUnits="userSpaceOnUse">
                                                <stop stop-color="#2161DF" />
                                                <stop offset="0.993279" stop-color="#DB265C" />
                                            </linearGradient>
                                        </defs>
                                    </svg>
                                    <span>Adicionar</span>
                                </button>
                            </div>
                            <template x-if="additional[<?php echo esc_attr($parent_id); ?>]?.id === <?php echo esc_attr($related_product_id); ?>">
                                <div id="<?php echo esc_attr($item_fields_id); ?>" class="mt-3 <?php echo $is_last ? '' : 'mb-3'; ?>">
                                    <?php
                                    ob_start();
                                    ?>
                                    <button class="upgram-other-products-remove" @click="delete additional[<?php echo esc_attr($parent_id); ?>]" type="button">Remover</button>
                                    <?php
                                    $remove_product_button = ob_get_clean();
                                    echo render_links_fields($related_product, [
                                        'prefix_field' => "additional[$parent_id]",
                                        'remove_product_button' => $remove_product_button
                                    ]);
                                    ?>
                                    <?php if ($related_service_type === 'comentarios'): ?>
                                        <?php echo render_comments_field($related_product, "additional[$parent_id][comments]"); ?>
                                    <?php endif; ?>
                                </div>
                            </template>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endif; ?>

            <div id="product-info" class="mt-1 mb-3">
                <p id="product-name" style="font-weight: 700; font-size: 16px; color: var(--upgram-checkout-text-color, #202029);" class="col-form-label">
                    <?php echo esc_attr(implode(' - ', $product->get_attributes())); ?>
                </p>
                <div class="d-flex align-items-center justify-content-between" style="flex:1;">
                    <span style="font-weight: 500; font-size: 16px; color: var(--upgram-checkout-text-color, #515063);" class="col-form-label">Valor total:</span>
                    <span x-text="Object.values(additional).reduce((total, it) => it.price + total, <?php echo $product->get_price(); ?>).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' })" style="font-weight: 600; font-size: 20px; color: var(--upgram-checkout-text-color, #202029);" id="passwordHelpInline"></span>
                </div>
            </div>
        </div>
        
        <input name="product_id" type="hidden" value="<?php echo esc_attr($product->get_parent_id()); ?>">
        <input name="variation_id" type="hidden" value="<?php echo esc_attr($product->get_id()); ?>">
        <input type="hidden" name="skip" value="<?php echo $skip_seguidores_instructions ? 'true' : 'false'; ?>">
        
        <div class="d-flex align-items-stretch justify-content-center flex-column w-100">
            <button type="submit" 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;">
                <span style="color: #FFFFFF; font-weight: bold; margin-right: 10px">Continuar</span>
                <img id="continue-button-icon" src="<?php echo esc_attr(UPGRAM_URL); ?>/assets/images/arrow-right.svg" alt="arrow-right">
                <span id="continue-button-spinner" class="spinner-border spinner-border-sm text-light" style="display: none;" role="status" aria-hidden="true"></span>
            </button>
            <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>
    </form>
</div>

