<?php
/**
 * Theme functions & definitations
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @package foresty
 */

/**
 * Define Theme Folder Path & URL Constant
 * @package foresty
 * @since 1.0.0
 */

define('FORESTY_THEME_ROOT', get_template_directory());
define('FORESTY_THEME_ROOT_URL', get_template_directory_uri());
define('FORESTY_INC', FORESTY_THEME_ROOT . '/inc');
define('FORESTY_THEME_SETTINGS', FORESTY_INC . '/theme-settings');
define('FORESTY_THEME_SETTINGS_IMAGES', FORESTY_THEME_ROOT_URL . '/inc/theme-settings/images');
define('FORESTY_TGMA', FORESTY_INC . '/plugins/tgma');
define('FORESTY_DYNAMIC_STYLESHEETS', FORESTY_INC . '/theme-stylesheets');
define('FORESTY_CSS', FORESTY_THEME_ROOT_URL . '/assets/css');
define('FORESTY_JS', FORESTY_THEME_ROOT_URL . '/assets/js');
define('FORESTY_ASSETS', FORESTY_THEME_ROOT_URL . '/assets');
define('FORESTY_DEV', true);


/**
 * Theme Initial File
 * @package foresty
 * @since 1.0.0
 */
if (file_exists(FORESTY_INC . '/theme-init.php')) {
    require_once FORESTY_INC . '/theme-init.php';
}


/**
 * Codester Framework Functions
 * @package foresty
 * @since 1.0.0
 */
if (file_exists(FORESTY_INC . '/theme-cs-function.php')) {
    require_once FORESTY_INC . '/theme-cs-function.php';
}


/**
 * Theme Helpers Functions
 * @package foresty
 * @since 1.0.0
 */
if (file_exists(FORESTY_INC . '/theme-helper-functions.php')) {

    require_once FORESTY_INC . '/theme-helper-functions.php';
    if (!function_exists('foresty')) {
        function foresty()
        {
            return class_exists('Foresty_Helper_Functions') ? new Foresty_Helper_Functions() : false;
        }
    }
}
/**
 * Nav menu fallback function
 * @since 1.0.0
 */
if (is_user_logged_in()) {
    function foresty_theme_fallback_menu()
    {
        get_template_part('template-parts/default', 'menu');
    }
}

// // ==============================
// TRACKING UTM CAMPAIGNS
// ==============================

// 3. GESTÃO DA BASE DE DADOS (ATIVAÇÃO)
function tc_criar_tabela()
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'tracking_campaigns';
    $charset_collate = $wpdb->get_charset_collate();

    // Estrutura: ID, Source, Campaign, Timestamp, Registo.
    // Usamos dbDelta para garantir que a tabela existe sem apagar dados.
    $sql = "CREATE TABLE $table_name (
        id BIGINT(20) NOT NULL AUTO_INCREMENT,
        utm_source VARCHAR(100) DEFAULT '',
        utm_campaign VARCHAR(100) DEFAULT '',
        post_timestamp BIGINT(20) DEFAULT 0,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id)
    ) $charset_collate;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}
register_activation_hook(__FILE__, 'tc_criar_tabela');

// 4. CAPTURA DE DADOS (UTMs)
function tc_guardar_utm_campaign()
{
    if (!is_admin()) {
        global $wpdb;

        // Sanitização rigorosa
        $utm_source = isset($_GET['utm_source']) ? sanitize_text_field($_GET['utm_source']) : '';
        $utm_campaign = isset($_GET['utm_campaign']) ? sanitize_text_field($_GET['utm_campaign']) : '';
        $post_timestamp = isset($_GET['post_ts']) ? intval($_GET['post_ts']) : 0;

        // Se o timestamp for inválido, usa o atual
        if ($post_timestamp < 946684800 || $post_timestamp > 4102444800) {
            $post_timestamp = current_time('timestamp');
        }

        if (!empty($utm_source) || !empty($utm_campaign)) {
            $table_name = $wpdb->prefix . 'tracking_campaigns';
            $wpdb->insert(
                $table_name,
                [
                    'utm_source' => $utm_source,
                    'utm_campaign' => $utm_campaign,
                    'post_timestamp' => $post_timestamp,
                    'created_at' => current_time('mysql'),
                ]
            );
        }
    }
}
add_action('template_redirect', 'tc_guardar_utm_campaign');

// 5. CARREGAMENTO DE SCRIPTS (CHART.JS)
function tc_enqueue_admin_scripts($hook)
{
    // Apenas carrega na página do plugin
    if ($hook != 'toplevel_page_tracking-campaigns') {
        return;
    }
    wp_enqueue_script('chartjs', 'https://cdn.jsdelivr.net/npm/chart.js', array(), '4.4.0', true);
}
add_action('admin_enqueue_scripts', 'tc_enqueue_admin_scripts');

