<?php

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

add_action('admin_post_wnc_export_analytics', 'wnc_export_analytics_csv');
add_action('admin_post_wnc_clear_analytics', 'wnc_clear_analytics_data');

function wnc_analytics_range() {
    $range = isset($_GET['range']) ? sanitize_key(wp_unslash($_GET['range'])) : '30';

    return in_array($range, ['7', '30', '90', 'all'], true) ? $range : '30';
}

function wnc_analytics_where($range) {
    if ($range === 'all') {
        return ['sql' => '1=1', 'value' => null];
    }

    $days = max(1, absint($range));
    $since = current_datetime()->modify('-' . ($days - 1) . ' days')->setTime(0, 0)->format('Y-m-d H:i:s');

    return ['sql' => 'created_at >= %s', 'value' => $since];
}

function wnc_analytics_prepared_where($range) {
    global $wpdb;
    $where = wnc_analytics_where($range);

    return $where['value'] === null
        ? $where['sql']
        : $wpdb->prepare($where['sql'], $where['value']);
}

function wnc_render_analytics_page() {
    if (!current_user_can('manage_options')) {
        return;
    }

    $pro_active = function_exists('wnc_is_pro_active') && wnc_is_pro_active();
    $enabled = function_exists('wnc_analytics_enabled') && wnc_analytics_enabled();
    $range = wnc_analytics_range();
    ?>
    <div class="wrap wnc-analytics-wrap">
        <h1>Where Next Analytics</h1>

        <?php if (!$pro_active) : ?>
            <div class="notice notice-info"><p>Analytics is a Where Next Connector Pro feature.</p></div>
            <p><a class="button button-primary" href="<?php echo esc_url(admin_url('admin.php?page=where-next-pro')); ?>">View Pro Features</a></p>
            </div>
            <?php return; ?>
        <?php endif; ?>

        <?php if (!$enabled) : ?>
            <div class="notice notice-info"><p>Click analytics is currently disabled.</p></div>
            <p><a class="button button-primary" href="<?php echo esc_url(admin_url('admin.php?page=where-next-pro')); ?>">Enable Analytics</a></p>
            </div>
            <?php return; ?>
        <?php endif; ?>

        <?php
        global $wpdb;
        $table = wnc_analytics_table_name();
        $where = wnc_analytics_prepared_where($range);
        $total = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$table} WHERE {$where}");
        $content_clicked = (int) $wpdb->get_var("SELECT COUNT(DISTINCT post_id) FROM {$table} WHERE {$where}");
        $today = current_time('Y-m-d');
        $today_clicks = (int) $wpdb->get_var(
            $wpdb->prepare("SELECT COUNT(*) FROM {$table} WHERE DATE(created_at) = %s", $today)
        );
        $top_pages = $wpdb->get_results(
            "SELECT post_id, MAX(page_url) AS page_url, COUNT(*) AS clicks
             FROM {$table} WHERE {$where}
             GROUP BY post_id ORDER BY clicks DESC LIMIT 20"
        );
        $daily = $wpdb->get_results(
            "SELECT DATE(created_at) AS click_date, COUNT(*) AS clicks
             FROM {$table} WHERE {$where}
             GROUP BY DATE(created_at) ORDER BY click_date ASC"
        );
        $devices = $wpdb->get_results(
            "SELECT device, COUNT(*) AS clicks FROM {$table} WHERE {$where}
             GROUP BY device ORDER BY clicks DESC"
        );
        $post_types = $wpdb->get_results(
            "SELECT COALESCE(p.post_type, 'deleted') AS post_type, COUNT(*) AS clicks
             FROM {$table} a LEFT JOIN {$wpdb->posts} p ON p.ID = a.post_id
             WHERE {$where} GROUP BY p.post_type ORDER BY clicks DESC"
        );
        $max_daily = 1;

        foreach ($daily as $day) {
            $max_daily = max($max_daily, (int) $day->clicks);
        }

        $export_url = wp_nonce_url(
            add_query_arg(['action' => 'wnc_export_analytics', 'range' => $range], admin_url('admin-post.php')),
            'wnc_export_analytics'
        );
        ?>

        <div class="wnc-analytics-toolbar">
            <form method="get">
                <input type="hidden" name="page" value="where-next-analytics">
                <label for="wnc-range"><strong>Date range</strong></label>
                <select id="wnc-range" name="range" onchange="this.form.submit()">
                    <option value="7" <?php selected($range, '7'); ?>>Last 7 days</option>
                    <option value="30" <?php selected($range, '30'); ?>>Last 30 days</option>
                    <option value="90" <?php selected($range, '90'); ?>>Last 90 days</option>
                    <option value="all" <?php selected($range, 'all'); ?>>All time</option>
                </select>
            </form>
            <a class="button" href="<?php echo esc_url($export_url); ?>">Export CSV</a>
        </div>

        <div class="wnc-analytics-cards">
            <?php wnc_analytics_card('Button Clicks', $total); ?>
            <?php wnc_analytics_card('Content Clicked', $content_clicked); ?>
            <?php wnc_analytics_card('Clicks Today', $today_clicks); ?>
        </div>

        <div class="wnc-analytics-grid">
            <div class="postbox wnc-analytics-panel">
                <h2>Click Trend</h2>
                <?php if (!$daily) : ?>
                    <p>No clicks in this period.</p>
                <?php else : ?>
                    <div class="wnc-bar-chart">
                        <?php foreach ($daily as $day) : ?>
                            <?php $width = max(2, round(((int) $day->clicks / $max_daily) * 100)); ?>
                            <div class="wnc-bar-row">
                                <span><?php echo esc_html($day->click_date); ?></span>
                                <div><i style="width:<?php echo esc_attr($width); ?>%"></i></div>
                                <strong><?php echo esc_html($day->clicks); ?></strong>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>

            <div class="postbox wnc-analytics-panel">
                <h2>Devices</h2>
                <?php wnc_render_analytics_breakdown($devices, 'device', $total); ?>

                <h2 style="margin-top:28px;">Content Types</h2>
                <?php wnc_render_analytics_breakdown($post_types, 'post_type', $total); ?>
            </div>
        </div>

        <div class="postbox wnc-analytics-panel">
            <h2>Top Content</h2>
            <table class="widefat striped">
                <thead><tr><th>Content</th><th>Post type</th><th>Clicks</th><th>Actions</th></tr></thead>
                <tbody>
                <?php if (!$top_pages) : ?>
                    <tr><td colspan="4">No clicks in this period.</td></tr>
                <?php else : ?>
                    <?php foreach ($top_pages as $row) : ?>
                        <?php $post_type = get_post_type($row->post_id); ?>
                        <tr>
                            <td><strong><?php echo esc_html(get_the_title($row->post_id) ?: $row->page_url); ?></strong><br><code>#<?php echo esc_html($row->post_id); ?></code></td>
                            <td><?php echo esc_html($post_type ?: 'Deleted'); ?></td>
                            <td><strong><?php echo esc_html($row->clicks); ?></strong></td>
                            <td><a href="<?php echo esc_url(get_edit_post_link($row->post_id)); ?>">Edit</a> | <a href="<?php echo esc_url($row->page_url); ?>" target="_blank" rel="noopener">View</a></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>

        <div class="postbox wnc-analytics-panel wnc-danger-zone">
            <h2>Analytics Data</h2>
            <p>Analytics is first-party and stores no IP address, cookie identifier or full user-agent string. Existing records are removed according to the retention setting.</p>
            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" onsubmit="return confirm('Permanently delete all Where Next analytics data?');">
                <input type="hidden" name="action" value="wnc_clear_analytics">
                <?php wp_nonce_field('wnc_clear_analytics'); ?>
                <?php submit_button('Clear Analytics Data', 'delete', 'submit', false); ?>
            </form>
        </div>
    </div>
    <style>
        .wnc-analytics-toolbar{display:flex;align-items:end;gap:12px;justify-content:space-between;margin:18px 0}.wnc-analytics-toolbar form{display:flex;align-items:center;gap:8px}.wnc-analytics-cards{display:flex;flex-wrap:wrap;gap:14px;margin:18px 0}.wnc-analytics-card{min-width:190px;background:#fff;border:1px solid #c3c4c7;border-radius:12px;padding:18px}.wnc-analytics-card strong{display:block;font-size:34px;color:#2271b1}.wnc-analytics-grid{display:grid;grid-template-columns:minmax(0,2fr) minmax(280px,1fr);gap:18px}.wnc-analytics-panel{padding:18px}.wnc-analytics-panel h2{margin-top:0}.wnc-bar-row{display:grid;grid-template-columns:90px minmax(80px,1fr) 45px;gap:10px;align-items:center;margin:9px 0}.wnc-bar-row>div{height:14px;background:#e5e7eb;border-radius:999px;overflow:hidden}.wnc-bar-row i{display:block;height:100%;background:#2271b1;border-radius:999px}.wnc-breakdown-row{display:grid;grid-template-columns:minmax(90px,1fr) 50px;gap:8px;margin:10px 0}.wnc-breakdown-row div{grid-column:1/-1;height:8px;background:#e5e7eb;border-radius:999px}.wnc-breakdown-row i{display:block;height:8px;background:#0f766e;border-radius:999px}.wnc-danger-zone{border-left:4px solid #d63638;margin-top:18px}@media(max-width:900px){.wnc-analytics-grid{grid-template-columns:1fr}}@media(max-width:600px){.wnc-analytics-toolbar{align-items:flex-start;flex-direction:column}}
    </style>
    <?php
}

