<?php
if (!defined('ABSPATH')) exit;

// =============================================================================
// PAINEL DO ANUNCIANTE — [imz_meus_anuncios]
// Self-service: o anunciante vê os seus anúncios, métricas e pode pausar/retomar.
// =============================================================================

/**
 * Descobre o URL da página que contém [imz_meus_anuncios] (cache 12h).
 * Devolve string vazia se nenhuma página publicada tiver o shortcode.
 */
function imz_get_my_ads_page_url(): string {
    $cached = get_transient('imz_my_ads_page_url');
    if (false !== $cached) return (string) $cached;

    $url = '';
    $pages = get_posts([
        'post_type'      => 'page',
        'post_status'    => 'publish',
        'posts_per_page' => 1,
        's'              => '[imz_meus_anuncios',
        'fields'         => 'ids',
    ]);
    if (!empty($pages)) {
        $url = (string) get_permalink($pages[0]);
    }
    set_transient('imz_my_ads_page_url', $url, 12 * HOUR_IN_SECONDS);
    return $url;
}

add_shortcode('imz_meus_anuncios', 'imz_render_my_ads_panel');
function imz_render_my_ads_panel(): string {
    $account_logged_in = defined('RMBZ_ARTISTS_EMBEDDED')
        ? (function_exists('imz_rmbz_is_artist_logged_in') && imz_rmbz_is_artist_logged_in())
        : is_user_logged_in();
    if (!$account_logged_in) {
        $login_url = function_exists('imz_rmbz_account_url') ? imz_rmbz_account_url() : wp_login_url(get_permalink());
        return '<div class="imz-message imz-message-warning">Entra na tua <a href="' . esc_url($login_url) . '">conta 1MZ For Artists</a> para ver os teus anúncios.</div>';
    }

    $user_id = function_exists('imz_get_current_artist_user_id') ? imz_get_current_artist_user_id() : get_current_user_id();
    $ads = get_posts([
        'post_type'      => 'imz_anuncio',
        'author'         => $user_id,
        'post_status'    => 'publish',
        'posts_per_page' => -1,
        'orderby'        => 'date',
        'order'          => 'DESC',
    ]);

    if (empty($ads)) {
        return '<div class="imz-my-ads-empty">
            <h3>Ainda não tem anúncios</h3>
            <p>Crie a sua primeira campanha e alcance milhares de ouvintes.</p>
        </div>';
    }

    $formats = function_exists('imz_get_ad_formats') ? imz_get_ad_formats() : [];
    $today = current_time('Y-m-d');

    $status_labels = [
        'ativo'                => 'Ativo',
        'pausado'              => 'Pausado',
        'pendente'             => 'Em aprovação',
        'rejeitado'            => 'Rejeitado',
        'expirado'             => 'Expirado',
        'aguardando_pagamento' => 'Aguarda pagamento',
    ];

    // KPIs agregados
    $total_impressions = 0;
    $total_clicks = 0;
    $cards = [];

    foreach ($ads as $ad) {
        $ad_id  = $ad->ID;
        $status = get_post_meta($ad_id, '_imz_ad_status', true) ?: 'pendente';
        $end    = get_post_meta($ad_id, '_imz_ad_end_date', true);

        // Estado "expirado" calculado, mesmo que a meta ainda diga 'ativo'
        if ($status === 'ativo' && $end && $end < $today) {
            $status = 'expirado';
        }

        $totals = function_exists('imz_ads_get_totals') ? imz_ads_get_totals($ad_id) : ['impressions' => 0, 'clicks' => 0];
        $total_impressions += $totals['impressions'];
        $total_clicks      += $totals['clicks'];

        $cards[] = [
            'id'          => $ad_id,
            'title'       => get_the_title($ad_id),
            'status'      => $status,
            'format'      => get_post_meta($ad_id, '_imz_ad_format', true),
            'start'       => get_post_meta($ad_id, '_imz_ad_start_date', true),
            'end'         => $end,
            'price'       => (float) get_post_meta($ad_id, '_imz_ad_price', true),
            'impressions' => $totals['impressions'],
            'clicks'      => $totals['clicks'],
        ];
    }

    $global_ctr = $total_impressions > 0 ? round(($total_clicks / $total_impressions) * 100, 2) : 0;
    $fmt = function ($n) {
        return function_exists('imz_format_number_short') ? imz_format_number_short($n) : number_format_i18n($n);
    };

    ob_start();
    ?>
    <div class="imz-my-ads" id="imz-my-ads">
        <h2 class="imz-my-ads-heading">📢 Os Meus Anúncios</h2>

        <div class="imz-my-ads-kpis">
            <div class="imz-my-ads-kpi"><span class="val"><?php echo esc_html($fmt($total_impressions)); ?></span><span class="lbl">Impressões</span></div>
            <div class="imz-my-ads-kpi"><span class="val"><?php echo esc_html($fmt($total_clicks)); ?></span><span class="lbl">Cliques</span></div>
            <div class="imz-my-ads-kpi"><span class="val"><?php echo esc_html($global_ctr); ?>%</span><span class="lbl">CTR</span></div>
            <div class="imz-my-ads-kpi"><span class="val"><?php echo count($cards); ?></span><span class="lbl">Anúncios</span></div>
        </div>

        <?php foreach ($cards as $card) :
            $ctr = $card['impressions'] > 0 ? round(($card['clicks'] / $card['impressions']) * 100, 2) : 0;
            $format_name = isset($formats[$card['format']]) ? $formats[$card['format']]['name'] . ' (' . $formats[$card['format']]['label'] . ')' : '—';
            $can_toggle = in_array($card['status'], ['ativo', 'pausado'], true);
        ?>
        <div class="imz-my-ad-card" data-ad-id="<?php echo esc_attr($card['id']); ?>">
            <div class="imz-my-ad-card-header">
                <strong class="imz-my-ad-title"><?php echo esc_html($card['title']); ?></strong>
                <span class="imz-ad-status-badge imz-ad-status-<?php echo esc_attr($card['status']); ?>"><?php echo esc_html($status_labels[$card['status']] ?? $card['status']); ?></span>
            </div>
            <div class="imz-my-ad-meta">
                <span><strong>Formato:</strong> <?php echo esc_html($format_name); ?></span>
                <span><strong>Período:</strong> <?php echo esc_html($card['start'] ?: '—'); ?> → <?php echo esc_html($card['end'] ?: '—'); ?></span>
                <span><strong>Investimento:</strong> <?php echo esc_html(number_format($card['price'])); ?> MT</span>
            </div>
            <div class="imz-my-ad-stats">
                <div class="imz-my-ad-stat"><span class="val"><?php echo esc_html($fmt($card['impressions'])); ?></span><span class="lbl">Impressões</span></div>
                <div class="imz-my-ad-stat"><span class="val"><?php echo esc_html($fmt($card['clicks'])); ?></span><span class="lbl">Cliques</span></div>
                <div class="imz-my-ad-stat"><span class="val"><?php echo esc_html($ctr); ?>%</span><span class="lbl">CTR</span></div>
            </div>
            <?php if ($can_toggle) : ?>
            <div class="imz-my-ad-actions">
                <?php if ($card['status'] === 'ativo') : ?>
                    <button type="button" class="imz-botao-secundario imz-ad-toggle-btn" data-ad-id="<?php echo esc_attr($card['id']); ?>" data-new-status="pausado">⏸ Pausar</button>
                <?php else : ?>
                    <button type="button" class="imz-botao-principal imz-mt0 imz-ad-toggle-btn" data-ad-id="<?php echo esc_attr($card['id']); ?>" data-new-status="ativo">▶ Retomar</button>
                <?php endif; ?>
            </div>
            <?php elseif ($card['status'] === 'aguardando_pagamento' && get_option('imz_enable_mpesa_api')) : ?>
            <div class="imz-my-ad-pay">
                <input type="tel" class="imz-input imz-ad-pay-phone" pattern="[0-9]{9}" maxlength="9" placeholder="Número M-Pesa (84xxxxxxx)" inputmode="numeric">
                <button type="button" class="imz-botao-principal imz-mt0 imz-ad-pay-now" data-ad-id="<?php echo esc_attr($card['id']); ?>">💳 Pagar <?php echo esc_html(number_format($card['price'])); ?> MT</button>
            </div>
            <div class="imz-form-messages" aria-live="polite"></div>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>
    </div>
    <?php
    return ob_get_clean();
}

