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

/**
 * Kryptograficky silný identifikátor platby / objednávky.
 *
 * @param string $prefix Volitelný prefix (např. fio_).
 * @return string
 */
function elementsell_generate_payment_uid( $prefix = '' ) {
    $prefix = preg_replace( '/[^a-zA-Z0-9_\-]/', '', (string) $prefix );

    try {
        $token = bin2hex( random_bytes( 16 ) );
    } catch ( Exception $e ) {
        $token = function_exists( 'wp_generate_password' )
            ? wp_generate_password( 32, false, false )
            : md5( uniqid( (string) wp_rand(), true ) );
    }

    return $prefix . $token;
}

function elementsell_save_order( $args = [] ) {
    global $wpdb;

    $defaults = [
        'order_uid'      => '',
        'payment_uid'    => '',
        'payment_method' => '',
        'payment_status' => 'pending',
        'vs'             => '',
        'pay_url'        => '',
        'return_url'     => '',
    ];

    $args = wp_parse_args( $args, $defaults );

    $email = isset($_POST['email']) ? sanitize_email($_POST['email']) : '';

    if ( empty($email) || ! is_email($email) ) {
        error_log('ElementSell: neplatný email.');
        return false;
    }

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

    $order_uid = ! empty($args['order_uid'])
        ? sanitize_text_field($args['order_uid'])
        : elementsell_generate_payment_uid( 'order_' );

    $payment_method = ! empty($args['payment_method'])
        ? sanitize_text_field($args['payment_method'])
        : (isset($_POST['payment_method']) ? sanitize_text_field($_POST['payment_method']) : '');

    $now = current_time('mysql');
    $order_data = [
        'order_uid'      => $order_uid,
        'payment_uid'    => sanitize_text_field($args['payment_uid']),
        'payment_method' => $payment_method,
        'payment_status' => sanitize_text_field($args['payment_status']),
        'product_name'   => isset($_POST['product_name']) ? sanitize_text_field($_POST['product_name']) : '',
        'amount'         => isset($_POST['amount']) ? floatval($_POST['amount']) : 0,
        'currency'       => 'CZK',
        'email'          => $email,
        'first_name'     => isset($_POST['first_name']) ? sanitize_text_field($_POST['first_name']) : '',
        'surname'        => isset($_POST['surname']) ? sanitize_text_field($_POST['surname']) : '',
        'phone'          => isset($_POST['phone']) ? sanitize_text_field($_POST['phone']) : '',
        'vs'             => sanitize_text_field($args['vs']),
        'pay_url'        => esc_url_raw($args['pay_url']),
        'return_url'     => esc_url_raw($args['return_url']),
        'created_at'     => $now,
        'updated_at'     => $now,
    ];

$inserted = $wpdb->insert($orders_table, $order_data);

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

    $order_id = $wpdb->insert_id;

    elementsell_save_order_fields($order_id);
    elementsell_save_standard_customer_fields_from_post( $order_id );
    elementsell_save_widget_profile_fields($order_id);
    elementsell_save_order_widget_context( $order_id );
    elementsell_save_custom_fields_from_post( $order_id );

    $widget_settings = isset( $args['widget_settings'] ) && is_array( $args['widget_settings'] )
        ? $args['widget_settings']
        : null;

    elementsell_save_upsell_from_post( $order_id, $widget_settings );
    elementsell_save_order_field( $order_id, 'gdpr_consent', 'implicit' );
    elementsell_save_order_field( $order_id, 'gdpr_consent_at', current_time( 'mysql' ) );
    elementsell_save_order_field( $order_id, 'gdpr_privacy_url', esc_url_raw( elementsell_get_privacy_page_url() ) );

    elementsell_create_invoice_for_order($order_id);

    do_action( 'elementsell_order_saved', $order_id );

    return $order_id;
}

function elementsell_save_order_fields( $order_id ) {
    global $wpdb;

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

    $system_fields = elementsell_get_system_order_fields();

    foreach ( $_POST as $field_name => $field_value ) {

        $field_name = sanitize_key($field_name);

        if ( in_array($field_name, $system_fields, true) ) {
            continue;
        }

        if ( is_array($field_value) ) {
            $field_value = wp_json_encode($field_value);
        }

        $field_value = sanitize_textarea_field((string) $field_value);

        if ( $field_value === '' ) {
            continue;
        }

        $wpdb->insert(
            $fields_table,
            [
                'order_id'    => intval($order_id),
                'field_name'  => $field_name,
                'field_value' => $field_value,
                'created_at'  => current_time('mysql'),
            ],
            [
                '%d',
                '%s',
                '%s',
                '%s',
            ]
        );
    }
}

/**
 * Uloží standardní pole z formuláře, která nejsou v tabulce objednávek.
 *
 * @param int $order_id
 * @return void
 */
