<?php

/**
 * Dashboard REST endpoint, view tracking, and script enqueueing for the free plugin.
 *
 * @package domain-for-sale
 * @subpackage domain-for-sale/src/Admin
 * @author ThemeAtelier <themeatelierbd@gmail.com>
 */

namespace ThemeAtelier\DomainForSale\Admin;

use WP_REST_Server;

class Dashboard
{
    function __construct()
    {
        $this->create_views_table();
        add_action('template_redirect', [$this, 'track_domain_view'], 5);
        add_action('dfs_shortcode_rendered', [$this, 'record_view']);
        add_action('rest_api_init', [$this, 'register_rest_routes']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_scripts'], 100);
    }

    /**
     * Creates the domain views table if it doesn't already exist.
     * Called once per request; uses a SHOW TABLES check to skip dbDelta on existing tables.
     */
    public function create_views_table()
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'dfs_domain_views';

        if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table_name)) === $table_name) { // phpcs:ignore
            return;
        }

        $charset_collate = $wpdb->get_charset_collate();
        $sql = "CREATE TABLE {$table_name} (
            id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            domain_id BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
            viewed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY  (id),
            KEY domain_id (domain_id)
        ) {$charset_collate};";

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

    /**
     * Inserts one row into wp_dfs_domain_views for the given domain post ID.
     * Called from shortcode hook and template_redirect hook.
     */
    public function record_view($domain_id)
    {
        $domain_id  = (int) $domain_id;
        $cookie_key = 'dfs_imp_' . $domain_id;

        if (!empty($_COOKIE[$cookie_key])) {
            return;
        }

        setcookie($cookie_key, '1', time() + 1800, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true);
        $_COOKIE[$cookie_key] = '1';

        global $wpdb;
        $wpdb->insert( // phpcs:ignore
            $wpdb->prefix . 'dfs_domain_views',
            ['domain_id' => $domain_id, 'viewed_at' => current_time('mysql')]
        );
    }

    /**
     * Tracks views for replace_theme and singular dfs_template modes.
     * Fires at template_redirect priority 5 — before Frontend.php's include+die (priority 10).
     * Shortcode mode is handled separately via the dfs_shortcode_rendered action.
     */
    public function track_domain_view()
    {
        if (is_admin() || is_preview() || is_feed() || is_customize_preview() || current_user_can('manage_options') || defined('DOMAIN_FOR_SALE_PRO_VERSION')) {
            return;
        }

        // Case 1: visitor viewing a singular dfs_template post directly.
        if (is_singular('dfs_template')) {
            $this->record_view(get_queried_object_id());
            return;
        }

        // Case 2: replace_theme — the plugin replaces the entire theme on every page load.
        $posts = get_posts(['post_type' => 'dfs_template', 'posts_per_page' => -1, 'fields' => 'ids']);
        foreach ($posts as $post_id) {
            $opts = get_post_meta($post_id, 'dfs_template_options', true);
            if (!empty($opts['dfs_apply_on']) && $opts['dfs_apply_on'] === 'replace_theme') {
                $this->record_view($post_id);
                return;
            }
        }
    }

    public function register_rest_routes()
    {
        register_rest_route(
            'domain-for-sale/v1',
            '/dashboard',
            [
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => [$this, 'get_dashboard_stats'],
                'permission_callback' => fn() => current_user_can('manage_options'),
            ]
        );
    }

    public function get_dashboard_stats()
    {
        global $wpdb;

        $total_domains = (int) wp_count_posts('dfs_template')->publish;

        $table_offers = $wpdb->prefix . 'domain_for_sale_offers';
        $total_offers = (int) $wpdb->get_var("SELECT COUNT(*) FROM `{$table_offers}`"); // phpcs:ignore

        $table_views       = $wpdb->prefix . 'dfs_domain_views';
        $total_impressions = 0;
        if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table_views)) === $table_views) { // phpcs:ignore
            $total_impressions = (int) $wpdb->get_var("SELECT COUNT(*) FROM `{$table_views}`"); // phpcs:ignore
        }

        $total_listings = (int) wp_count_posts('domain_listing')->publish;

        $current_user = wp_get_current_user();
        $user_name    = $current_user->display_name ?: $current_user->user_login;

        return [
            'total_domains'     => $total_domains,
            'total_offers'      => $total_offers,
            'total_impressions' => $total_impressions,
            'total_listings'    => $total_listings,
            'user_name'         => $user_name,
            'version'           => DOMAIN_FOR_SALE_VERSION,
        ];
    }

    public function enqueue_scripts($hook)
    {
        if ($hook !== 'toplevel_page_domain-for-sale') {
            return;
        }

        add_action('admin_print_scripts', function () {
            echo wp_print_inline_script_tag(
                'window.domainForSaleDashboard = ' . wp_json_encode([
                    'restUrl'   => esc_url_raw(rest_url('domain-for-sale/v1')),
                    'nonce'     => wp_create_nonce('wp_rest'),
                    'version'   => DOMAIN_FOR_SALE_VERSION,
                    'pluginUrl' => DOMAIN_FOR_SALE_URL,
                ]) . ';'
            );
        });

        wp_enqueue_script(
            'domain-for-sale-admin-ui',
            plugin_dir_url(__FILE__) . 'assets/js/domain-for-sale-admin-ui.js',
            [],
            DOMAIN_FOR_SALE_VERSION,
            true
        );
    }
}
