<?php
/**
 * Setup health snapshot pro centrální statistiky.
 */
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Odfiltruje zjevný odpad typu "aaa" / "test".
 *
 * @param string $value
 * @param int    $min_len
 * @return bool
 */
function elementsell_telemetry_value_looks_filled( $value, $min_len = 3 ) {
    $value = trim( (string) $value );

    if ( strlen( $value ) < $min_len ) {
        return false;
    }

    $lower = strtolower( $value );
    $junk  = [ 'aaa', 'bbb', 'xxx', 'test', 'asdf', 'qwerty', 'password', 'heslo', 'demo', 'null', 'none' ];

    if ( in_array( $lower, $junk, true ) ) {
        return false;
    }

    // Opakující se stejný znak (aaa, 1111).
    if ( preg_match( '/^(.)\1{2,}$/u', $lower ) ) {
        return false;
    }

    return true;
}

/**
 * get_permalink() padá, když $wp_rewrite ještě není (např. admin-post / publish redirect).
 *
 * @param int $post_id
 * @return string
 */
function elementsell_telemetry_safe_permalink( $post_id ) {
    $post_id = (int) $post_id;

    if ( $post_id <= 0 ) {
        return '';
    }

    global $wp_rewrite;

    if ( ! isset( $wp_rewrite ) || ! is_object( $wp_rewrite ) ) {
        return home_url( '/?p=' . $post_id );
    }

    $permalink = get_permalink( $post_id );

    return is_string( $permalink ) ? $permalink : '';
}

/**
 * @param array{project_id?: int, merchant_id?: string, api_password?: string} $credentials
 * @return bool
 */
function elementsell_telemetry_thepay_credentials_look_valid( $credentials ) {
    if ( ! is_array( $credentials ) ) {
        return false;
    }

    $project_id   = (int) ( $credentials['project_id'] ?? 0 );
    $merchant_id  = trim( (string) ( $credentials['merchant_id'] ?? '' ) );
    $api_password = trim( (string) ( $credentials['api_password'] ?? '' ) );

    if ( $project_id < 1 ) {
        return false;
    }

    if ( ! elementsell_telemetry_value_looks_filled( $merchant_id, 3 ) ) {
        return false;
    }

    if ( ! elementsell_telemetry_value_looks_filled( $api_password, 8 ) ) {
        return false;
    }

    return true;
}

/**
 * Formulář na publikované stránce/příspěvku (Elementor widget).
 *
 * @return bool
 */
function elementsell_telemetry_has_payment_form_on_published() {
    return elementsell_telemetry_get_any_payment_form_page_url() !== '';
}

/**
 * Permalink první publikované stránky s formulářem (fallback).
 *
 * @return string
 */
function elementsell_telemetry_get_any_payment_form_page_url() {
    global $wpdb;

    $like_new = '%' . $wpdb->esc_like( 'elementsell_payment_form' ) . '%';
    $like_old = '%' . $wpdb->esc_like( 'platebni_formular' ) . '%';

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $post_id = (int) $wpdb->get_var(
        $wpdb->prepare(
            "SELECT p.ID
             FROM {$wpdb->posts} p
             INNER JOIN {$wpdb->postmeta} pm
                ON pm.post_id = p.ID AND pm.meta_key = '_elementor_data'
             WHERE p.post_status = 'publish'
               AND p.post_type IN ( 'page', 'post' )
               AND ( pm.meta_value LIKE %s OR pm.meta_value LIKE %s )
             ORDER BY p.ID DESC
             LIMIT 1",
            $like_new,
            $like_old
        )
    );

    if ( $post_id <= 0 ) {
        return '';
    }

    $url = elementsell_telemetry_safe_permalink( $post_id );

    return $url !== '' ? esc_url_raw( $url ) : '';
}

/**
 * Stránka s formulářem s nejvíce reálnými (produkčními) prodeji.
 *
 * @return array{url: string, sales: int}
 */
