<?php
/**
 * Debug page for troubleshooting PinnerPress
 *
 * Access via: /wp-admin/admin.php?page=pinnerpress-debug
 * This page is hidden from the menu - you must know the URL to access it.
 */

// If this file is called directly, abort.
if (!defined('WPINC')) {
    die;
}

// Require admin access
if (!current_user_can('manage_options')) {
    wp_die(__('You do not have sufficient permissions to access this page.', 'pinnerpress'));
}

global $wpdb;

// Handle repair tables action
$repair_message = '';
$repair_status = '';
if (isset($_POST['repair_tables']) && check_admin_referer('pinnerpress_repair_tables')) {
    // Get analytics instance and create tables
    $analytics = new PinnerPress_Analytics();

    $tables_created = array();
    $tables_failed = array();

    // Create main analytics table
    $analytics->create_table();
    $analytics_table_check = $wpdb->prefix . 'pinnerpress_analytics';
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Table check
    if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $analytics_table_check)) === $analytics_table_check) {
        $tables_created[] = 'pinnerpress_analytics';
    } else {
        $tables_failed[] = 'pinnerpress_analytics';
    }

    // Create post analytics table
    $analytics->create_post_table();
    $post_table_check = $wpdb->prefix . 'pinnerpress_post_analytics';
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Table check
    if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $post_table_check)) === $post_table_check) {
        $tables_created[] = 'pinnerpress_post_analytics';
    } else {
        $tables_failed[] = 'pinnerpress_post_analytics';
    }

    // Create image analytics table
    $analytics->create_image_table();
    $image_table_check = $wpdb->prefix . 'pinnerpress_image_analytics';
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Table check
    if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $image_table_check)) === $image_table_check) {
        $tables_created[] = 'pinnerpress_image_analytics';
    } else {
        $tables_failed[] = 'pinnerpress_image_analytics';
    }

    if (empty($tables_failed)) {
        $repair_status = 'success';
        $repair_message = __('All database tables verified/created successfully!', 'pinnerpress');
    } else {
        $repair_status = 'error';
        $repair_message = sprintf(
            __('Some tables could not be created: %s. Please check database permissions.', 'pinnerpress'),
            implode(', ', $tables_failed)
        );
    }
}

// Table names
$analytics_table = $wpdb->prefix . 'pinnerpress_analytics';
$post_analytics_table = $wpdb->prefix . 'pinnerpress_post_analytics';
$image_analytics_table = $wpdb->prefix . 'pinnerpress_image_analytics';

// Check table existence
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Debug query
$analytics_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $analytics_table)) === $analytics_table;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Debug query
$post_analytics_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $post_analytics_table)) === $post_analytics_table;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Debug query
$image_analytics_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $image_analytics_table)) === $image_analytics_table;

// Get row counts if tables exist
$analytics_count = 0;
$post_analytics_count = 0;
$image_analytics_count = 0;

if ($analytics_exists) {
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Debug query, table name validated
    $analytics_count = (int) $wpdb->get_var("SELECT COUNT(*) FROM `" . esc_sql($analytics_table) . "`");
}
if ($post_analytics_exists) {
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Debug query, table name validated
    $post_analytics_count = (int) $wpdb->get_var("SELECT COUNT(*) FROM `" . esc_sql($post_analytics_table) . "`");
}
if ($image_analytics_exists) {
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Debug query, table name validated
    $image_analytics_count = (int) $wpdb->get_var("SELECT COUNT(*) FROM `" . esc_sql($image_analytics_table) . "`");
}

// Check if any tables are missing
$tables_missing = !$analytics_exists || !$post_analytics_exists || !$image_analytics_exists;

// Get WordPress info
$wp_version = get_bloginfo('version');
$php_version = phpversion();
$plugin_version = defined('PINNERPRESS_VERSION') ? PINNERPRESS_VERSION : 'Unknown';

// Get published post count
$published_posts = wp_count_posts('post');
$published_post_count = isset($published_posts->publish) ? $published_posts->publish : 0;

?>

