<?php
/**
 * Template Etapa 3: Pagamento
 * Checkout em Página - Baseado em payment-modal.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 as etapas anteriores 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 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';

// Obter total do carrinho
$cart_total = $cart->get_total('');
?>

<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 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;">Selecionar Posts</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;">3</div>
            <span style="font-size: 14px; color: var(--upgram-checkout-text-color, #333);">Pagamento</span>
        </div>
        <div style="position: absolute; top: 20px; left: 0; right: 0; 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=2' : ''); ?>" 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>

            <!-- Resumo do Pedido -->
            <div class="mb-4">
                <h3 style="font-size: 20px; font-weight: 700; color: var(--upgram-checkout-text-color, #202029); margin-bottom: 20px;">Resumo do Pedido</h3>
                <?php
                $cart_items = $cart->get_cart();
                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 } ?>
            </div>

            <!-- Total -->
            <div class="mb-4" style="background: var(--upgram-checkout-background-color, #F5F5F5); padding: 20px; border-radius: 12px;">
                <div class="d-flex align-items-center justify-content-between">
                    <label style="font-weight: 500; font-size: 16px; color: var(--upgram-checkout-text-color, #515063);" for="totalValue">
                        Total:
                    </label>
                    <span id="totalValue" style="font-weight: 600; font-size: 20px; color: var(--upgram-checkout-text-color, #202029);">
                        <?php echo wc_price($cart_total); ?>
                    </span>
                </div>
            </div>

            <!-- Formulário de Checkout WooCommerce -->
            <div class="woocommerce-checkout">
                <?php
                // Usar o formulário de checkout padrão do WooCommerce
                // Isso irá renderizar os métodos de pagamento disponíveis
                if (function_exists('woocommerce_checkout')) {
                    // Criar um formulário de checkout customizado ou usar o padrão
                    echo '<div id="upgram-checkout-form">';
                    echo '<h3 style="font-size: 20px; font-weight: 700; color: var(--upgram-checkout-text-color, #202029); margin-bottom: 20px;">Método de Pagamento</h3>';
                    
                    // Listar métodos de pagamento disponíveis
                    $available_gateways = WC()->payment_gateways->get_available_payment_gateways();
                    if (!empty($available_gateways)) {
                        echo '<div class="payment-methods" style="margin-bottom: 20px;">';
                        foreach ($available_gateways as $gateway) {
                            echo '<div class="payment-method" style="margin-bottom: 15px; padding: 15px; border: 2px solid #e0e0e0; border-radius: 8px; cursor: pointer;" onclick="selectPaymentMethod(\'' . esc_js($gateway->id) . '\')">';
                            echo '<input type="radio" name="payment_method" value="' . esc_attr($gateway->id) . '" id="payment_method_' . esc_attr($gateway->id) . '" style="margin-right: 10px;">';
                            echo '<label for="payment_method_' . esc_attr($gateway->id) . '" style="font-weight: 500; color: var(--upgram-checkout-text-color, #333); cursor: pointer;">';
                            echo esc_html($gateway->get_title());
                            echo '</label>';
                            if ($gateway->has_fields() || $gateway->get_description()) {
                                echo '<div class="payment_box payment_method_' . esc_attr($gateway->id) . '" style="display: none; margin-top: 10px; padding: 10px; background: #f9f9f9; border-radius: 4px;">';
                                echo wp_kses_post($gateway->get_description());
                                $gateway->payment_fields();
                                echo '</div>';
                            }
                            echo '</div>';
                        }
                        echo '</div>';
                    }
                    
                    // Campo CPF para PagHiper PIX
                    echo '<div id="upgram-cpf" class="d-none mb-3">';
                    echo '<label class="upgram-input">';
                    echo '<span><i class="bi bi-person-badge" style="color: #614DDD; font-size: 24px;"></i></span>';
                    echo '<input type="text" name="cpf" placeholder="CPF (apenas números)" maxlength="11" pattern="[0-9]{11}">';
                    echo '</label>';
                    echo '</div>';
                    
                    echo '</div>';
                }
                ?>
            </div>

            <!-- Botão Finalizar Compra -->
            <div class="d-flex align-items-stretch justify-content-center flex-column w-100 mt-4">
                <button type="button" id="upgram-place-order" 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; border: none; cursor: pointer;">
                    <span style="color: #FFFFFF; font-weight: bold; margin-right: 10px">Finalizar Compra</span>
                    <img id="place-order-icon" src="<?php echo esc_attr(UPGRAM_URL); ?>/assets/images/arrow-right.svg" alt="arrow-right">
                    <span id="place-order-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>
        </div>
    </div>
</div>

<script>
function selectPaymentMethod(methodId) {
    // Marcar o radio button
    document.querySelectorAll('input[name="payment_method"]').forEach(function(radio) {
        radio.checked = false;
        const paymentBox = document.querySelector('.payment_method_' + radio.value);
        if (paymentBox) {
            paymentBox.style.display = 'none';
        }
    });
    
    const selectedRadio = document.getElementById('payment_method_' + methodId);
    if (selectedRadio) {
        selectedRadio.checked = true;
        const paymentBox = document.querySelector('.payment_method_' + methodId);
        if (paymentBox) {
            paymentBox.style.display = 'block';
        }
    }
    
    // Mostrar/ocultar CPF para PagHiper PIX
    const cpfField = document.getElementById('upgram-cpf');
    if (cpfField) {
        if (methodId === 'paghiper_pix') {
            cpfField.classList.remove('d-none');
        } else {
            cpfField.classList.add('d-none');
        }
    }
}

// Processar pedido quando clicar em Finalizar Compra
document.addEventListener('DOMContentLoaded', function() {
    const placeOrderBtn = document.getElementById('upgram-place-order');
    if (placeOrderBtn) {
        placeOrderBtn.addEventListener('click', function() {
            // Implementar lógica de processamento do pedido
            // Similar ao que é feito no modal de pagamento
            alert('Funcionalidade de processamento de pedido será implementada em breve.');
        });
    }
});
</script>