function elementsell_telemetry_get_top_payment_form_page() {
    global $wpdb;

    $result = [
        'url'   => '',
        'sales' => 0,
    ];

    $orders_table = $wpdb->prefix . 'elementsell_orders';
    $fields_table = $wpdb->prefix . 'elementsell_order_fields';

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $orders_table ) );

    if ( $table_exists !== $orders_table ) {
        $fallback = elementsell_telemetry_get_any_payment_form_page_url();

        return [
            'url'   => $fallback,
            'sales' => 0,
        ];
    }

    $production = function_exists( 'elementsell_billing_get_production_orders_sql' )
        ? elementsell_billing_get_production_orders_sql( 'o' )
        : '';

    // 1) Podle source_page_url u produkčních paid objednávek.
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    $by_url = $wpdb->get_row(
        "SELECT f.field_value AS page_url, COUNT(*) AS sales_count
         FROM {$orders_table} o
         INNER JOIN {$fields_table} f
            ON f.order_id = o.id
           AND f.field_name = 'source_page_url'
           AND f.field_value <> ''
         WHERE o.payment_status = 'paid'
         {$production}
         GROUP BY f.field_value
         ORDER BY sales_count DESC, page_url ASC
         LIMIT 1"
    );

    if ( $by_url && ! empty( $by_url->page_url ) ) {
        $url = function_exists( 'elementsell_normalize_customer_source_page_url' )
            ? elementsell_normalize_customer_source_page_url( (string) $by_url->page_url )
            : esc_url_raw( (string) $by_url->page_url );

        if ( $url !== '' ) {
            $result['url']   = $url;
            $result['sales'] = (int) $by_url->sales_count;
        }
    }

    // 2) Podle elementsell_post_id — může mít víc prodejů než URL (starší data).
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    $by_post = $wpdb->get_row(
        "SELECT f.field_value AS post_id, COUNT(*) AS sales_count
         FROM {$orders_table} o
         INNER JOIN {$fields_table} f
            ON f.order_id = o.id
           AND f.field_name = 'elementsell_post_id'
           AND CAST(f.field_value AS UNSIGNED) > 0
         WHERE o.payment_status = 'paid'
         {$production}
         GROUP BY f.field_value
         ORDER BY sales_count DESC, CAST(f.field_value AS UNSIGNED) ASC
         LIMIT 1"
    );

    if ( $by_post && (int) $by_post->post_id > 0 && (int) $by_post->sales_count > (int) $result['sales'] ) {
        $post_id = (int) $by_post->post_id;

        if ( get_post_status( $post_id ) === 'publish' ) {
            $permalink = elementsell_telemetry_safe_permalink( $post_id );

            if ( $permalink !== '' ) {
                $url = function_exists( 'elementsell_normalize_customer_source_page_url' )
                    ? elementsell_normalize_customer_source_page_url( $permalink )
                    : esc_url_raw( $permalink );

                if ( $url !== '' ) {
                    $result['url']   = $url;
                    $result['sales'] = (int) $by_post->sales_count;
                }
            }
        }
    }

    if ( $result['url'] === '' ) {
        $result['url'] = elementsell_telemetry_get_any_payment_form_page_url();
    }

    return $result;
}

/**
 * @return bool
 */
function elementsell_telemetry_fio_credentials_look_valid() {
    $account = function_exists( 'elementsell_get_fio_account_number' )
        ? (string) elementsell_get_fio_account_number()
        : '';
    $token = function_exists( 'elementsell_fio_get_api_token' )
        ? trim( (string) elementsell_fio_get_api_token() )
        : '';

    if ( $account === '' || ! elementsell_telemetry_value_looks_filled( $account, 3 ) ) {
        return false;
    }

    if ( ! elementsell_telemetry_value_looks_filled( $token, 16 ) ) {
        return false;
    }

    return true;
}

/**
 * @return int
 */
function elementsell_get_demo_paid_orders_count() {
    global $wpdb;

    $orders_table = $wpdb->prefix . 'elementsell_orders';
    $fields_table = $wpdb->prefix . 'elementsell_order_fields';

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $orders_table ) );

    if ( $table_exists !== $orders_table ) {
        return 0;
    }

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    return (int) $wpdb->get_var(
        "SELECT COUNT(DISTINCT o.id)
         FROM {$orders_table} o
         INNER JOIN {$fields_table} f
            ON f.order_id = o.id
           AND f.field_name = 'environment'
           AND f.field_value = 'demo'
         WHERE o.payment_status = 'paid'"
    );
}

