<?php
/**
 * Plugin Name: Fe Adulta — Support Campaign
 * Description: Landing y banner discreto de apoyo económico para la migración de Fe Adulta.
 * Version: 1.0
 */

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

const FEA_SUPPORT_TEMPLATE = 'fea-support-campaign.php';
const FEA_SUPPORT_TEMPLATE_LABEL = 'Fe Adulta — Campaña de apoyo';

function fea_support_template_path(): string {
    return __DIR__ . '/fea-support-campaign/template.php';
}

function fea_support_is_spanish_context(): bool {
    if (!function_exists('pll_current_language')) {
        return true;
    }

    return pll_current_language() === 'es';
}

function fea_support_campaign_page(): ?WP_Post {
    static $page = 'unset';

    if ($page !== 'unset') {
        return $page instanceof WP_Post ? $page : null;
    }

    $pages = get_posts([
        'post_type'      => 'page',
        'post_status'    => ['publish', 'draft', 'private'],
        'posts_per_page' => 1,
        'meta_key'       => '_wp_page_template',
        'meta_value'     => FEA_SUPPORT_TEMPLATE,
    ]);

    if (!$pages) {
        $slug_page = get_page_by_path('apoya-feadulta', OBJECT, 'page');
        $page = $slug_page instanceof WP_Post ? $slug_page : null;
        return $page;
    }

    $page = $pages[0];
    return $page;
}

function fea_support_campaign_url(): string {
    $page = fea_support_campaign_page();
    if (!$page || $page->post_status !== 'publish') {
        return '';
    }

    return (string) get_permalink($page);
}

function fea_support_meta(int $page_id, string $key, $default = '') {
    $value = get_post_meta($page_id, $key, true);
    return ($value === '' || $value === null) ? $default : $value;
}

function fea_support_campaign_data(?int $page_id = null): array {
    $page_id = $page_id ?: (fea_support_campaign_page()?->ID ?? 0);
    if (!$page_id) {
        return [];
    }

    $goal = (float) fea_support_meta($page_id, 'fea_support_goal', 2000);
    $raised = (float) fea_support_meta($page_id, 'fea_support_raised', 0);
    $goal = $goal > 0 ? $goal : 2000;
    $raised = max(0, $raised);

    return [
        'page_id'       => $page_id,
        'eyebrow'       => (string) fea_support_meta($page_id, 'fea_support_eyebrow', 'Apoya Fe Adulta'),
        'hero_title'    => (string) fea_support_meta($page_id, 'fea_support_hero_title', 'Ayúdanos a sostener la nueva web de Fe Adulta'),
        'hero_intro'    => (string) fea_support_meta($page_id, 'fea_support_hero_intro', 'La migración de Fe Adulta ha requerido meses de trabajo y un coste aproximado de 2000€. Si puedes colaborar, por pequeña que sea la aportación, nos ayudas a sostener este esfuerzo compartido.'),
        'progress_note' => (string) fea_support_meta($page_id, 'fea_support_progress_note', 'Objetivo aproximado para cubrir el trabajo técnico y la migración.'),
        'banner_title'  => (string) fea_support_meta($page_id, 'fea_support_banner_title', 'Estamos sosteniendo la nueva web entre todos'),
        'banner_text'   => (string) fea_support_meta($page_id, 'fea_support_banner_text', 'La migración ha supuesto meses de trabajo y unos 2000€ de coste. Si puedes colaborar, nos ayudas a cuidar Fe Adulta.'),
        'goal'          => $goal,
        'raised'        => $raised,
        'stripe_url'    => (string) fea_support_meta($page_id, 'fea_support_stripe_url', ''),
        'cajamar_url'   => (string) fea_support_meta($page_id, 'fea_support_cajamar_url', ''),
        'paypal_url'    => (string) fea_support_meta($page_id, 'fea_support_paypal_url', ''),
    ];
}

function fea_support_amount(float $amount): string {
    if (floor($amount) === $amount) {
        return number_format_i18n($amount, 0) . '€';
    }

    return number_format_i18n($amount, 2) . '€';
}

function fea_support_progress_percent(array $data): float {
    $goal = (float) ($data['goal'] ?? 0);
    $raised = (float) ($data['raised'] ?? 0);

    if ($goal <= 0) {
        return 0;
    }

    return max(0, min(100, ($raised / $goal) * 100));
}

