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

add_action( 'admin_post_nopriv_elementsell_access', 'elementsell_handle_legacy_access_request' );
add_action( 'admin_post_elementsell_access', 'elementsell_handle_legacy_access_request' );
add_action( 'admin_post_nopriv_elementsell_go', 'elementsell_handle_customer_go' );
add_action( 'admin_post_elementsell_go', 'elementsell_handle_customer_go' );

/**
 * @param string $email
 * @param int    $exclude_order_id
 * @return bool
 */
function elementsell_customer_has_completed_access( $email, $exclude_order_id = 0 ) {
    global $wpdb;

    $email = strtolower( sanitize_email( (string) $email ) );

    if ( $email === '' ) {
        return false;
    }

    $sql    = "SELECT 1
               FROM {$wpdb->prefix}elementsell_orders o
               INNER JOIN {$wpdb->prefix}elementsell_order_fields f ON f.order_id = o.id
               WHERE LOWER(o.email) = %s
               AND f.field_name = 'access_completed_at'
               AND f.field_value != ''";
    $params = [ $email ];

    $exclude_order_id = (int) $exclude_order_id;

    if ( $exclude_order_id > 0 ) {
        $sql     .= ' AND o.id != %d';
        $params[] = $exclude_order_id;
    }

    $sql .= ' LIMIT 1';

    return (bool) $wpdb->get_var( $wpdb->prepare( $sql, $params ) );
}

/**
 * @param object $order
 * @return bool
 */
function elementsell_is_returning_customer_for_order( $order ) {
    if ( ! $order || empty( $order->email ) ) {
        return false;
    }

    if ( ! elementsell_customer_has_completed_access( $order->email, (int) $order->id ) ) {
        return false;
    }

    $user = get_user_by( 'email', sanitize_email( (string) $order->email ) );

    if ( ! $user ) {
        return false;
    }

    $created_for_order_id = (int) get_user_meta( $user->ID, 'elementsell_created_for_order_id', true );

    if ( $created_for_order_id === (int) $order->id ) {
        return false;
    }

    return true;
}

/**
 * Připraví e-mail pro opakovaný test: smaže WP účet a zruší dokončený přístup u objednávek.
 *
 * @param string $email
 * @return int|WP_Error Počet ovlivněných objednávek.
 */
function elementsell_reset_customer_access_test_state( $email ) {
    $email = sanitize_email( (string) $email );

    if ( $email === '' || ! is_email( $email ) ) {
        return new WP_Error( 'elementsell_invalid_email', 'Zadejte platný e-mail.' );
    }

    $user = get_user_by( 'email', $email );

    if ( $user ) {
        if ( user_can( $user, 'manage_options' ) ) {
            return new WP_Error(
                'elementsell_admin_email',
                'Účet správce webu nelze smazat. Pro test použijte jiný e-mail.'
            );
        }

        if ( ! wp_delete_user( (int) $user->ID ) ) {
            return new WP_Error( 'elementsell_delete_user', 'WP účet se nepodařilo smazat.' );
        }
    }

    global $wpdb;

    $orders_table = $wpdb->prefix . 'elementsell_orders';
    $fields_table = $wpdb->prefix . 'elementsell_order_fields';
    $order_ids    = $wpdb->get_col(
        $wpdb->prepare(
            "SELECT id FROM {$orders_table} WHERE LOWER(email) = LOWER(%s)",
            $email
        )
    );

    foreach ( (array) $order_ids as $order_id ) {
        $order_id = (int) $order_id;

        elementsell_delete_order_access_token( $order_id );

        $wpdb->delete(
            $fields_table,
            [
                'order_id'   => $order_id,
                'field_name' => 'access_completed_at',
            ],
            [ '%d', '%s' ]
        );
    }

    return count( (array) $order_ids );
}

/**
 * U opakovaného nákupu přiřadí roli a označí objednávku jako dokončenou bez nového hesla.
 *
 * @param object $order
 * @return void
 */
function elementsell_complete_returning_customer_access( $order ) {
    if ( ! $order || elementsell_is_order_access_completed( (int) $order->id ) ) {
        return;
    }

    if ( ! elementsell_is_returning_customer_for_order( $order ) ) {
        return;
    }

    if ( ! elementsell_setup_customer_account_for_order( $order ) ) {
        return;
    }

    $user = get_user_by( 'email', sanitize_email( (string) $order->email ) );

    if ( $user ) {
        elementsell_save_customer_login_redirect(
            (int) $user->ID,
            (string) elementsell_get_order_field( $order->id, 'login_url' )
        );
    }

    elementsell_mark_order_access_completed( (int) $order->id );
}

/**
 * @param int $order_id
 * @return bool
 */
function elementsell_is_order_access_completed( $order_id ) {
    return (string) elementsell_get_order_field( $order_id, 'access_completed_at' ) !== '';
}

/**
 * @param int $order_id
 * @return void
 */
function elementsell_mark_order_access_completed( $order_id ) {
    elementsell_save_order_field( $order_id, 'access_completed_at', current_time( 'mysql' ) );
    elementsell_delete_order_access_token( (int) $order_id );
}

/**
 * @param int $order_id
 * @return void
 */
function elementsell_delete_order_access_token( $order_id ) {
    global $wpdb;

    $wpdb->delete(
        $wpdb->prefix . 'elementsell_order_fields',
        [
            'order_id'   => (int) $order_id,
            'field_name' => 'access_token',
        ],
        [ '%d', '%s' ]
    );
}

/**
 * @param object $order
 * @param string $password
 * @return string|WP_Error
 */
