<?php

function bwdcv_get_user_token( $user_id ): string {
    $user = get_userdata( $user_id );
    if ( !$user ) {
        return '';
    }

    $token = get_user_meta( $user_id, 'wp_cv_user_token', true );
    if ( !$token ) {
        bwdcv_generate_user_token( $user_id );
        $token = get_user_meta( $user_id, 'wp_cv_user_token', true );
    }

    return $token;
}

function bwdcv_generate_user_token( $user_id ): string {
    $user = get_userdata( $user_id );
    if ( !$user ) {
        return '';
    }

    $email = $user->user_email;
    $timezone = get_option( 'timezone_string' ) ?: 'UTC';
    $domain = $_SERVER['SERVER_NAME'];

    $raw = $domain . '|' . $timezone . '|' . $email;
    $token = hash( 'sha256', $raw );

    add_user_meta( $user_id, 'wp_cv_user_token', $token );

    return $token;
}

function get_cv_page_token_url() {
    $page_id = get_the_ID();
    if ( !$page_id || $page_id === 0 ) {
        return '';
    }
    $creator_user_id = get_post_field( 'post_author', $page_id );
    $user_token = bwdcv_get_user_token( $creator_user_id );
    $args = [
        'post_type'      => 'cv',
        'posts_per_page' => 1,
        'author'         => $creator_user_id,
        'post_status'    => 'publish',
    ];
    $pages = get_posts( $args );
    if ( empty( $pages ) ) {
        return '';
    }
    $page_url = get_permalink( $pages[0]->ID );
    return add_query_arg( 'token', $user_token, $page_url );
}



function bwdcv_output_qr_canvas( $linkedin_url, $qrWidth = '150' ) {
    $qr_url = apply_filters( 'bwdcv_qr_code_link', get_cv_page_token_url(), $linkedin_url );

    echo '<canvas
        id="qr-code-canvas"
        data-url="' . esc_attr( $qr_url ) . '"
        data-qr-color="#000000"
        data-qr-bg-color="#ffffff"
        data-qr-width="' . esc_attr( $qrWidth ) . '"
        data-qr-margin="1"
        data-qr-correction-level="L">
        </canvas>';
}


// Free and Pro Download
/**
 * Outputs the appropriate download button based on template and subscription status
 * 
 * @param string $style The current template style being rendered
 * @param string $getEditLink The edit link HTML markup
 * @param array $subscription_orders User's subscription orders data
 */
function render_cv_download_button($style, $getEditLink = '', $subscription_orders = []) {
    $options = get_option('bwd_userfronted_options');
    $main_options = get_option('bwdcv_preview_options', array());
    $download_text = esc_html( get_option( 'cv_download_bwd', esc_html__( 'Download', 'cv-builder' ) ) );
    
    // Check for valid subscription
    $hasValidSubscription = false;
    if (is_array($subscription_orders) && !empty($subscription_orders)) {
        foreach ($subscription_orders as $order) {
            $isActive = isset($order['status']) && ($order['status'] === 'completed' || $order['status'] === 'processing');
            $perDownload = isset($order['per_download']) ? intval($order['per_download']) : 0;
            $billingPeriod = isset($order['billing_period']) ? intval($order['billing_period']) : 0;
            if ($isActive && ($perDownload >= 1 || $billingPeriod >= 1)) {
                $hasValidSubscription = true;
                break;
            }
        }
    }

    // Find matching template and output button
    for ($i = 1; $i <= 28; $i++) {
        if ($style === 'style' . $i) {
            $isTemplatePro = !empty($main_options['cv_allow_style' . $i]);
            
            if ($hasValidSubscription) {
                echo '<div class="bwd-downl-btn">',
                     '<button class="bwd-download-text">', $download_text, '</button>',
                     wp_kses_post($getEditLink),
                     '</div>';
            } elseif ($isTemplatePro) {
                echo '<div class="bwd-go-subscription">',
                     '<a class="bwd-go-subscription-text" href="', esc_url(get_permalink($options['subscription_page'])), '">',
                     $download_text, '</a>',
                     wp_kses_post($getEditLink),
                     '</div>';
            } else {
                echo '<div class="bwd-downl-btn">',
                     '<button class="bwd-download-text" data-order-id="0" data-cv-download="0" ',
                     'data-subscription-billing-period="" data-template-style="', esc_attr('style' . $i), '">',
                     $download_text, '</button>',
                     wp_kses_post($getEditLink),
                     '</div>';
            }
            break;
        }
    }
}