function fea_support_buttons_html(array $data, string $context = 'page'): string {
    $buttons = [
        'stripe_url'  => ['label' => 'Donar con Stripe', 'class' => 'is-primary'],
        'cajamar_url' => ['label' => 'Donar con Cajamar', 'class' => 'is-secondary'],
        'paypal_url'  => ['label' => 'Donar con PayPal', 'class' => 'is-secondary'],
    ];

    $html = '<div class="fea-support-actions fea-support-actions--' . esc_attr($context) . '">';
    foreach ($buttons as $key => $config) {
        if (empty($data[$key])) {
            continue;
        }

        $html .= '<a class="fea-support-button ' . esc_attr($config['class']) . '" href="'
            . esc_url($data[$key]) . '" target="_blank" rel="noopener">'
            . esc_html($config['label']) . '</a>';
    }
    $html .= '</div>';

    return $html;
}

function fea_support_progress_html(array $data, string $context = 'page'): string {
    $percent = fea_support_progress_percent($data);
    $summary = fea_support_amount((float) $data['raised']) . ' de ' . fea_support_amount((float) $data['goal']);

    $html = '<div class="fea-support-progress fea-support-progress--' . esc_attr($context) . '">';
    $html .= '<div class="fea-support-progress__numbers">';
    $html .= '<strong>' . esc_html($summary) . '</strong>';
    $html .= '<span>' . esc_html(number_format_i18n($percent, 0)) . '%</span>';
    $html .= '</div>';
    $html .= '<div class="fea-support-progress__track" aria-hidden="true">';
    $html .= '<span class="fea-support-progress__fill" style="width:' . esc_attr(number_format($percent, 2, '.', '')) . '%"></span>';
    $html .= '</div>';
    if (!empty($data['progress_note'])) {
        $html .= '<p class="fea-support-progress__note">' . esc_html($data['progress_note']) . '</p>';
    }
    $html .= '</div>';

    return $html;
}

function fea_support_banner_html(): string {
    $page = fea_support_campaign_page();
    if (!$page || $page->post_status !== 'publish') {
        return '';
    }

    $data = fea_support_campaign_data($page->ID);
    $url = get_permalink($page);

    $html = '<section class="fea-support-banner" aria-label="Campaña de apoyo económico">';
    $html .= '<div class="fea-support-banner__copy">';
    $html .= '<span class="fea-support-banner__eyebrow">' . esc_html($data['eyebrow']) . '</span>';
    $html .= '<h2 class="fea-support-banner__title">' . esc_html($data['banner_title']) . '</h2>';
    $html .= '<p class="fea-support-banner__text">' . esc_html($data['banner_text']) . '</p>';
    $html .= '</div>';
    $html .= '<div class="fea-support-banner__side">';
    $html .= fea_support_progress_html($data, 'banner');
    $html .= '<div class="fea-support-banner__links">';
    $html .= '<a class="fea-support-button is-primary" href="' . esc_url($url) . '">Ver la campaña</a>';
    $html .= '</div>';
    $html .= '</div>';
    $html .= '</section>';

    return $html;
}

add_filter('theme_page_templates', function(array $templates, WP_Theme $theme, ?WP_Post $post, string $post_type): array {
    if ($post_type === 'page') {
        $templates[FEA_SUPPORT_TEMPLATE] = FEA_SUPPORT_TEMPLATE_LABEL;
    }

    return $templates;
}, 10, 4);

add_filter('template_include', function(string $template): string {
    if (!is_page()) {
        return $template;
    }

    $page = get_queried_object();
    if (!$page instanceof WP_Post) {
        return $template;
    }

    if (get_page_template_slug($page) !== FEA_SUPPORT_TEMPLATE) {
        return $template;
    }

    return fea_support_template_path();
});