// =============================================================================
// AJAX — Pausar/Retomar pelo próprio anunciante
// =============================================================================

add_action('wp_ajax_imz_ad_toggle_status', 'imz_ajax_ad_toggle_status');
function imz_ajax_ad_toggle_status(): void {
    check_ajax_referer('imz_ad_toggle_status', 'nonce');

    $ad_id      = absint($_POST['ad_id'] ?? 0);
    $new_status = sanitize_key($_POST['new_status'] ?? '');

    if (!$ad_id || get_post_type($ad_id) !== 'imz_anuncio') {
        wp_send_json_error(['message' => 'Anúncio inválido.']);
    }
    if ((int) get_post_field('post_author', $ad_id) !== get_current_user_id()) {
        wp_send_json_error(['message' => 'Não tem permissão para gerir este anúncio.']);
    }

    $current = get_post_meta($ad_id, '_imz_ad_status', true);
    // O anunciante só pode alternar entre ativo ⇄ pausado.
    // Pendente/rejeitado/aguardando_pagamento são estados controlados pelo admin/pagamento.
    if (!in_array($current, ['ativo', 'pausado'], true) || !in_array($new_status, ['ativo', 'pausado'], true) || $current === $new_status) {
        wp_send_json_error(['message' => 'Transição de estado não permitida.']);
    }

    update_post_meta($ad_id, '_imz_ad_status', $new_status);

    wp_send_json_success([
        'message'    => $new_status === 'pausado' ? 'Anúncio pausado. Pode retomá-lo quando quiser.' : 'Anúncio retomado — já está a ser exibido.',
        'new_status' => $new_status,
        'new_label'  => $new_status === 'pausado' ? 'Pausado' : 'Ativo',
    ]);
}