function elementsell_complete_order_access( $order, $password ) {
    if ( elementsell_is_order_access_completed( (int) $order->id ) ) {
        return new WP_Error( 'elementsell_access_done', 'Přístup už byl nastavený.' );
    }

    if ( strlen( $password ) < 8 ) {
        return new WP_Error( 'elementsell_password_short', 'Heslo musí mít alespoň 8 znaků.' );
    }

    if ( ! elementsell_should_send_login_credentials( (int) $order->id ) ) {
        return new WP_Error( 'elementsell_access_disabled', 'Pro tuto objednávku není povolen přístup.' );
    }

    if ( elementsell_email_belongs_to_site_admin( $order->email ) ) {
        return new WP_Error(
            'elementsell_admin_email',
            'Tento e-mail patří správci webu. Pro test platby použijte jiný e-mail, nebo se přihlaste jako zákazník.'
        );
    }

    $user = elementsell_setup_customer_account_for_order( $order );

    if ( ! $user ) {
        return new WP_Error( 'elementsell_user_failed', 'Účet se nepodařilo připravit. Kontaktujte podporu.' );
    }

    wp_set_password( $password, $user->ID );

    $signed_in = wp_signon(
        [
            'user_login'    => $user->user_login,
            'user_password' => $password,
            'remember'      => true,
        ],
        is_ssl()
    );

    if ( is_wp_error( $signed_in ) ) {
        return new WP_Error( 'elementsell_signon_failed', 'Přihlášení se nepodařilo. Zkuste to prosím znovu.' );
    }

    elementsell_mark_order_access_completed( (int) $order->id );

    $destination = elementsell_normalize_login_redirect_url(
        (string) elementsell_get_order_field( $order->id, 'login_url' )
    );

    elementsell_save_customer_login_redirect( (int) $user->ID, $destination );

    return $destination;
}

/**
 * Starý odkaz z e-mailu přesměruje na návratovou stránku objednávky.
 *
 * @return void
 */
function elementsell_handle_legacy_access_request() {
    $token = isset( $_REQUEST['token'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['token'] ) ) : '';
    $order = elementsell_get_order_by_access_token( $token );

    if ( ! $order ) {
        wp_safe_redirect( elementsell_get_thank_you_page_url() );
        exit;
    }

    wp_safe_redirect( elementsell_get_thank_you_url_for_order( $order ) );
    exit;
}

/**
 * @param string $token
 * @return object|null
 */
function elementsell_get_order_by_access_token( $token ) {
    global $wpdb;

    $token = sanitize_text_field( (string) $token );

    if ( $token === '' ) {
        return null;
    }

    $order_id = $wpdb->get_var(
        $wpdb->prepare(
            "SELECT order_id
             FROM {$wpdb->prefix}elementsell_order_fields
             WHERE field_name = %s
             AND field_value = %s
             LIMIT 1",
            'access_token',
            $token
        )
    );

    if ( ! $order_id ) {
        return null;
    }

    return elementsell_get_order( (int) $order_id );
}

/**
 * @param object $order
 * @return string
 */
function elementsell_get_post_login_destination_for_order( $order ) {
    $login_url = trim( (string) elementsell_get_order_field( $order->id, 'login_url' ) );

    if ( $login_url !== '' && function_exists( 'elementsell_ensure_page_from_widget_url' ) ) {
        elementsell_ensure_page_from_widget_url( $login_url, 'login_destination' );
    }

    return elementsell_normalize_login_redirect_url( $login_url );
}

/**
 * @param object $order
 * @return bool
 */
function elementsell_order_matches_current_user( $order ) {
    if ( ! is_user_logged_in() || ! $order ) {
        return false;
    }

    $user = wp_get_current_user();

    return strtolower( $user->user_email ) === strtolower( (string) $order->email );
}

/**
 * @param object $order
 * @return string
 */
function elementsell_get_customer_go_url( $order ) {
    return add_query_arg(
        [
            'action'      => 'elementsell_go',
            'payment_uid' => rawurlencode( (string) $order->payment_uid ),
        ],
        admin_url( 'admin-post.php' )
    );
}

/**
 * Chytrý vstup z e-mailu: přihlášeného pošle rovnou na obsah, jinak na návratovou stránku nebo přihlášení.
 *
 * @return void
 */
function elementsell_handle_customer_go() {
    $payment_uid = isset( $_GET['payment_uid'] ) ? sanitize_text_field( wp_unslash( $_GET['payment_uid'] ) ) : '';
    $order       = $payment_uid ? elementsell_get_order_by_payment_uid( $payment_uid ) : null;

    if ( ! $order ) {
        wp_safe_redirect( elementsell_get_thank_you_page_url() );
        exit;
    }

    if ( ! elementsell_should_send_login_credentials( (int) $order->id ) ) {
        wp_safe_redirect( elementsell_get_thank_you_url_for_order( $order ) );
        exit;
    }

    $destination = elementsell_get_post_login_destination_for_order( $order );

    elementsell_complete_returning_customer_access( $order );

    if ( elementsell_is_order_access_completed( (int) $order->id ) ) {
        if ( elementsell_order_matches_current_user( $order ) ) {
            wp_safe_redirect( $destination );
            exit;
        }

        wp_safe_redirect( wp_login_url( $destination ) );
        exit;
    }

    wp_safe_redirect( elementsell_get_thank_you_url_for_order( $order ) );
    exit;
}

/**
 * @param object $order
 * @return string
 */
function elementsell_build_access_button_html( $order ) {
    $url = elementsell_get_customer_go_url( $order );

    return '<p style="text-align:center;margin:28px 0 8px;">'
        . '<a href="' . esc_url( $url ) . '" style="display:inline-block;padding:14px 28px;background-color:#4CAF50;color:#ffffff;text-decoration:none;border-radius:8px;font-size:16px;font-weight:700;">JDEME NA TO</a>'
        . '</p>';
}