function wnc_analytics_card($label, $value) {
    echo '<div class="wnc-analytics-card"><strong>' . esc_html(number_format_i18n($value)) . '</strong><span>' . esc_html($label) . '</span></div>';
}

function wnc_render_analytics_breakdown($rows, $key, $total) {
    if (!$rows) {
        echo '<p>No data yet.</p>';
        return;
    }

    foreach ($rows as $row) {
        $label = ucfirst((string) ($row->{$key} ?: 'unknown'));
        $count = (int) $row->clicks;
        $percent = $total > 0 ? round(($count / $total) * 100) : 0;
        echo '<div class="wnc-breakdown-row"><span>' . esc_html($label) . '</span><strong>' . esc_html($count) . '</strong><div><i style="width:' . esc_attr($percent) . '%"></i></div></div>';
    }
}

function wnc_export_analytics_csv() {
    if (!current_user_can('manage_options') || !wnc_analytics_enabled()) {
        wp_die('You do not have permission to export analytics.');
    }

    check_admin_referer('wnc_export_analytics');
    $range = wnc_analytics_range();
    $where = wnc_analytics_prepared_where($range);
    global $wpdb;
    $rows = $wpdb->get_results(
        'SELECT created_at, post_id, page_url, device, button_mode FROM ' . wnc_analytics_table_name() . " WHERE {$where} ORDER BY created_at DESC",
        ARRAY_A
    );

    nocache_headers();
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=where-next-analytics-' . gmdate('Y-m-d') . '.csv');
    $output = fopen('php://output', 'w');
    fputcsv($output, ['Date', 'Post ID', 'Title', 'Post Type', 'Page URL', 'Device', 'Button Mode'], ',', '"', '');

    foreach ($rows as $row) {
        fputcsv($output, [
            $row['created_at'],
            $row['post_id'],
            get_the_title($row['post_id']),
            get_post_type($row['post_id']),
            $row['page_url'],
            $row['device'],
            $row['button_mode'],
        ], ',', '"', '');
    }

    fclose($output);
    exit;
}

function wnc_clear_analytics_data() {
    if (!current_user_can('manage_options') || !wnc_analytics_enabled()) {
        wp_die('You do not have permission to clear analytics.');
    }

    check_admin_referer('wnc_clear_analytics');
    global $wpdb;
    $wpdb->query('DELETE FROM ' . wnc_analytics_table_name());
    wp_safe_redirect(add_query_arg(['page' => 'where-next-analytics', 'cleared' => '1'], admin_url('admin.php')));
    exit;
}
