<?php
if(!defined('ABSPATH')){exit;}
add_action('woocommerce_payment_complete','drop_print_maybe_queue_auto_production',20,1);
add_action('woocommerce_order_status_processing','drop_print_maybe_queue_auto_production',20,1);
add_action('woocommerce_order_status_completed','drop_print_maybe_queue_auto_production',20,1);
const DROP_PRINT_AUTO_PRODUCTION_CLAIM_META = '_drop_print_auto_production_claimed';
const DROP_PRINT_AUTO_PRODUCTION_ACTION = 'drop_print_run_auto_production';
function drop_print_maybe_queue_auto_production($order_id){
    $order_id = absint($order_id);
    if($order_id === 0){return;}
    $order = wc_get_order($order_id);
    if(!$order instanceof WC_Order){return;}
    if($order->get_meta(DROP_PRINT_AUTO_PRODUCTION_CLAIM_META,true)){return;}
    $existing_details = $order->get_meta('_drop_print_order_details',true);
    if(is_array($existing_details) && !empty($existing_details['payment_intent_id'])){return;}
    $responsible_user_id = drop_print_get_responsible_user_for_auto_production();
    if($responsible_user_id === 0){return;}
    $user_settings = drop_print_get_user_settings($responsible_user_id);
    if(($user_settings['auto_production'] ?? 'off') !== 'on'){
        return;
    }
    $order->update_meta_data(DROP_PRINT_AUTO_PRODUCTION_CLAIM_META,time());
    $order->save();
    if(function_exists('as_enqueue_async_action')){
        as_enqueue_async_action(DROP_PRINT_AUTO_PRODUCTION_ACTION,array($order_id),'drop-print');
    }else{
        wp_schedule_single_event(time()+5,DROP_PRINT_AUTO_PRODUCTION_ACTION,array($order_id));
    }
}
function drop_print_run_auto_production_job($order_id){
    $order_id = absint($order_id);
    if($order_id === 0){return;}
    $order = wc_get_order($order_id);
    if(!$order instanceof WC_Order){return;}
    drop_print_initiate_auto_production_flow($order_id,array(),$order);
}
add_action(DROP_PRINT_AUTO_PRODUCTION_ACTION,'drop_print_run_auto_production_job',10,1);
function drop_print_get_responsible_user_for_auto_production(){
    $responsible_user_id = apply_filters('drop_print_auto_production_responsible_user_id', 0);
    if($responsible_user_id > 0 && get_userdata($responsible_user_id)){
        return $responsible_user_id;
    }
    $admin_users = get_users(array('role__in' => array('administrator'), 'orderby' => 'ID'));
    foreach($admin_users as $admin_user){
        $settings = drop_print_get_user_settings($admin_user->ID);
        if(!empty($settings['auth_username_b64']) && !empty($settings['auth_password_b64'])
            && ($settings['auto_production'] ?? 'off') === 'on'){
            return $admin_user->ID;
        }
    }
    foreach($admin_users as $admin_user){
        $settings = drop_print_get_user_settings($admin_user->ID);
        if(!empty($settings['auth_username_b64']) && !empty($settings['auth_password_b64'])){
            return $admin_user->ID;
        }
    }
    if(!empty($admin_users)){
        return $admin_users[0]->ID;
    }
    return 0;
}
if(!function_exists('drop_print_initiate_auto_production_flow')){
    function drop_print_initiate_auto_production_flow($client_order_id,$posted_data,WC_Order $order){
        $responsible_user_id = drop_print_get_responsible_user_for_auto_production();
        if($responsible_user_id === 0){
            return;
        }
        $user_settings = drop_print_get_user_settings($responsible_user_id);
        $auto_production_enabled=($user_settings['auto_production']??'off')==='on';
        if(!$auto_production_enabled){return;}
        if(!$client_order_id||!$order){
            return;
        }
        if(!function_exists('drop_print_build_unified_order_payload')||!function_exists('drop_print_make_server_request_for_ajax')){
            $order->add_order_note(__('Drop Print Auto-Production Error: Critical client plugin function missing. Please contact support.','drop-print'));
            return;
        }
        $order->add_order_note(__('Attempting Drop Print Auto-Production...','drop-print'));
        $skipped_items=[];
        $initial_payload=drop_print_build_unified_order_payload($order,$user_settings,'auto_production_init',true,($user_settings['default_shipping_method']??'standard'),$skipped_items);
        if(!empty($skipped_items)){
            $skipped_names=implode(', ',array_map(static function($skipped){return $skipped['name'].' ('.$skipped['reason'].')';},$skipped_items));
            $order->add_order_note(sprintf(__('Drop Print Auto-Production: %s item(s) need re-saving in the Drop Print builder and were not sent for production: %s','drop-print'),count($skipped_items),$skipped_names));
        }
        if(empty($initial_payload)||empty($initial_payload['items'])){
            $msg=__('No valid items to process for auto-production. This may be due to missing print files or inaccessible print file URLs (e.g., 404 errors). Please check product setup.','drop-print');
            $order_note_text = __('Drop Print Auto-Production Failed: %1$s','drop-print');
            $order->add_order_note(sprintf($order_note_text, $msg));
            $order->update_meta_data('_drop_print_order_details',['status'=>'auto_production_asset_invalid','last_server_message'=>$msg,'last_client_update'=>time(), 'responsible_user_id' => $responsible_user_id]);
            $order->save_meta_data();
            return;
        }
        $session_response=drop_print_make_server_request_for_ajax('quotes/session',$initial_payload,'POST',45,$responsible_user_id);
        if(is_wp_error($session_response)||(isset($session_response['success'])&&$session_response['success']===false)||empty($session_response['quote_id'])){
            $error_message=is_wp_error($session_response)?$session_response->get_error_message():($session_response['message']??__('Failed to initiate quote session with server.','drop-print'));
            $error_code=is_wp_error($session_response)?$session_response->get_error_code():($session_response['code']??'unknown_session_error');
            $is_prerequisite_failure=($error_code==='payload_validation_failed'||strpos($error_message,'required')!==false||strpos($error_message,'Missing')!==false);
            $log_msg_prefix=($is_prerequisite_failure?__('Prerequisite Failure','drop-print'):__('Quote Session Error','drop-print'));
            $order_note_text_fail = __('Drop Print Auto-Production Failed: %1$s - %2$s','drop-print');
            $order->add_order_note(sprintf($order_note_text_fail, $log_msg_prefix, $error_message));
            $meta_status=$is_prerequisite_failure?'auto_production_prerequisite_failed':'auto_production_quote_session_failed';
            $order->update_meta_data('_drop_print_order_details',['status'=>$meta_status,'last_server_message'=>$error_message,'last_client_update'=>time(), 'responsible_user_id' => $responsible_user_id]);
            $order->save_meta_data();
            return;
        }
        $quote_id=$session_response['quote_id'];
        $order_meta_for_quote_init = $order->get_meta('_drop_print_order_details', true);
        if(!is_array($order_meta_for_quote_init)) $order_meta_for_quote_init = [];
        $order_meta_for_quote_init['quote_id'] = $quote_id;
        $order_meta_for_quote_init['status'] = 'auto_production_quote_initiated';
        $order_meta_for_quote_init['last_client_update'] = time();
        $order_meta_for_quote_init['responsible_user_id'] = $responsible_user_id;
        $order->update_meta_data('_drop_print_order_details', $order_meta_for_quote_init);
        $order->save_meta_data();
        $shipping_methods_to_try=array_unique(array_filter([
            isset($user_settings['default_shipping_method'])?sanitize_key($user_settings['default_shipping_method']):'standard',
            'overnight','express','standard','budget'
        ]));
        $final_quote_details=null;
        $selected_shipping_method=null;
        $shipping_calculation_error=null;
        foreach($shipping_methods_to_try as $method_to_try){
            $price_payload=['quote_id'=>$quote_id,'tier'=>$method_to_try];
            $price_response=drop_print_make_server_request_for_ajax('quotes/price',$price_payload,'POST',45,$responsible_user_id);
            if(is_wp_error($price_response)||(isset($price_response['success'])&&$price_response['success']===false)||!isset($price_response['amount'])){
                $shipping_calculation_error=is_wp_error($price_response)?$price_response->get_error_message():($price_response['message']??__('Error calculating total with server.','drop-print'));
                continue;
            }
            $final_quote_details=$price_response;
            $selected_shipping_method=$method_to_try;
            $shipping_calculation_error=null;
            break;
        }
        if(!$final_quote_details||!$selected_shipping_method){
            $error_msg=$shipping_calculation_error?:__('Could not find any available shipping method after trying all options. Manual review may be required.','drop-print');
            $order_note_shipping_fail = __('Drop Print Auto-Production Failed: %1$s','drop-print');
            $order->add_order_note(sprintf($order_note_shipping_fail, $error_msg));
            $current_order_meta=$order->get_meta('_drop_print_order_details',true);
            if(!is_array($current_order_meta))$current_order_meta=[];
            $current_order_meta['status']='auto_production_shipping_failed';
            $current_order_meta['last_server_message']=$error_msg;
            $current_order_meta['last_client_update']=time();
            $order->update_meta_data('_drop_print_order_details',$current_order_meta);
            $order->save_meta_data();
            return;
        }
        if($selected_shipping_method!==($user_settings['default_shipping_method']??'standard')){
            $shipping_change_msg_format = __('Shipping method for order #%1$s was automatically changed from %2$s to %3$s as the original was unavailable. The final charge reflects the new shipping cost.','drop-print');
            $downgrade_msg=sprintf($shipping_change_msg_format, $client_order_id, ($user_settings['default_shipping_method']??'default'), $selected_shipping_method);
            $order_note_shipping_change = __('Drop Print: %1$s','drop-print');
            $order->add_order_note(sprintf($order_note_shipping_change, $downgrade_msg));
        }
        $payment_payload=['quote_id'=>$quote_id,'shipping_method_preference'=>$selected_shipping_method,'charge_automatically'=>true];
        $payment_intent_response=drop_print_make_server_request_for_ajax('payments/intent',$payment_payload,'POST',45,$responsible_user_id);
        $current_order_meta=$order->get_meta('_drop_print_order_details',true);
        if(!is_array($current_order_meta))$current_order_meta=[];
        $current_order_meta['quote_id']=$quote_id;
        $current_order_meta['final_shipping_method_selected']=$selected_shipping_method;
        $current_order_meta['calculated_total']=$final_quote_details['amount']??null;
        $current_order_meta['calculated_currency']=$final_quote_details['currency']??null;
        $current_order_meta['last_client_update']=time();
        if(is_wp_error($payment_intent_response)||(isset($payment_intent_response['success'])&&$payment_intent_response['success']===false)||empty($payment_intent_response['stripe_client_secret'])){
            $error_message=is_wp_error($payment_intent_response)?$payment_intent_response->get_error_message():($payment_intent_response['message']??__('Failed to create or confirm payment intent with server. Manual payment via "Quote & Pay" may be required.','drop-print'));
            $order_note_payment_fail = __('Drop Print Auto-Production Failed: %1$s','drop-print');
            $order->add_order_note(sprintf($order_note_payment_fail, $error_message));
            $current_order_meta['status']='auto_production_payment_failed';
            $current_order_meta['last_server_message']=$error_message;
        }else{
            $current_order_meta['payment_intent_id']=$payment_intent_response['payment_intent_id']??null;
            $pi_status=$payment_intent_response['status']??'unknown';
            if($pi_status==='succeeded'){
                $current_order_meta['status']='awaiting_webhook_confirmation';
                $order_note_payment_success = __('Drop Print Auto-Production: Payment successful (PI: %1$s). Awaiting server confirmation.','drop-print');
                $order->add_order_note(sprintf($order_note_payment_success, $current_order_meta['payment_intent_id']));
            }elseif($pi_status==='requires_action'||$pi_status==='requires_source_action'){
                $current_order_meta['status']='auto_production_requires_intervention';
                $intervention_msg=__('Automatic payment requires further action (e.g., 3D Secure) and could not be completed. Please attempt payment manually via "Quote & Pay".','drop-print');
                $order_note_intervention = __('Drop Print Auto-Production: %1$s (PI: %2$s)','drop-print');
                $order->add_order_note(sprintf($order_note_intervention, $intervention_msg, $current_order_meta['payment_intent_id']));
                $current_order_meta['last_server_message']=$intervention_msg;
            }else{
                $current_order_meta['status']='auto_production_payment_failed';
                $failed_status_msg_format = __('Automatic payment failed with status: %1$s.','drop-print');
                $failed_msg=sprintf($failed_status_msg_format, $pi_status).' '.(isset($payment_intent_response['message'])?$payment_intent_response['message']:'').' '.__('Manual payment via "Quote & Pay" may be required.','drop-print');
                $order_note_payment_unsuccessful = __('Drop Print Auto-Production Failed: %1$s (PI: %2$s)','drop-print');
                $order->add_order_note(sprintf($order_note_payment_unsuccessful, $failed_msg, $current_order_meta['payment_intent_id']));
                $current_order_meta['last_server_message']=$failed_msg;
            }
        }
        $order->update_meta_data('_drop_print_order_details',$current_order_meta);
        $order->save_meta_data();
    }
}