/**
 * @return float
 */
function elementsell_get_demo_paid_revenue_total() {
    global $wpdb;

    $orders_table = $wpdb->prefix . 'elementsell_orders';
    $fields_table = $wpdb->prefix . 'elementsell_order_fields';

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $orders_table ) );

    if ( $table_exists !== $orders_table ) {
        return 0.0;
    }

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    return (float) $wpdb->get_var(
        "SELECT COALESCE(SUM(o.amount), 0)
         FROM {$orders_table} o
         INNER JOIN {$fields_table} f
            ON f.order_id = o.id
           AND f.field_name = 'environment'
           AND f.field_value = 'demo'
         WHERE o.payment_status = 'paid'"
    );
}

/**
 * Snapshot stavu instalace — bez tajných credentials.
 *
 * @return array<string, mixed>
 */
function elementsell_telemetry_get_setup_health() {
    $thepay_demo = function_exists( 'elementsell_resolve_thepay_credentials_from_options_strict' )
        ? elementsell_resolve_thepay_credentials_from_options_strict( 'demo' )
        : [];
    $thepay_prod = function_exists( 'elementsell_resolve_thepay_credentials_from_options_strict' )
        ? elementsell_resolve_thepay_credentials_from_options_strict( 'production' )
        : [];

    $thepay_ok = elementsell_telemetry_thepay_credentials_look_valid( $thepay_demo )
        || elementsell_telemetry_thepay_credentials_look_valid( $thepay_prod );
    $fio_ok    = elementsell_telemetry_fio_credentials_look_valid();

    $demo_paid = function_exists( 'elementsell_get_demo_paid_orders_count' )
        ? elementsell_get_demo_paid_orders_count()
        : 0;
    $prod_paid = function_exists( 'elementsell_get_production_paid_orders_count' )
        ? elementsell_get_production_paid_orders_count()
        : 0;

    $prod_revenue = 0.0;

    if ( function_exists( 'elementsell_sales_stats_get_totals' ) ) {
        $totals       = elementsell_sales_stats_get_totals();
        $prod_revenue = (float) ( $totals['revenue'] ?? 0 );
    }

    $admin_email = sanitize_email( (string) get_option( 'admin_email', '' ) );
    $owner_email = function_exists( 'elementsell_get_invoice_supplier_email' )
        ? (string) elementsell_get_invoice_supplier_email()
        : '';

    if ( $owner_email === '' ) {
        $owner_email = $admin_email;
    }

    $top_form = elementsell_telemetry_get_top_payment_form_page();

    return [
        'setup_plugin_installed'      => 1,
        'setup_form_on_site'          => ( $top_form['url'] !== '' || elementsell_telemetry_has_payment_form_on_published() ) ? 1 : 0,
        'setup_thepay_ok'             => $thepay_ok ? 1 : 0,
        'setup_fio_ok'                => $fio_ok ? 1 : 0,
        'setup_payment_ok'            => ( $thepay_ok || $fio_ok ) ? 1 : 0,
        'setup_test_sales_done'       => $demo_paid > 0 ? 1 : 0,
        'setup_gmail_ok'              => (
            function_exists( 'elementsell_gmail_smtp_is_configured' )
            && elementsell_gmail_smtp_is_configured()
        ) ? 1 : 0,
        'setup_invoice_ok'            => (
            function_exists( 'elementsell_billing_are_invoice_details_complete' )
            && elementsell_billing_are_invoice_details_complete()
        ) ? 1 : 0,
        'elementor_version'           => defined( 'ELEMENTOR_VERSION' ) ? (string) ELEMENTOR_VERSION : '',
        'admin_email'                 => $admin_email,
        'contact_email'               => $owner_email !== '' ? $owner_email : $admin_email,
        'demo_paid_orders'            => (int) $demo_paid,
        'demo_revenue_total'          => round( elementsell_get_demo_paid_revenue_total(), 2 ),
        'production_paid_orders'      => (int) $prod_paid,
        'production_revenue_total'    => round( $prod_revenue, 2 ),
        'top_form_page_url'           => (string) $top_form['url'],
        'top_form_page_sales'         => (int) $top_form['sales'],
    ];
}