// 6. ADICIONAR AO MENU LATERAL
function tc_tracking_menu()
{
    add_menu_page(
        'Tracking Campanhas',
        'Tracking Campanhas',
        'manage_options',
        'tracking-campaigns',
        'tc_pagina_dashboard_html',
        'dashicons-chart-bar',
        20
    );
}
add_action('admin_menu', 'tc_tracking_menu');

// 7. EXPORTAÇÃO PARA EXCEL (CSV)
function tc_exportar_csv()
{
    if (isset($_GET['page']) && $_GET['page'] == 'tracking-campaigns' && isset($_POST['exportar_excel'])) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'tracking_campaigns';
        $resultados = $wpdb->get_results("SELECT * FROM $table_name ORDER BY id DESC");

        if ($resultados) {
            ob_clean();
            header('Content-Type: text/csv; charset=utf-8');
            header('Content-Disposition: attachment; filename=tracking_campaigns_WP_' . date('Y-m-d') . '.csv');

            $saida = fopen('php://output', 'w');
            fprintf($saida, chr(0xEF) . chr(0xBB) . chr(0xBF)); // BOM para Excel
            fputcsv($saida, array('ID', 'Source', 'Campaign', 'Post Date', 'Data Registo'), ';');

            foreach ($resultados as $row) {
                $post_date = (!empty($row->post_timestamp)) ? date('Y-m-d H:i:s', $row->post_timestamp) : '-';
                fputcsv($saida, array(
                    $row->id,
                    (!empty($row->utm_source) ? $row->utm_source : '-'),
                    (!empty($row->utm_campaign) ? $row->utm_campaign : '-'),
                    $post_date,
                    $row->created_at
                ), ';');
            }
            fclose($saida);
            exit;
        }
    }
}
add_action('admin_init', 'tc_exportar_csv');

