<?php
if(!defined('ABSPATH')){exit;}
if(!function_exists('drop_print_build_unified_order_payload')){
    function drop_print_build_unified_order_payload(WC_Order $order, array $user_settings, string $submission_type, bool $use_new_card_flow_param, ?string $selected_shipping_method_pref = null, ?array &$skipped_items = null): array{
        $skipped_items=[];
        $payload_items=[];
        $upload_dir_info=wp_upload_dir();
        $drop_print_upload_baseurl='';
        if(isset($upload_dir_info['baseurl'])){
            $drop_print_upload_baseurl=trailingslashit($upload_dir_info['baseurl']).'drop-print/';
        }
        $admin_email=get_option('admin_email');
        $order_currency=$order->get_currency();
        $order_key=$order->get_order_key();
        foreach($order->get_items()as $item_id=>$item){
            if(!$item instanceof WC_Order_Item_Product){
                continue;
            }
            $product=$item->get_product();
            $parent_product_id_for_meta=$item->get_product_id();
            $variation_id=$item->get_variation_id();
            $client_product_identifier=$variation_id?(string)$variation_id:(string)$parent_product_id_for_meta;
            $client_item_actual_name=$item->get_name();
            $line_item_sku='';
            $order_item_crop=drop_print_get_order_item_crop($item,$user_settings);
            $sizing_preference=drop_print_crop_mode_to_prodigi_sizing($order_item_crop['mode']);
            $client_product_identifier_for_ref = $variation_id ? (string)$variation_id : (string)$parent_product_id_for_meta;
            $base_display_title = '';
            $attribute_display_string = '';
            $afp_file_url=null;
            $dp_meta=get_post_meta($parent_product_id_for_meta,'_drop_print_meta',true);
            if(is_array($dp_meta)&&!empty($dp_meta['file'])){
                $container_ext=defined('DROP_PRINT_CONTAINER_EXT')?DROP_PRINT_CONTAINER_EXT:'.drop';
                $file_name_with_ext=sanitize_file_name($dp_meta['file']).$container_ext;
                if($drop_print_upload_baseurl){
                    $afp_file_url=$drop_print_upload_baseurl.$file_name_with_ext;
                }
            }
            if(empty($afp_file_url)){
                $skipped_items[]=['item_id'=>$item_id,'name'=>sanitize_text_field($item->get_name()),'reason'=>'no_print_file'];
                continue;
            }
            if($product){
                if($product->is_type('variation')){
                    $parent_product = wc_get_product($product->get_parent_id());
                    $base_display_title = $parent_product ? $parent_product->get_name() : $product->get_name();
                    $attribute_display_string = trim(wp_strip_all_tags(wc_get_formatted_variation($product, false, false, false)));
                }else{
                    $base_display_title = $product->get_name();
                    $order_item_name = $item->get_name();
                    if($order_item_name !== $base_display_title && strpos($order_item_name, $base_display_title) === 0){
                        $potential_attrs = trim(substr($order_item_name, strlen($base_display_title)), " \t\n\r\0\x0B-–,");
                        if(!empty($potential_attrs)){
                            $attribute_display_string = $potential_attrs;
                        }
                    }
                }
            }else{
                $base_display_title = $item->get_name();
            }
            $safe_base_display_title = sanitize_text_field($base_display_title);
            if(empty($line_item_sku)){
                 $line_item_sku=drop_print_get_order_item_sku($item);
            }
            if(empty($line_item_sku)){
                $skipped_items[]=['item_id'=>$item_id,'name'=>$safe_base_display_title,'reason'=>'unresolvable_sku'];
                continue;
            }
            $item_attributes_to_send=null;
            $expected_source_sha256='';
            if(function_exists('drop_print_files_get_record')){
                $file_record=drop_print_files_get_record($dp_meta['file']);
                if(is_array($file_record)&&!empty($file_record['source_sha256'])){
                    $expected_source_sha256=sanitize_text_field($file_record['source_sha256']);
                }
            }
            if(''===$expected_source_sha256&&!empty($dp_meta['source_sha256'])){
                $expected_source_sha256=sanitize_text_field($dp_meta['source_sha256']);
            }
            $assets_payload=[['printArea'=>'default','url'=>esc_url_raw($afp_file_url),'sha256'=>$expected_source_sha256,]];
            $safe_title=sanitize_text_field($client_item_actual_name);
            $safe_title=str_replace('|','-',$safe_title);
            $safe_title=preg_replace('/[^\p{L}\p{N}\s\.,\-\'"&\(\)]/u','',$safe_title);
            if(mb_strlen($safe_title)>60){
                $safe_title=mb_substr($safe_title,0,57).'...';
            }
            $final_merchant_reference=$client_product_identifier;
            if(!empty(trim($safe_title))){
                $final_merchant_reference.='|'.$safe_title;
            }
            $item_quantity = $item->get_quantity();
            $item_total_paid = (float) $item->get_total();
            $item_per_unit_price = ($item_quantity > 0) ? ($item_total_paid / $item_quantity) : 0;
            $recipient_cost_data = [
                'amount'   => wc_format_decimal($item_per_unit_price, wc_get_price_decimals()),
                'currency' => $order_currency
            ];
            $payload_items[] = [
                'merchantReference' => $client_product_identifier_for_ref,
                'sku' => sanitize_text_field($line_item_sku),
                'copies' => $item_quantity,
                'sizing' => sanitize_text_field($sizing_preference),
                'crop' => [
                    'mode' => sanitize_text_field((string) $order_item_crop['mode']),
                    'borderFraction' => (float) $order_item_crop['borderFraction'],
                    'rotated' => (bool) $order_item_crop['rotated'],
                ],
                'attributes' => $item_attributes_to_send,
                'client_item_base_title_for_display' => $safe_base_display_title,
                'client_item_attribute_details_for_display' => sanitize_text_field($attribute_display_string),
                'recipientCost' => $recipient_cost_data,
                'assets' => $assets_payload
            ];
        }
        if(empty($payload_items)){
            return[];
        }
        $shipping_company_name=trim($order->get_shipping_company());
        $shipping_full_name=trim($order->get_shipping_first_name().' '.$order->get_shipping_last_name());
        $billing_company_name=trim($order->get_billing_company());
        $billing_full_name=trim($order->get_billing_first_name().' '.$order->get_billing_last_name());
        $company_to_use='';
        $name_to_use='';
        if(!empty($shipping_full_name)||!empty($shipping_company_name)){
            $company_to_use=$shipping_company_name;
            $name_to_use=$shipping_full_name;
        }elseif(!empty($billing_full_name)||!empty($billing_company_name)){
            $company_to_use=$billing_company_name;
            $name_to_use=$billing_full_name;
        }
        $recipient_name_str='';
        if(!empty($company_to_use)){
            $recipient_name_str=$company_to_use;
            if(!empty($name_to_use)){
                $recipient_name_str.=', '.$name_to_use;
            }
        }elseif(!empty($name_to_use)){
            $recipient_name_str=$name_to_use;
        }else{
            $recipient_name_str='Valued Customer';
        }
        $recipient_name_str=trim($recipient_name_str);
        if(empty($recipient_name_str)){
            $recipient_name_str='Valued Customer';
        }
        $phone_number=$order->get_shipping_phone('edit');
        if(empty($phone_number))$phone_number=$order->get_billing_phone('edit');
        $email_address=$order->get_billing_email();
        if(empty($email_address))$email_address=$admin_email;
        $destination_country_code=$order->get_shipping_country()?:$order->get_billing_country();
        $recipient_payload=[
            'name'=>sanitize_text_field(trim($recipient_name_str)),
            'phoneNumber'=>sanitize_text_field($phone_number?:''),
            'email'=>sanitize_email($email_address),
            'address'=>[
                'line1'=>sanitize_text_field($order->get_shipping_address_1()?:$order->get_billing_address_1()),
                'line2'=>sanitize_text_field($order->get_shipping_address_2()?:$order->get_billing_address_2()),
                'postalOrZipCode'=>sanitize_text_field($order->get_shipping_postcode()?:$order->get_billing_postcode()),
                'countryCode'=>strtoupper(sanitize_text_field($destination_country_code)),
                'townOrCity'=>sanitize_text_field($order->get_shipping_city()?:$order->get_billing_city()),
                'stateOrCounty'=>sanitize_text_field($order->get_shipping_state()?:$order->get_billing_state())
            ]
        ];
        $packing_slip_url = null;
        $packing_slip_attachment_id = $user_settings['packing_slip_attachment_id'] ?? 0;
        if($packing_slip_attachment_id > 0){
            $url = wp_get_attachment_url(absint($packing_slip_attachment_id));
            if($url){
                $packing_slip_url = esc_url_raw($url);
            }
        }
        $us_sales_tax_bool=($user_settings['us_sales_tax_collected']??'false')==='true';
        $final_shipping_method=$selected_shipping_method_pref??($user_settings['default_shipping_method']??'standard');
        $payload_to_server=[
            'merchantReference'=>(string)$order->get_id(),
            'shippingMethod'=>sanitize_key($final_shipping_method),
            'idempotencyKey'=>(string)$order_key,
            'recipient'=>$recipient_payload,
            'packingSlip'=> $packing_slip_url ? ['url' => $packing_slip_url] : null,
            'USSalesTaxAlreadyCollected'=>$us_sales_tax_bool,
            'items'=>$payload_items,
            'callbackUrl'=>rest_url('drop-print-client/v1/order-status-update'),
            'metadata'=>[
                'sourceId'=>'drop-print-client-'.(defined('DROP_PRINT_VERSION')?DROP_PRINT_VERSION:'1.1'),
                'client_plugin_version'=>(defined('DROP_PRINT_VERSION')?DROP_PRINT_VERSION:'1.1.3'),
                'client_is_pro'=>(bool)($user_settings['pro_status']??false),
                'client_auto_production_setting'=>($user_settings['auto_production']??'off'),
                'submissionType'=>sanitize_key($submission_type),
                'use_new_card_flow'=>(bool)$use_new_card_flow_param
            ]
        ];
        return $payload_to_server;
    }
}
?>