function elementsell_save_standard_customer_fields_from_post( $order_id ) {
    $fields = [
        'address'       => 'Adresa',
        'company'       => 'Firma',
        'ico'           => 'IČO',
        'dic'           => 'DIČ',
        'discount_code' => 'Slevový kód',
    ];

    foreach ( $fields as $post_key => $label ) {
        if ( empty( $_POST[ $post_key ] ) ) {
            continue;
        }

        elementsell_save_order_label_field(
            $order_id,
            $label,
            sanitize_text_field( wp_unslash( (string) $_POST[ $post_key ] ) )
        );
    }
}

/**
 * Uloží odkaz na Elementor dokument a widget pro dohledání štítků polí.
 *
 * @param int $order_id
 * @return void
 */
function elementsell_save_order_widget_context( $order_id ) {
    if ( isset( $_POST['elementsell_post_id'] ) ) {
        elementsell_save_order_field(
            $order_id,
            'elementsell_post_id',
            (string) (int) $_POST['elementsell_post_id']
        );
    }

    if ( isset( $_POST['elementsell_widget_id'] ) ) {
        elementsell_save_order_field(
            $order_id,
            'elementsell_widget_id',
            sanitize_text_field( wp_unslash( (string) $_POST['elementsell_widget_id'] ) )
        );
    }
}

function elementsell_save_widget_profile_fields( $order_id ) {
    $create_profile = isset( $_POST['vytvorit_profil'] ) ? (int) $_POST['vytvorit_profil'] : 0;

    elementsell_save_order_field( $order_id, 'vytvorit_profil', (string) $create_profile );

    if ( isset( $_POST['login_url'] ) ) {
        $login_url = elementsell_normalize_page_url(
            sanitize_text_field( wp_unslash( $_POST['login_url'] ) )
        );

        if ( $login_url !== '' ) {
            elementsell_save_order_field( $order_id, 'login_url', $login_url );
        }
    }

    $source_page_url = '';

    if ( isset( $_POST['source_page_url'] ) ) {
        $source_page_url = elementsell_normalize_customer_source_page_url(
            wp_unslash( $_POST['source_page_url'] )
        );
    }

    if ( $source_page_url === '' && isset( $_POST['elementsell_post_id'] ) ) {
        $post_id = (int) $_POST['elementsell_post_id'];

        if ( $post_id > 0 && get_post_status( $post_id ) === 'publish' ) {
            $source_page_url = elementsell_normalize_customer_source_page_url(
                (string) get_permalink( $post_id )
            );
        }
    }

    if ( $source_page_url !== '' ) {
        elementsell_save_order_field( $order_id, 'source_page_url', $source_page_url );
    }

    elementsell_save_after_payment_widget_fields( $order_id );
    elementsell_ensure_widget_pages_from_payment_post();
}

/**
 * Uloží nastavení po zaplacení z widgetu (jsou v system fields, ne v custom polích).
 *
 * @param int $order_id
 * @return void
 */
function elementsell_save_after_payment_widget_fields( $order_id ) {
    $fields = [
        'email_subject'   => 'sanitize_text_field',
        'email_body'      => 'sanitize_textarea_field',
        'email_from_name' => 'sanitize_text_field',
    ];

    foreach ( $fields as $field_name => $sanitize_callback ) {
        if ( ! isset( $_POST[ $field_name ] ) ) {
            continue;
        }

        $value = call_user_func(
            $sanitize_callback,
            wp_unslash( (string) $_POST[ $field_name ] )
        );

        if ( $value === '' ) {
            continue;
        }

        elementsell_save_order_field( $order_id, $field_name, $value );
    }

    if ( isset( $_POST['navratova_url'] ) ) {
        $navratova_url = elementsell_normalize_page_url(
            wp_unslash( (string) $_POST['navratova_url'] )
        );

        if ( $navratova_url !== '' ) {
            elementsell_save_order_field( $order_id, 'navratova_url', $navratova_url );
        }
    }
}

function elementsell_get_system_order_fields() {
    return [
        'action',
        '_wpnonce',
        '_wp_http_referer',

        'amount',
        'payment_method',
        'product_name',

        'email',
        'first_name',
        'surname',
        'phone',
        'address',
        'company',
        'ico',
        'dic',
        'discount_code',

        'merchant_id',
        'project_id',
        'api_password',
        'environment',

        'email_subject',
        'email_body',
        'email_from_name',
        'navratova_url',

        'custom_field_label',
        'custom_field_type',
        'custom_field_value',
        'elementsell_custom_fields',

        'elementsell_post_id',
        'elementsell_widget_id',

        'vytvorit_profil',
        'login_url',
        'source_page_url',

        'upsell_accepted',
        'upsell_decided',
        'elementsell_hp',
    ];
}