// 8. CONTEÚDO DO DASHBOARD
if (!function_exists('tc_pagina_dashboard_html')) {
function tc_pagina_dashboard_html()
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'tracking_campaigns';

    // 1. Processar Eliminação Total
    if (isset($_POST['tc_delete_all_records'])) {
        check_admin_referer('tc_delete_all_nonce_action', 'tc_delete_all_nonce_field');
        $wpdb->query("TRUNCATE TABLE $table_name");
        echo '<div class="notice notice-success is-dismissible"><p>Todos os registos foram eliminados!</p></div>';
    }

    // 2. Processar Eliminação Individual
    if (isset($_GET['delete_id'])) {
        $wpdb->delete($table_name, array('id' => intval($_GET['delete_id'])));
        echo '<div class="notice notice-success is-dismissible"><p>Registo eliminado com sucesso.</p></div>';
    }

    // 3. Obter Dados
    $resultados = $wpdb->get_results("SELECT * FROM $table_name ORDER BY id DESC LIMIT 200");
    $unique_sources = $wpdb->get_col("SELECT DISTINCT utm_source FROM $table_name WHERE utm_source != ''");
    $unique_campaigns = $wpdb->get_col("SELECT DISTINCT utm_campaign FROM $table_name WHERE utm_campaign != ''");
    ?>

    <div class="wrap">
        <div style="display: flex; justify-content: space-between; align-items: center; margin: 20px 0;">
            <h1 style="font-weight: 700; color: #1d2327; margin: 0;">🚀 Tracking de Campanhas</h1>
            
            <form method="post" onsubmit="return confirm('🚨 ALERTA CRÍTICO: ESTÁ PRESTES A APAGAR TUDO!\n\nEsta ação vai eliminar TODOS OS REGISTOS da base de dados de forma PERMANENTE.\n- Não é possível reverter.\n- Nada será poupado (mesmo o que não está a ver agora).\n\nTEM A CERTEZA ABSOLUTA QUE DESEJA ELIMINAR TUDO?');">
                <?php wp_nonce_field('tc_delete_all_nonce_action', 'tc_delete_all_nonce_field'); ?>
                <button type="submit" name="tc_delete_all_records" class="button" style="background: #d63638; color: #fff; border-color: #d63638; font-weight: 700; padding: 5px 20px;">
                    <span class="dashicons dashicons-warning" style="margin-top: 3px;"></span> APAGAR TUDO (IRREVERSÍVEL)
                </button>
            </form>
        </div>

        <!-- Filtros Unificados (Gráfico + Tabela) -->
        <div style="background: #fff; padding: 20px; border: 1px solid #ccd0d4; border-radius: 4px; margin-bottom: 20px; display: flex; gap: 15px; align-items: flex-end;">
            <div>
                <label style="display:block; font-weight: 600; font-size: 11px; text-transform: uppercase; color: #646970;">📅 Período</label>
                <div style="display: flex; gap: 5px; align-items: center;">
                    <input type="date" id="tc_start_date" style="height: 32px; border-radius: 4px;">
                    <span>até</span>
                    <input type="date" id="tc_end_date" style="height: 32px; border-radius: 4px;">
                </div>
            </div>
            <div>
                <label style="display:block; font-weight: 600; font-size: 11px; text-transform: uppercase; color: #646970;">🔍 Origem (Source)</label>
                <select id="tc_filter_source" style="height: 32px; min-width: 160px; border-radius: 4px;">
                    <option value="">Todas as Origens</option>
                    <?php foreach($unique_sources as $s) echo '<option value="'.esc_attr($s).'">'.esc_html($s).'</option>'; ?>
                </select>
            </div>
            <button type="button" id="tc_apply_filters" class="button button-primary" style="height: 32px; font-weight: 600;">Aplicar Filtros</button>
            <button type="button" id="tc_reset_filters" class="button" style="height: 32px;">Limpar</button>
        </div>

        <!-- Gráficos -->
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px;">
            <div style="background: #fff; padding: 15px; border: 1px solid #ccd0d4;">
                <h3 style="margin-top:0;">Origens</h3>
                <canvas id="tcSourceChart" style="max-height: 250px;"></canvas>
            </div>
            <div style="background: #fff; padding: 15px; border: 1px solid #ccd0d4;">
                <h3 style="margin-top:0;">Campanhas</h3>
                <canvas id="tcCampaignChart" style="max-height: 250px;"></canvas>
            </div>
        </div>

        <!-- Tabela -->
        <div style="background: #fff; border: 1px solid #ccd0d4; border-radius: 4px; overflow: hidden;">
            <div style="padding: 15px; background: #f8f9fa; border-bottom: 1px solid #ccd0d4; display: flex; justify-content: space-between;">
                <h3 style="margin:0;">Listagem de Registos</h3>
                <form method="post">
                    <input type="submit" name="exportar_excel" class="button" value="📥 Exportar Excel">
                </form>
            </div>
            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th style="width: 60px;">ID</th>
                        <th>Origem</th>
                        <th>Campanha</th>
                        <th>Data Post</th>
                        <th>Data Registo</th>
                        <th style="text-align: center; width: 80px;">Ações</th>
                    </tr>
                </thead>
                <tbody id="tc_table_results">
                    <?php if ($resultados) : foreach ($resultados as $row) : ?>
                        <tr>
                            <td>#<?php echo $row->id; ?></td>
                            <td><strong><?php echo esc_html($row->utm_source ?: 'Direto'); ?></strong></td>
                            <td><?php echo esc_html($row->utm_campaign ?: '-'); ?></td>
                            <td><small><?php echo $row->post_timestamp ? date('Y-m-d H:i', $row->post_timestamp) : '-'; ?></small></td>
                            <td><small><?php echo $row->created_at; ?></small></td>
                            <td style="text-align: center;">
                                <a href="?page=tracking-campaigns&delete_id=<?php echo $row->id; ?>" style="color: #d63638;" onclick="return confirm('Apagar?')">
                                    <span class="dashicons dashicons-trash"></span>
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; else : ?>
                        <tr><td colspan="6" style="text-align:center; padding: 30px;">Sem registos.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <script>
    jQuery(document).ready(function($) {
        let chartS, chartC;

        function updateCharts(data) {
            if(chartS) chartS.destroy();
            if(chartC) chartC.destroy();

            chartS = new Chart(document.getElementById('tcSourceChart'), {
                type: 'doughnut',
                data: {
                    labels: data.sources.labels,
                    datasets: [{ data: data.sources.data, backgroundColor: ['#2271b1', '#34d399', '#f0b849', '#d63638'] }]
                },
                options: { plugins: { legend: { position: 'right' } } }
            });

            chartC = new Chart(document.getElementById('tcCampaignChart'), {
                type: 'bar',
                data: {
                    labels: data.campaigns.labels,
                    datasets: [{ label: 'Visitas', data: data.campaigns.data, backgroundColor: '#2271b1' }]
                }
            });
        }

        function reloadDashboard() {
            $.post(ajaxurl, {
                action: 'tc_filter_data',
                start_date: $('#tc_start_date').val(),
                end_date: $('#tc_end_date').val(),
                source: $('#tc_filter_source').val()
            }, function(r) {
                if(r.success) {
                    updateCharts(r.data);
                    $('#tc_table_results').html(r.data.table_html);
                }
            });
        }

        $('#tc_apply_filters').click(reloadDashboard);
        $('#tc_reset_filters').click(function(){ 
            $('#tc_start_date, #tc_end_date, #tc_filter_source').val(''); 
            reloadDashboard(); 
        });

        // Carga inicial
        reloadDashboard();
    });
    </script>
    <?php
}
}