add_action('acf/init', function() {
    if (!function_exists('acf_add_local_field_group')) {
        return;
    }

    acf_add_local_field_group([
        'key'    => 'group_fea_support_campaign',
        'title'  => 'Campaña de apoyo económico',
        'fields' => [
            [
                'key'           => 'field_fea_support_goal',
                'label'         => 'Objetivo económico',
                'name'          => 'fea_support_goal',
                'type'          => 'number',
                'instructions'  => 'Importe objetivo de la campaña.',
                'default_value' => 2000,
                'min'           => 1,
                'step'          => 1,
            ],
            [
                'key'           => 'field_fea_support_raised',
                'label'         => 'Importe recaudado',
                'name'          => 'fea_support_raised',
                'type'          => 'number',
                'instructions'  => 'Cantidad actual recaudada.',
                'default_value' => 0,
                'min'           => 0,
                'step'          => 0.01,
            ],
            [
                'key'           => 'field_fea_support_eyebrow',
                'label'         => 'Antetítulo',
                'name'          => 'fea_support_eyebrow',
                'type'          => 'text',
                'default_value' => 'Apoya Fe Adulta',
            ],
            [
                'key'           => 'field_fea_support_hero_title',
                'label'         => 'Título principal',
                'name'          => 'fea_support_hero_title',
                'type'          => 'text',
                'default_value' => 'Ayúdanos a sostener la nueva web de Fe Adulta',
            ],
            [
                'key'           => 'field_fea_support_hero_intro',
                'label'         => 'Texto principal',
                'name'          => 'fea_support_hero_intro',
                'type'          => 'textarea',
                'rows'          => 4,
                'new_lines'     => 'br',
                'default_value' => 'La migración de Fe Adulta ha requerido meses de trabajo y un coste aproximado de 2000€. Si puedes colaborar, por pequeña que sea la aportación, nos ayudas a sostener este esfuerzo compartido.',
            ],
            [
                'key'           => 'field_fea_support_progress_note',
                'label'         => 'Nota bajo la barra',
                'name'          => 'fea_support_progress_note',
                'type'          => 'text',
                'default_value' => 'Objetivo aproximado para cubrir el trabajo técnico y la migración.',
            ],
            [
                'key'           => 'field_fea_support_banner_title',
                'label'         => 'Título del banner de portada',
                'name'          => 'fea_support_banner_title',
                'type'          => 'text',
                'default_value' => 'Estamos sosteniendo la nueva web entre todos',
            ],
            [
                'key'           => 'field_fea_support_banner_text',
                'label'         => 'Texto del banner de portada',
                'name'          => 'fea_support_banner_text',
                'type'          => 'textarea',
                'rows'          => 3,
                'new_lines'     => 'br',
                'default_value' => 'La migración ha supuesto meses de trabajo y unos 2000€ de coste. Si puedes colaborar, nos ayudas a cuidar Fe Adulta.',
            ],
            [
                'key'           => 'field_fea_support_stripe_url',
                'label'         => 'URL Stripe',
                'name'          => 'fea_support_stripe_url',
                'type'          => 'url',
            ],
            [
                'key'           => 'field_fea_support_cajamar_url',
                'label'         => 'URL TPV Cajamar',
                'name'          => 'fea_support_cajamar_url',
                'type'          => 'url',
            ],
            [
                'key'           => 'field_fea_support_paypal_url',
                'label'         => 'URL PayPal',
                'name'          => 'fea_support_paypal_url',
                'type'          => 'url',
            ],
        ],
        'location' => [[
            ['param' => 'page_template', 'operator' => '==', 'value' => FEA_SUPPORT_TEMPLATE],
        ]],
        'position'        => 'normal',
        'style'           => 'default',
        'label_placement' => 'top',
    ]);
});

add_filter('the_content', function(string $content): string {
    // DESACTIVADO temporalmente: la campaña de apoyo (Codex) aún no está lista
    // (barra 0€/2.000€, sin enlaces de donación). No mostrar el banner en portada.
    // Reactivar quitando este return cuando la campaña esté terminada.
    return $content;

    if (is_admin() || !is_main_query() || !in_the_loop()) {
        return $content;
    }

    if (!function_exists('fea_is_front_page') || !fea_is_front_page()) {
        return $content;
    }

    if (!fea_support_is_spanish_context()) {
        return $content;
    }

    $banner = fea_support_banner_html();
    if (!$banner) {
        return $content;
    }

    return $content . $banner;
}, 40);

add_shortcode('fea_support_campaign_banner', function() {
    return fea_support_banner_html();
});
