<?php
if(!defined('ABSPATH')){exit;}
function drop_print_create_global_attribute($name, $slug){
    if(!function_exists('wc_attribute_taxonomy_name')||!function_exists('wc_create_attribute')){
        error_log('[DropPrint Client ERROR] WooCommerce attribute functions not available for attribute: ' . $name);
        return false;
    }
    $taxonomy_name = wc_attribute_taxonomy_name($slug);
    if(!taxonomy_exists($taxonomy_name)){
        $attribute_id = wc_create_attribute(
            array(
                'name' => $name,
                'slug' => $slug,
                'type' => 'select',
                'order_by' => 'menu_order',
                'has_archives' => false,
            )
        );
        if(is_wp_error($attribute_id)){
            error_log('[DropPrint Client ERROR] Failed to create WooCommerce attribute: ' . $attribute_id->get_error_message());
            return false;
        }
        register_taxonomy(
            $taxonomy_name,
            array('product'),
            array(
                'labels' => array(
                    'name' => $name,
                    'singular_name' => $name,
                ),
                'hierarchical' => false,
                'show_ui' => false,
                'query_var' => true,
                'rewrite' => false,
            )
        );
        delete_transient('wc_attribute_taxonomies');
        return true;
    }
    return true;
}
function drop_print_is_file_in_live_order($afp_base_filename){
    if(empty($afp_base_filename)){
        return false;
    }
    $live_order_statuses = apply_filters('drop_print_live_order_statuses', array(
        'wc-pending',
        'wc-processing',
        'wc-on-hold',
    ));
    if(empty($live_order_statuses)){
        return false;
    }
    $orders = wc_get_orders(array(
        'status' => $live_order_statuses,
        'limit' => -1,
        'orderby' => 'date',
        'order' => 'DESC',
    ));
    if(empty($orders)){
        return false;
    }
    foreach($orders as $order){
        if(!$order){
            continue;
        }
        $items = $order->get_items();
        foreach($items as $item){
            if(!$item instanceof WC_Order_Item_Product){
                continue;
            }
            $product_id = $item->get_product_id();
            $parent_product_id = $product_id;
            if($item->get_variation_id() > 0){
                $parent_product_id = $item->get_product_id();
            }
            if($parent_product_id > 0){
                $drop_print_meta = get_post_meta($parent_product_id, '_drop_print_meta', true);
                if(is_array($drop_print_meta) && isset($drop_print_meta['file']) && $drop_print_meta['file'] === $afp_base_filename){
                    return true;
                }
            }
        }
    }
    return false;
}
function drop_print_get_default_user_settings(){
    return [
        'client_user_connection_id' => null,
        'public_key_pem_b64' => null,
        'auth_username_b64' => null,
        'auth_password_b64' => null,
        'pro_status' => 0,
        'billing_currency' => null,
        'available_media' => [],
        'media_last_updated' => 0,
        'user_display_name' => null,
        'default_media_id' => 'ask',
        'payment_frequency' => 'pay_as_you_go',
        'auto_production' => 'off',
        'default_shipping_method' => 'standard',
        'available_shipping_methods' => [],
        'place_order_blocked_text' => '',
        'default_image_resize' => 'fill',
        'packing_slip_attachment_id' => 0,
        'us_sales_tax_collected' => 'false',
        'encryption' => false,
        'default_intent' => 'ask',
        'default_customer_location' => '',
        'onboarding_completed_version' => '',
        'payment_method_snapshot' => ['has_card' => false, 'brand' => null, 'last4' => null, 'exp_month' => null, 'exp_year' => null],
    ];
}
function drop_print_crop_mode_to_prodigi_sizing(string $mode): string {
    switch ($mode) {
        case 'fit':
            return 'fitPrintArea';
        case 'border':
            return 'fillPrintArea';
        case 'fill':
        default:
            return 'fillPrintArea';
    }
}
function drop_print_get_user_settings($user_id = 0){
    if($user_id === 0){
        $user_id = get_current_user_id();
    }
    if($user_id === 0){
        return drop_print_get_default_user_settings();
    }
    $defaults = drop_print_get_default_user_settings();
    $saved_settings = get_user_meta($user_id, 'drop_print_user_settings', true);
    if(!is_array($saved_settings)){
        $saved_settings = [];
    }
    return wp_parse_args($saved_settings, $defaults);
}
function drop_print_note_api_auth_status(int $status_code): void {
    if (in_array($status_code, [401, 403], true)) {
        if (false === get_option('drop_print_outbound_401_seen', false)) {
            update_option('drop_print_outbound_401_seen', time(), false);
        }
    } elseif (200 === $status_code) {
        delete_option('drop_print_outbound_401_seen');
    }
}
function drop_print_client_refresh_data_and_status($user_id = 0){
    if($user_id === 0){
        $user_id = get_current_user_id();
    }
    if($user_id === 0){
        error_log('[DropPrint Client ERROR] User context not found for settings refresh.');
        return ['status' => false, 'message' => __('User context not found for settings refresh.', 'drop-print'), 'data' => []];
    }
    $settings = drop_print_get_user_settings($user_id);
    $api_base_url = defined('DROP_PRINT_API_URI') ? DROP_PRINT_API_URI : null;
    $api_user_b64 = $settings['auth_username_b64'] ?? null;
    $api_pass_b64 = $settings['auth_password_b64'] ?? null;
    if(empty($api_base_url) || empty($api_user_b64) || empty($api_pass_b64)){
        error_log('[DropPrint Client ERROR] Not connected or API details incomplete in user settings for user ID: ' . $user_id);
        return ['status' => false, 'message' => __('Not connected or API details incomplete in user settings.', 'drop-print'), 'data' => []];
    }
    $api_username = base64_decode($api_user_b64);
    $api_password = base64_decode($api_pass_b64);
    if(false === $api_username || false === $api_password){
        error_log('[DropPrint Client ERROR] Failed to decode API credentials for user ID: ' . $user_id);
        return ['status' => false, 'message' => __('Failed to decode API credentials for user.', 'drop-print'), 'data' => []];
    }
    $auth_header = 'Basic '.base64_encode($api_username.':'.$api_password);
    $default_args = [
        'method' => 'GET',
        'headers' => ['Authorization' => $auth_header, 'Accept' => 'application/json'],
        'timeout' => 30,
    ];
    $pro_status_refreshed = false;
    $pro_status_url = trailingslashit($api_base_url).'subscription-status';
    $pro_response = wp_remote_get($pro_status_url, $default_args);
    $current_user_settings = drop_print_get_user_settings($user_id);
    if(is_wp_error($pro_response)){
        error_log('[DropPrint Client ERROR] wp_remote_get error for PRO status for user ID ' . $user_id . ': ' . $pro_response->get_error_message());
    }else{
        $status_code = wp_remote_retrieve_response_code($pro_response);
        drop_print_note_api_auth_status($status_code);
        $body = wp_remote_retrieve_body($pro_response);
        $server_data = json_decode($body, true);
        if($status_code === 200 && isset($server_data['success'], $server_data['data']['is_pro']) && $server_data['success']){
            $current_user_settings['pro_status'] = (int) $server_data['data']['is_pro'];
            $pro_status_refreshed = true;
        }else{
            error_log('[DropPrint Client ERROR] PRO status response not successful or invalid format for user ID ' . $user_id . '. Status: ' . $status_code . ', Data: ' . print_r($server_data, true));
        }
    }
    $media_types_url = trailingslashit($api_base_url).'papers';
    $media_response = wp_remote_get($media_types_url, $default_args);
    $fetched_media_types = [];
    $media_types_fetched_successfully = false;
    if(is_wp_error($media_response)){
        error_log('[DropPrint Client ERROR] wp_remote_get error for media types for user ID ' . $user_id . ': ' . $media_response->get_error_message());
    }else{
        $media_status_code = wp_remote_retrieve_response_code($media_response);
        drop_print_note_api_auth_status($media_status_code);
        $media_body = wp_remote_retrieve_body($media_response);
        $media_data = json_decode($media_body, true);
        if($media_status_code === 200 && is_array($media_data)){
            $sanitized_media_data = [];
            foreach($media_data as $m_item){
                if(isset($m_item['id']) && isset($m_item['name']) && is_string($m_item['id']) && is_string($m_item['name'])){
                    $sanitized_media_data[] = ['id' => sanitize_key($m_item['id']), 'name' => sanitize_text_field($m_item['name'])];
                } else {
                    error_log('[DropPrint Client WARNING] Skipping malformed media item for user ID ' . $user_id . ': ' . print_r($m_item, true));
                }
            }
            $current_user_settings['available_media'] = $sanitized_media_data;
            $current_user_settings['media_last_updated'] = time();
            $fetched_media_types = $sanitized_media_data;
            $media_types_fetched_successfully = true;
        }else{
            error_log('[DropPrint Client ERROR] Media types response not successful or invalid format for user ID ' . $user_id . '. Status: ' . $media_status_code . ', Data: ' . print_r($media_data, true));
        }
    }
    $shipping_tiers_url = trailingslashit($api_base_url).'shipping-tiers';
    $shipping_tiers_response = wp_remote_get($shipping_tiers_url, $default_args);
    if(is_wp_error($shipping_tiers_response)){
        error_log('[DropPrint Client ERROR] wp_remote_get error for shipping tiers for user ID ' . $user_id . ': ' . $shipping_tiers_response->get_error_message());
    }else{
        $shipping_tiers_status_code = wp_remote_retrieve_response_code($shipping_tiers_response);
        drop_print_note_api_auth_status($shipping_tiers_status_code);
        $shipping_tiers_body = wp_remote_retrieve_body($shipping_tiers_response);
        $shipping_tiers_data = json_decode($shipping_tiers_body, true);
        if($shipping_tiers_status_code === 200 && is_array($shipping_tiers_data)){
            $sanitized_shipping_tiers = [];
            foreach($shipping_tiers_data as $t_item){
                if(isset($t_item['slug']) && isset($t_item['label']) && is_string($t_item['slug']) && is_string($t_item['label'])){
                    $sanitized_shipping_tiers[] = ['slug' => sanitize_key($t_item['slug']), 'label' => sanitize_text_field($t_item['label'])];
                } else {
                    error_log('[DropPrint Client WARNING] Skipping malformed shipping-tier item for user ID ' . $user_id . ': ' . print_r($t_item, true));
                }
            }
            if(!empty($sanitized_shipping_tiers)){
                $current_user_settings['available_shipping_methods'] = $sanitized_shipping_tiers;
            }
        }else{
            error_log('[DropPrint Client ERROR] Shipping tiers response not successful or invalid format for user ID ' . $user_id . '. Status: ' . $shipping_tiers_status_code . ', Data: ' . print_r($shipping_tiers_data, true));
        }
    }
    $account_state_url = trailingslashit($api_base_url).'account-state';
    $account_state_args = [
        'method' => 'POST',
        'headers' => ['Authorization' => $auth_header, 'Content-Type' => 'application/json; charset=utf-8', 'Accept' => 'application/json'],
        'timeout' => 15,
        'body' => wp_json_encode(['client_wp_user_id' => $user_id]),
    ];
    $account_state_response = wp_remote_post($account_state_url, $account_state_args);
    if(is_wp_error($account_state_response)){
        error_log('[DropPrint Client ERROR] wp_remote_post error for account-state for user ID ' . $user_id . ': ' . $account_state_response->get_error_message());
    }else{
        $account_state_status_code = wp_remote_retrieve_response_code($account_state_response);
        drop_print_note_api_auth_status($account_state_status_code);
        $account_state_body = wp_remote_retrieve_body($account_state_response);
        $account_state_data = json_decode($account_state_body, true);
        if($account_state_status_code === 200 && is_array($account_state_data)){
            $account_state = function_exists('drop_print_extract_pro_upgrade_account_state')
                ? drop_print_extract_pro_upgrade_account_state($account_state_data)
                : (isset($account_state_data['data']) && is_array($account_state_data['data']) ? $account_state_data['data'] : $account_state_data);
            if(!empty($account_state) && isset($account_state['is_pro'])){
                $current_user_settings['pro_account_state_snapshot'] = $account_state;
                $current_user_settings['pro_status'] = (int) (bool) $account_state['is_pro'];
            }
            if(isset($account_state['payment_method']) && is_array($account_state['payment_method'])){
                $current_user_settings['payment_method_snapshot'] = $account_state['payment_method'];
            }
        }else{
            error_log('[DropPrint Client ERROR] account-state response not successful or invalid format for user ID ' . $user_id . '. Status: ' . $account_state_status_code);
        }
    }
    delete_transient('drop_print_offer_refresh_' . $user_id);
    update_user_meta($user_id, 'drop_print_user_settings', $current_user_settings);
    if(empty($fetched_media_types) && !empty($current_user_settings['available_media']) && $media_types_fetched_successfully){
        $fetched_media_types = $current_user_settings['available_media'];
    }elseif(empty($fetched_media_types) && !empty($current_user_settings['available_media'])){
        $fetched_media_types = $current_user_settings['available_media'];
    }
    $final_status = $pro_status_refreshed && $media_types_fetched_successfully;
    $message = $final_status ?
        __('Subscription status and papers refreshed successfully for current user.', 'drop-print') :
        __('Refresh process for current user completed. Some items may not have updated. Check logs for details.', 'drop-print');
    return [
        'status' => $final_status,
        'message' => $message,
        'data' => ['pro_status_updated' => $pro_status_refreshed, 'media_types_count' => count($fetched_media_types)]
    ];
}
function drop_print_get_order_item_sku( WC_Order_Item_Product $item ): string {
    $sku = $item->get_meta( '_dp_sku' );
    if ( empty( $sku ) ) {
        $sku = $item->get_meta( 'pa_print_dimensions' );
    }
    if ( empty( $sku ) ) {
        return '';
    }
    return strtoupper( sanitize_text_field( (string) $sku ) );
}
function drop_print_get_cart_item_sku( array $cart_item ): string {
    $sku = '';
    if ( ! empty( $cart_item['variation_id'] ) ) {
        $sku = get_post_meta( absint( $cart_item['variation_id'] ), '_drop_print_sku', true );
    }
    if ( empty( $sku ) && ! empty( $cart_item['variation']['attribute_pa_print_dimensions'] ) ) {
        $sku = $cart_item['variation']['attribute_pa_print_dimensions'];
    }
    if ( empty( $sku ) && ! empty( $cart_item['data'] ) && is_object( $cart_item['data'] ) && method_exists( $cart_item['data'], 'get_sku' ) ) {
        $sku = $cart_item['data']->get_sku();
    }
    if ( empty( $sku ) ) {
        return '';
    }
    return strtoupper( sanitize_text_field( (string) $sku ) );
}
function drop_print_get_order_item_crop( WC_Order_Item_Product $item, array $user_settings ): array {
    $raw = $item->get_meta( '_dp_sizing' );
    if ( empty( $raw ) ) {
        $variation_id = $item->get_variation_id();
        if ( $variation_id ) {
            $raw = get_post_meta( absint( $variation_id ), '_drop_print_sizing', true );
        }
    }
    if ( ! empty( $raw ) ) {
        $decoded = is_array( $raw ) ? $raw : json_decode( (string) $raw, true );
        if ( is_array( $decoded ) && ! empty( $decoded['mode'] ) && in_array( $decoded['mode'], array( 'fit', 'fill', 'border' ), true ) ) {
            return array(
                'mode'           => (string) $decoded['mode'],
                'borderFraction' => max( 0.0, min( 0.9, (float) ( $decoded['borderFraction'] ?? 0 ) ) ),
                'rotated'        => ! empty( $decoded['rotated'] ),
            );
        }
    }
    return array(
        'mode'           => (string) ( $user_settings['default_image_resize'] ?? 'fill' ),
        'borderFraction' => 0.0,
        'rotated'        => false,
    );
}
function drop_print_get_order_item_crop_mode( WC_Order_Item_Product $item, array $user_settings ): string {
    return drop_print_get_order_item_crop( $item, $user_settings )['mode'];
}
