<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * @return string
 */
function elementsell_get_landing_leads_table_name() {
    global $wpdb;

    return $wpdb->prefix . 'elementsell_landing_leads';
}

/**
 * @param array<string, mixed> $data
 * @return int
 */
function elementsell_save_landing_lead( $data ) {
    global $wpdb;

    $table = elementsell_get_landing_leads_table_name();

    $wpdb->insert(
        $table,
        [
            'first_name'     => isset( $data['first_name'] ) ? sanitize_text_field( (string) $data['first_name'] ) : '',
            'surname'        => isset( $data['surname'] ) ? sanitize_text_field( (string) $data['surname'] ) : '',
            'website'        => isset( $data['website'] ) ? esc_url_raw( (string) $data['website'] ) : '',
            'product_intent' => isset( $data['product_intent'] ) ? sanitize_textarea_field( (string) $data['product_intent'] ) : '',
            'created_at'     => current_time( 'mysql' ),
        ],
        [ '%s', '%s', '%s', '%s', '%s' ]
    );

    return (int) $wpdb->insert_id;
}

/**
 * Uloží poptávku jako zaplacenou objednávku (viditelná v ElementSell → Objednávky).
 *
 * @param array{first_name?: string, surname?: string, email?: string, website?: string, product_intent?: string} $data
 * @return int Order ID nebo 0.
 */
function elementsell_create_landing_contact_order( $data ) {
    global $wpdb;

    if ( ! function_exists( 'elementsell_save_order_field' ) ) {
        return 0;
    }

    $first_name     = isset( $data['first_name'] ) ? sanitize_text_field( (string) $data['first_name'] ) : '';
    $surname        = isset( $data['surname'] ) ? sanitize_text_field( (string) $data['surname'] ) : '';
    $email          = isset( $data['email'] ) ? sanitize_email( (string) $data['email'] ) : '';
    $website        = isset( $data['website'] ) ? esc_url_raw( (string) $data['website'] ) : '';
    $product_intent = isset( $data['product_intent'] ) ? sanitize_textarea_field( (string) $data['product_intent'] ) : '';

    if ( $email === '' || ! is_email( $email ) ) {
        $email = sanitize_email( (string) get_option( 'elementsell_gmail_address', '' ) );
    }

    $product_name = $product_intent !== ''
        ? wp_html_excerpt( $product_intent, 80, '…' )
        : 'Poptávka z landingu';

    $now          = current_time( 'mysql' );
    $orders_table = $wpdb->prefix . 'elementsell_orders';

    $inserted = $wpdb->insert(
        $orders_table,
        [
            'order_uid'      => uniqid( 'lead_', true ),
            'payment_uid'    => '',
            'payment_method' => 'landing',
            'payment_status' => 'paid',
            'product_name'   => $product_name,
            'amount'         => 0,
            'currency'       => 'CZK',
            'email'          => $email,
            'first_name'     => $first_name,
            'surname'        => $surname,
            'phone'          => '',
            'vs'             => '',
            'pay_url'        => '',
            'return_url'     => $website,
            'created_at'     => $now,
            'updated_at'     => $now,
            'paid_at'        => $now,
        ],
        [ '%s', '%s', '%s', '%s', '%s', '%f', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' ]
    );

    if ( $inserted === false ) {
        error_log( 'ElementSell: chyba uložení poptávky z landingu: ' . $wpdb->last_error );

        return 0;
    }

    $order_id = (int) $wpdb->insert_id;

    if ( $order_id <= 0 ) {
        return 0;
    }

    elementsell_save_order_field( $order_id, 'landing_lead', '1' );
    elementsell_save_order_field( $order_id, 'environment', 'demo' );
    elementsell_save_order_field( $order_id, 'website', $website );
    elementsell_save_order_field( $order_id, 'product_intent', $product_intent );

    return $order_id;
}

/**
 * @param int $limit
 * @return array<int, object>
 */
function elementsell_get_landing_leads( $limit = 100 ) {
    global $wpdb;

    $table = elementsell_get_landing_leads_table_name();
    $limit = max( 1, min( 500, (int) $limit ) );

    return (array) $wpdb->get_results(
        $wpdb->prepare(
            "SELECT * FROM {$table} ORDER BY id DESC LIMIT %d",
            $limit
        )
    );
}

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

    $table = elementsell_get_landing_leads_table_name();

    return (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" );
}