<div class="wrap">
    <h1>PinnerPress Debug Console</h1>
    <p class="description">This is a hidden debug page for troubleshooting. URL: <code>admin.php?page=pinnerpress-debug</code></p>

    <?php if (!empty($repair_message)): ?>
        <div class="notice notice-<?php echo esc_attr($repair_status); ?> is-dismissible">
            <p><?php echo esc_html($repair_message); ?></p>
        </div>
    <?php endif; ?>

    <!-- System Info -->
    <div class="card" style="max-width: 100%; margin-top: 20px;">
        <h2>System Information</h2>
        <table class="widefat striped" style="margin-top: 10px;">
            <tbody>
                <tr>
                    <td><strong>Plugin Version</strong></td>
                    <td><?php echo esc_html($plugin_version); ?></td>
                </tr>
                <tr>
                    <td><strong>WordPress Version</strong></td>
                    <td><?php echo esc_html($wp_version); ?></td>
                </tr>
                <tr>
                    <td><strong>PHP Version</strong></td>
                    <td><?php echo esc_html($php_version); ?></td>
                </tr>
                <tr>
                    <td><strong>Published Posts</strong></td>
                    <td><?php echo esc_html($published_post_count); ?></td>
                </tr>
            </tbody>
        </table>
    </div>

    <!-- Database Tables Status -->
    <div class="card" style="max-width: 100%; margin-top: 20px;">
        <h2>Database Tables Status</h2>

        <?php if ($tables_missing): ?>
            <div class="notice notice-warning inline" style="margin: 10px 0;">
                <p><strong>One or more tables are missing.</strong> Click "Repair Tables" below to create them.</p>
            </div>
        <?php endif; ?>

        <table class="widefat striped" style="margin-top: 10px;">
            <thead>
                <tr>
                    <th>Table</th>
                    <th>Exists</th>
                    <th>Row Count</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td><code><?php echo esc_html($analytics_table); ?></code><br><small>Main event tracking</small></td>
                    <td><?php echo $analytics_exists ? '<span style="color: green;">&#10004; Yes</span>' : '<span style="color: red;">&#10008; No</span>'; ?></td>
                    <td><?php echo esc_html(number_format($analytics_count)); ?></td>
                    <td>
                        <?php if (!$analytics_exists): ?>
                            <span style="color: red;">Table missing - click Repair Tables</span>
                        <?php elseif ($analytics_count === 0): ?>
                            <span style="color: orange;">Empty - no events tracked yet</span>
                        <?php else: ?>
                            <span style="color: green;">OK</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <td><code><?php echo esc_html($post_analytics_table); ?></code><br><small>Post-level aggregated analytics</small></td>
                    <td><?php echo $post_analytics_exists ? '<span style="color: green;">&#10004; Yes</span>' : '<span style="color: red;">&#10008; No</span>'; ?></td>
                    <td><?php echo esc_html(number_format($post_analytics_count)); ?></td>
                    <td>
                        <?php if (!$post_analytics_exists): ?>
                            <span style="color: red;">Table missing - click Repair Tables</span>
                        <?php elseif ($post_analytics_count === 0): ?>
                            <span style="color: orange;">Empty - no post impressions/clicks tracked yet</span>
                        <?php else: ?>
                            <span style="color: green;">OK</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <td><code><?php echo esc_html($image_analytics_table); ?></code><br><small>Image-level click tracking</small></td>
                    <td><?php echo $image_analytics_exists ? '<span style="color: green;">&#10004; Yes</span>' : '<span style="color: red;">&#10008; No</span>'; ?></td>
                    <td><?php echo esc_html(number_format($image_analytics_count)); ?></td>
                    <td>
                        <?php if (!$image_analytics_exists): ?>
                            <span style="color: red;">Table missing - click Repair Tables</span>
                        <?php elseif ($image_analytics_count === 0): ?>
                            <span style="color: orange;">Empty - no image clicks tracked yet</span>
                        <?php else: ?>
                            <span style="color: green;">OK</span>
                        <?php endif; ?>
                    </td>
                </tr>
            </tbody>
        </table>

        <!-- Repair Tables Button -->
        <form method="post" action="" style="margin-top: 15px;">
            <?php wp_nonce_field('pinnerpress_repair_tables'); ?>
            <button type="submit" name="repair_tables" class="button button-primary">
                <?php echo $tables_missing ? esc_html__('Repair Tables', 'pinnerpress') : esc_html__('Verify/Recreate Tables', 'pinnerpress'); ?>
            </button>
            <span class="description" style="margin-left: 10px;">
                <?php esc_html_e('Creates any missing database tables. Safe to run - will not delete existing data.', 'pinnerpress'); ?>
            </span>
        </form>
    </div>

    <!-- Plugin Settings -->
    <div class="card" style="max-width: 100%; margin-top: 20px;">
        <h2>Analytics Settings</h2>
        <table class="widefat striped" style="margin-top: 10px;">
            <thead>
                <tr>
                    <th>Setting</th>
                    <th>Value</th>
                    <th>Impact</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td><strong>Analytics Enabled</strong></td>
                    <td><code><?php echo esc_html(get_option('pinnerpress_analytics_enabled', '1')); ?></code></td>
                    <td>
                        <?php if (get_option('pinnerpress_analytics_enabled', '1') === '1'): ?>
                            <span style="color: green;">&#10004; Events will be tracked</span>
                        <?php else: ?>
                            <span style="color: red;">&#10008; Events will NOT be tracked</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <td><strong>Ignore Logged-in Users</strong></td>
                    <td><code><?php echo esc_html(get_option('pinnerpress_analytics_ignore_logged_in', '0')); ?></code></td>
                    <td>
                        <?php if (get_option('pinnerpress_analytics_ignore_logged_in', '0') === '1'): ?>
                            <span style="color: orange;">&#9888; Logged-in users will NOT be tracked</span>
                        <?php else: ?>
                            <span style="color: green;">&#10004; All users will be tracked</span>
                        <?php endif; ?>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

    <!-- Current User Status -->
    <div class="card" style="max-width: 100%; margin-top: 20px;">
        <h2>Current User Status</h2>
        <?php $current_user = wp_get_current_user(); ?>
        <table class="widefat striped" style="margin-top: 10px;">
            <tbody>
                <tr>
                    <td><strong>User</strong></td>
                    <td><?php echo esc_html($current_user->display_name); ?> (ID: <?php echo esc_html($current_user->ID); ?>)</td>
                </tr>
                <tr>
                    <td><strong>Role</strong></td>
                    <td><?php echo esc_html(implode(', ', $current_user->roles)); ?></td>
                </tr>
                <tr>
                    <td><strong>Will your clicks be tracked?</strong></td>
                    <td>
                        <?php
                        $ignore_logged_in = get_option('pinnerpress_analytics_ignore_logged_in', '0') === '1';
                        if ($ignore_logged_in): ?>
                            <span style="color: red;"><strong>&#10008; NO</strong> - "Ignore logged-in users" is enabled</span>
                        <?php else: ?>
                            <span style="color: green;"><strong>&#10004; YES</strong></span>
                        <?php endif; ?>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

    <!-- Danger Zone -->
    <div class="card" style="max-width: 100%; margin-top: 20px; background-color: #fff8e5; border-left: 4px solid #d63638;">
        <h2 style="color: #d63638;">Danger Zone</h2>
        <p>These actions are destructive and cannot be undone.</p>
        <p>
            <a href="<?php echo esc_url(admin_url('admin.php?page=pinnerpress-reset-analytics')); ?>" class="button" style="color: #d63638; border-color: #d63638;">
                Reset All Analytics Data
            </a>
            <span class="description" style="margin-left: 10px;">This will permanently delete all analytics data from all tables.</span>
        </p>
    </div>

    <hr style="margin: 30px 0;" />

    <h2>Logs</h2>

    <?php if ($analytics_exists && $analytics_count > 0): ?>
    <!-- Event Type Breakdown -->
    <div class="card" style="max-width: 100%; margin-top: 20px;">
        <h3>Event Type Breakdown</h3>
        <?php
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Debug query
        $event_counts = $wpdb->get_results("SELECT event_type, COUNT(*) as count FROM `" . esc_sql($analytics_table) . "` GROUP BY event_type ORDER BY count DESC");
        ?>
        <table class="widefat striped" style="margin-top: 10px;">
            <thead>
                <tr>
                    <th>Event Type</th>
                    <th>Count</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($event_counts as $event): ?>
                <tr>
                    <td><code><?php echo esc_html($event->event_type); ?></code></td>
                    <td><?php echo esc_html(number_format($event->count)); ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <!-- Recent Events -->
    <div class="card" style="max-width: 100%; margin-top: 20px;">
        <h3>Recent Events (Last 10)</h3>
        <?php
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Debug query
        $recent_events = $wpdb->get_results("SELECT * FROM `" . esc_sql($analytics_table) . "` ORDER BY created_at DESC LIMIT 10");
        ?>
        <table class="widefat striped" style="margin-top: 10px;">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Event Type</th>
                    <th>Post ID</th>
                    <th>Created At</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($recent_events as $event): ?>
                <tr>
                    <td><?php echo esc_html($event->id); ?></td>
                    <td><code><?php echo esc_html($event->event_type); ?></code></td>
                    <td><?php echo esc_html($event->post_id); ?></td>
                    <td><?php echo esc_html($event->created_at); ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <div class="card" style="max-width: 100%; margin-top: 20px;">
        <p><em>No event data to display. Events will appear here once analytics tracking begins.</em></p>
    </div>
    <?php endif; ?>

    <!-- Debug Tips -->
    <div class="card" style="max-width: 100%; margin-top: 20px;">
        <h3>Debug Tips</h3>
        <ul style="list-style: disc; margin-left: 20px;">
            <li>Add <code>?pinnerpress_debug=1</code> to any admin page URL to enable JavaScript console logging</li>
            <li>If tables are missing, click "Repair Tables" above to create them</li>
            <li>If "Ignore logged-in users" is enabled, test analytics in an incognito window</li>
            <li>Post Analytics requires the <code>post_analytics</code> table to have data from impressions/clicks</li>
            <li>The <code>post_analytics</code> table is populated when users view posts (impressions) or click buttons</li>
        </ul>
    </div>
</div>