// 9. HANDLER AJAX PARA FILTROS
function tc_filter_data_ajax_handler() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'tracking_campaigns';

    $start_date = isset($_POST['start_date']) ? sanitize_text_field($_POST['start_date']) : '';
    $end_date   = isset($_POST['end_date']) ? sanitize_text_field($_POST['end_date']) : '';
    
    // Decodificar arrays JSON
    $sources   = isset($_POST['sources']) ? json_decode(stripslashes($_POST['sources'])) : [];
    $campaigns = isset($_POST['campaigns']) ? json_decode(stripslashes($_POST['campaigns'])) : [];

    $where = ["1=1"];
    if ($start_date) $where[] = $wpdb->prepare("DATE(created_at) >= %s", $start_date);
    if ($end_date)   $where[] = $wpdb->prepare("DATE(created_at) <= %s", $end_date);

    if (!empty($sources)) {
        $source_placeholders = implode(',', array_fill(0, count($sources), '%s'));
        $where[] = $wpdb->prepare("utm_source IN ($source_placeholders)", $sources);
    }
    if (!empty($campaigns)) {
        $campaign_placeholders = implode(',', array_fill(0, count($campaigns), '%s'));
        $where[] = $wpdb->prepare("utm_campaign IN ($campaign_placeholders)", $campaigns);
    }

    $where_clause = implode(' AND ', $where);

    // Dados para Gráficos
    $sources_stats = $wpdb->get_results("SELECT utm_source, COUNT(*) as count FROM $table_name WHERE $where_clause GROUP BY utm_source");
    $campaigns_stats = $wpdb->get_results("SELECT utm_campaign, COUNT(*) as count FROM $table_name WHERE $where_clause GROUP BY utm_campaign");

    $resp_sources = ['labels' => [], 'data' => []];
    foreach ($sources_stats as $s) {
        $resp_sources['labels'][] = empty($s->utm_source) ? 'Direto/Sem UTM' : $s->utm_source;
        $resp_sources['data'][] = (int)$s->count;
    }

    $resp_campaigns = ['labels' => [], 'data' => []];
    foreach ($campaigns_stats as $c) {
        $resp_campaigns['labels'][] = empty($c->utm_campaign) ? 'Nenhuma' : $c->utm_campaign;
        $resp_campaigns['data'][] = (int)$c->count;
    }

    // Dados para Tabela (HTML)
    $resultados = $wpdb->get_results("SELECT * FROM $table_name WHERE $where_clause ORDER BY id DESC LIMIT 100");
    $table_html = '';
    
    if ($resultados) {
        foreach ($resultados as $row) {
            $post_date = (!empty($row->post_timestamp)) ? date('Y-m-d H:i:s', $row->post_timestamp) : '-';
            $utm_source = !empty($row->utm_source) ? $row->utm_source : 'Direto';
            $table_html .= '<tr>';
            $table_html .= '<td><strong>#' . esc_html($row->id) . '</strong></td>';
            $table_html .= '<td><span style="background: #f0f6fb; color: #2271b1; padding: 2px 8px; border-radius: 4px; font-weight: 500;">' . esc_html($utm_source) . '</span></td>';
            $table_html .= '<td>' . esc_html(!empty($row->utm_campaign) ? $row->utm_campaign : '-') . '</td>';
            $table_html .= '<td><small>' . esc_html($post_date) . '</small></td>';
            $table_html .= '<td><small>' . esc_html($row->created_at) . '</small></td>';
            $table_html .= '<td style="text-align: center;"><a href="?page=tracking-campaigns&delete_id=' . $row->id . '" class="tc-delete-row" title="Eliminar este registo" onclick="return confirm(\'Tem a certeza?\')"><span class="dashicons dashicons-trash"></span></a></td>';
            $table_html .= '</tr>';
        }
    } else {
        $table_html = '<tr><td colspan="6" style="text-align: center; padding: 40px; color: #646970;">Sem dados para os filtros selecionados.</td></tr>';
    }

    wp_send_json_success([
        'sources' => $resp_sources,
        'campaigns' => $resp_campaigns,
        'table_html' => $table_html
    ]);
}
add_action('wp_ajax_tc_filter_data', 'tc_filter_data_ajax_handler');