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

add_action( 'init', 'elementsell_ensure_unsubscribe_page', 12 );
add_action( 'template_redirect', 'elementsell_handle_unsubscribe_page_request', 1 );

/**
 * @return string
 */
function elementsell_get_default_unsubscribe_page_slug() {
    return 'odhlasit';
}

/**
 * @return bool
 */
function elementsell_is_unsubscribe_page() {
    if ( ! is_page() ) {
        return false;
    }

    $page_id = (int) get_option( 'elementsell_unsubscribe_page_id', 0 );

    return is_page( elementsell_get_default_unsubscribe_page_slug() )
        || ( $page_id > 0 && is_page( $page_id ) );
}

/**
 * @return int
 */
function elementsell_ensure_unsubscribe_page() {
    if ( elementsell_is_elementor_context() ) {
        return (int) get_option( 'elementsell_unsubscribe_page_id', 0 );
    }

    $page_id = (int) get_option( 'elementsell_unsubscribe_page_id', 0 );

    if ( $page_id > 0 && get_post_status( $page_id ) === 'publish' ) {
        elementsell_sync_unsubscribe_page_content( $page_id );
        return $page_id;
    }

    $slug     = elementsell_get_default_unsubscribe_page_slug();
    $existing = get_page_by_path( $slug );

    if ( $existing instanceof WP_Post && $existing->post_status === 'publish' ) {
        update_option( 'elementsell_unsubscribe_page_id', (int) $existing->ID );
        elementsell_sync_unsubscribe_page_content( (int) $existing->ID );
        return (int) $existing->ID;
    }

    $page_id = wp_insert_post(
        [
            'post_title'   => 'Odhlášení z newsletteru',
            'post_name'    => $slug,
            'post_status'  => 'publish',
            'post_type'    => 'page',
            'post_content' => '',
        ],
        true
    );

    if ( is_wp_error( $page_id ) ) {
        error_log( 'ElementSell: nepodařilo se vytvořit stránku odhlášení: ' . $page_id->get_error_message() );
        return 0;
    }

    update_post_meta( (int) $page_id, '_elementsell_unsubscribe_auto', '1' );
    update_option( 'elementsell_unsubscribe_page_id', (int) $page_id );

    return (int) $page_id;
}

/**
 * @param int $page_id
 * @return void
 */
function elementsell_sync_unsubscribe_page_content( $page_id ) {
    $page_id = (int) $page_id;

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

    $page = get_post( $page_id );

    if ( ! $page instanceof WP_Post ) {
        return;
    }

    if ( trim( (string) $page->post_content ) === '' ) {
        return;
    }

    wp_update_post(
        [
            'ID'           => $page_id,
            'post_content' => '',
        ]
    );
}

/**
 * @return string
 */
function elementsell_get_unsubscribe_page_url() {
    $page_id = elementsell_ensure_unsubscribe_page();

    if ( $page_id > 0 ) {
        $permalink = get_permalink( $page_id );

        if ( $permalink ) {
            return $permalink;
        }
    }

    return home_url( '/' . elementsell_get_default_unsubscribe_page_slug() . '/' );
}

/**
 * @param string $email
 * @return true|WP_Error
 */
function elementsell_process_unsubscribe_email( $email ) {
    if ( ! function_exists( 'elementsell_add_email_to_blacklist' ) ) {
        return new WP_Error( 'elementsell_unsubscribe_unavailable', 'Odhlášení není momentálně dostupné.' );
    }

    return elementsell_add_email_to_blacklist( $email, 'unsubscribe' );
}

/**
 * @param string $message
 * @return void
 */
function elementsell_render_unsubscribe_blank_page( $message = '' ) {
    nocache_headers();

    ?><!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo( 'charset' ); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="robots" content="noindex,nofollow">
    <title><?php echo esc_html( $message !== '' ? $message : 'Odhlášení' ); ?></title>
    <style>
        html,
        body {
            margin: 0;
            padding: 0;
            width: 100%;
            min-height: 100vh;
            background: #fff;
            font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
            color: #222;
        }

        body {
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
        }

        .elementsell-unsubscribe-message {
            font-size: clamp(28px, 5vw, 42px);
            font-weight: 500;
            line-height: 1.2;
            text-align: center;
        }
    </style>
</head>
<body><?php echo $message !== '' ? '<span class="elementsell-unsubscribe-message">' . esc_html( $message ) . '</span>' : ''; ?></body>
</html>
    <?php
}

/**
 * @return void
 */
function elementsell_handle_unsubscribe_page_request() {
    if ( ! elementsell_is_unsubscribe_page() ) {
        return;
    }

    $message = '';

    if ( isset( $_GET['email'], $_GET['token'] ) ) {
        $email = elementsell_normalize_mailing_email( wp_unslash( (string) $_GET['email'] ) );
        $token = sanitize_text_field( wp_unslash( (string) $_GET['token'] ) );

        if ( $email !== '' && elementsell_verify_unsubscribe_token( $email, $token ) ) {
            $result = elementsell_process_unsubscribe_email( $email );

            if ( ! is_wp_error( $result ) ) {
                $message = 'Odhlášeno';
            }
        }
    }

    elementsell_render_unsubscribe_blank_page( $message );
    exit;
}
