<?php
if(!defined('ABSPATH')){exit;}
if(!function_exists('drop_print_add_production_column_client')){
    function drop_print_add_production_column_client($columns){
        $current_user_id = get_current_user_id();
        $user_settings = drop_print_get_user_settings($current_user_id);
        $is_dp_connected = !empty($user_settings['client_user_connection_id']);
        if(!$is_dp_connected){
            return $columns;
        }
        $new_columns=array();
        $inserted=false;
        foreach($columns as $key=>$column_value){
            $new_columns[$key]=$column_value;
            if('order_status'===$key&&!$inserted){
                $new_columns['drop_print_production']=__('Drop Print','drop-print');
                $inserted=true;
            }
        }
        if(!$inserted){
            $temp_action_column=null;
            if(isset($new_columns['wc_actions'])){
                $temp_action_column=$new_columns['wc_actions'];
                unset($new_columns['wc_actions']);
            }elseif(isset($new_columns['actions'])){
                $temp_action_column=$new_columns['actions'];
                unset($new_columns['actions']);
            }
            $new_columns['drop_print_production']=__('Drop Print','drop-print');
            if($temp_action_column!==null){
                if(array_key_exists('wc_actions',$columns)){$new_columns['wc_actions']=$temp_action_column;}
                elseif(array_key_exists('actions',$columns)){$new_columns['actions']=$temp_action_column;}
            }
        }
        return $new_columns;
    }
}
add_filter('manage_edit-shop_order_columns','drop_print_add_production_column_client',20);
add_filter('manage_woocommerce_page_wc-orders_columns','drop_print_add_production_column_client',20);
if(!function_exists('drop_print_render_printfile_error_button')){
    function drop_print_render_printfile_error_button($order_id, array $missing_skus){
        $skus_display = implode(', ', $missing_skus);
        $detail_text = sprintf(
            __('No Drop Print file is on file for: %s. Open the product, go to its Drop Print tab, and complete the file upload steps used when it was first set up. Because this order was placed with no file on record, please ask the customer to place a new order once the product is fixed.', 'drop-print'),
            esc_html($skus_display)
        );
        return '<button type="button" class="button drop-print-printfile-error-button" data-order-id="' . esc_attr($order_id) . '" aria-expanded="false">' . esc_html__('Printfile Error', 'drop-print') . '</button>'
            . '<div class="drop-print-printfile-error-detail" style="display:none;margin-top:6px;max-width:260px;">' . $detail_text . '</div>';
    }
}
if(!function_exists('drop_print_render_production_column_content_client')){
    function drop_print_render_production_column_content_client($column,$post_id_or_order_obj){
        if('drop_print_production'!==$column)return;
        $order=null;
        if($post_id_or_order_obj instanceof WC_Order){
            $order=$post_id_or_order_obj;
        }elseif(is_numeric($post_id_or_order_obj)){
            $order=wc_get_order($post_id_or_order_obj);
        }
        if(!$order){
            echo esc_html__('N/A','drop-print');
            return;
        }
        $order_id=$order->get_id();
        $details=$order->get_meta('_drop_print_order_details',true);
        if(!is_array($details)){$details=array();}
        $status=isset($details['status'])?sanitize_key($details['status']):'';
        $server_wc_order_id=isset($details['server_order_id'])?absint($details['server_order_id']):null;
        $queue_id=isset($details['queue_id'])?sanitize_text_field($details['queue_id']):null;
        $receipt_url=isset($details['receipt_url'])?esc_url_raw($details['receipt_url']):null;
        $status_output='';
        $api_uri_for_link=defined('DROP_PRINT_API_URI')?DROP_PRINT_API_URI:'';
        $server_link_base='';
        if(!empty($api_uri_for_link)){
            $parsed_url=wp_parse_url($api_uri_for_link);
            if(isset($parsed_url['scheme'],$parsed_url['host'])){
                $server_link_base=$parsed_url['scheme'].'://'.$parsed_url['host'];
                if(isset($parsed_url['port'])){
                    $server_link_base.=':'.$parsed_url['port'];
                }
                if(strpos($server_link_base,'/wp-json')!==false){
                    $server_link_base=substr($server_link_base,0,strpos($server_link_base,'/wp-json'));
                }
                $server_link_base=trailingslashit($server_link_base);
            }
        }
        $server_order_id_title_text=$server_wc_order_id?sprintf(' (Srv ID: %s)',esc_html($server_wc_order_id)):'';
        $server_my_account_order_url=($server_wc_order_id&&!empty($server_link_base))?$server_link_base.'my-account/view-order/'.$server_wc_order_id.'/':'#';
        $status_label=ucfirst(str_replace('_',' ',$status));
        $link_title_base=__('View order progress at Drop Print Server','drop-print');
        $has_drop_print_item = false;
        $missing_file_skus = array();
        foreach ($order->get_items() as $item) {
            if ($item instanceof WC_Order_Item_Product) {
                $product_id_for_meta = $item->get_product_id();
                $product_obj = wc_get_product($product_id_for_meta);
                if ($product_obj && $product_obj->is_type('variation')) {
                    $product_id_for_meta = $product_obj->get_parent_id();
                }
                $drop_print_meta = get_post_meta($product_id_for_meta, '_drop_print_meta', true);
                $is_drop_print_product = is_array($drop_print_meta) && 'yes' === ($drop_print_meta['active'] ?? 'no');
                if ($is_drop_print_product && !empty($drop_print_meta['file'])) {
                    $has_drop_print_item = true;
                }
                if ($is_drop_print_product && empty($drop_print_meta['file'])) {
                    $parent_product_obj = $product_id_for_meta ? wc_get_product($product_id_for_meta) : null;
                    $sku_or_name = $parent_product_obj ? $parent_product_obj->get_sku() : '';
                    if (empty($sku_or_name)) {
                        $sku_or_name = $parent_product_obj ? $parent_product_obj->get_name() : ('#' . $product_id_for_meta);
                    }
                    $missing_file_skus[] = sanitize_text_field($sku_or_name);
                }
            }
        }
        $missing_file_skus = array_values(array_unique(array_filter($missing_file_skus)));
        switch($status){
            case 'awaiting_webhook_confirmation':
            case 'payment_processing_initiated':
                $status_label=__('Processing Payment','drop-print');
                $status_output = "<span class=\"order-status dp-status-processing-payment\" title=\"" . esc_attr__('Payment submitted, awaiting server confirmation.', 'drop-print') . "\"><span>" . esc_html($status_label) . "</span></span>";
                break;
            case 'pre_production_queue':
                $status_label=__('Pre-Production','drop-print');
                $link_classes="order-status dp-status-pre-production";
                if(!empty($receipt_url)){
                    $status_output=sprintf('<a href="%s" class="%s" target="_blank" rel="noopener noreferrer" title="%s"><span>%s</span></a>',esc_url($receipt_url),esc_attr($link_classes),esc_attr__('View Stripe Receipt','drop-print'),esc_html($status_label));
                }else{
                    $status_output=sprintf('<span class="%s" title="%s"><span>%s</span></span>',esc_attr($link_classes),esc_attr__('Payment processed, awaiting server queue.','drop-print'),esc_html($status_label));
                }
                break;
            case 'processing_at_server':
            case 'submitted_to_external_api':
            case 'printing':
                $status_label=__('In Production','drop-print');
                $link_classes="order-status dp-status-in-production";
                 if($server_my_account_order_url!=='#'){
                    $status_output=sprintf('<a href="%s" target="_blank" rel="noopener noreferrer" class="%s" title="%s"><span>%s</span></a>',esc_url($server_my_account_order_url),esc_attr($link_classes),esc_attr($link_title_base.$server_order_id_title_text),esc_html($status_label));
                }else{
                    $status_output=sprintf('<span class="%s"><span>%s%s</span></span>',esc_attr($link_classes),esc_html($status_label),$server_order_id_title_text);
                }
                break;
            case 'shipped':
            case 'completed':
            case 'production-completed':
                $status_label=__('Shipped','drop-print');
                $link_classes="order-status dp-status-shipped";
                if($server_my_account_order_url!=='#'){
                    $status_output=sprintf('<a href="%s" target="_blank" rel="noopener noreferrer" class="%s" title="%s"><span>%s</span></a>',esc_url($server_my_account_order_url),esc_attr($link_classes),esc_attr($link_title_base.$server_order_id_title_text),esc_html($status_label));
                }else{
                    $status_output=sprintf('<span class="%s"><span>%s%s</span></span>',esc_attr($link_classes),esc_html($status_label),$server_order_id_title_text);
                }
                break;
            case 'file_issue_detected':
                $status_label=__('File Issue Detected','drop-print');
                $link_classes="order-status dp-status-file-issue";
                $item_ids_with_errors=$details['item_ids_with_errors']??null;
                $current_server_wc_order_id=$details['server_order_id']??$server_wc_order_id;
                if($current_server_wc_order_id&&!empty($item_ids_with_errors)&&is_array($item_ids_with_errors)&&!empty($server_link_base)){
                    $error_with_param=implode(',',array_map('absint',$item_ids_with_errors));
                    $resolution_url=add_query_arg('error_with',urlencode($error_with_param),trailingslashit($server_link_base).'my-account/view-order/'.$current_server_wc_order_id.'/');
                    $status_output=sprintf('<a href="%s" target="_blank" rel="noopener noreferrer" class="%s" title="%s"><span>%s</span></a>',esc_url($resolution_url),esc_attr($link_classes),esc_attr__('Resolve File Issue on Drop Print Server','drop-print'),esc_html($status_label));
                }else{
                    $status_output=sprintf('<span class="%s"><span>%s%s</span></span>',esc_attr($link_classes),esc_html($status_label),$server_order_id_title_text);
                }
                break;
            case 'payment_failed_client_attempt':
            case 'payment_timed_out_waiting_for_webhook':
            case 'auto_production_payment_failed':
            case 'auto_production_quote_session_failed':
            case 'auto_production_quote_calc_failed':
            case 'auto_production_shipping_failed':
            case 'auto_production_prerequisite_failed':
                $failure_message = $details['last_server_message'] ?? $details['last_client_error_message'] ?? $status_label;
                if ($status === 'payment_failed_client_attempt') {
                    $status_label_text = __('Payment Failed - Retry?', 'drop-print');
                } elseif ($status === 'payment_timed_out_waiting_for_webhook') {
                    $status_label_text = __('Confirmation Pending - Retry?', 'drop-print');
                } else {
                    $status_label_text = __('Auto-Prod Failed - Manual Quote', 'drop-print');
                }
                $status_output = "<span class=\"order-status dp-status-error\" title=\"" . esc_attr($failure_message) . "\"><span>" . esc_html($status_label_text) . "</span></span>";
                if($order->has_status(array('on-hold','pending','failed','processing')) && !empty($missing_file_skus)){
                    $status_output.='<br>'.drop_print_render_printfile_error_button($order_id, $missing_file_skus);
                }elseif($order->has_status(array('on-hold','pending','failed','processing')) && $has_drop_print_item){
                    $status_output.='<br><button style="margin-top:5px;" class="button drop-print-send-button button-primary" data-order-id="'.esc_attr($order_id).'" data-original-text="'.esc_attr__('Quote & Pay','drop-print').'">'.esc_html__('Manual Quote & Pay','drop-print').'</button><span class="spinner drop-print-spinner" style="float:none; display:inline-block; vertical-align: middle; margin-left: 5px; visibility: hidden;"></span>';
                }
                break;
            default:
                $would_show_quote_button = (($order->has_status(array('on-hold','pending','failed','processing','cancelled'))&&empty($status)) || !empty($details['quote_reenabled']));
                if($would_show_quote_button && !empty($missing_file_skus)){
                    $status_output=drop_print_render_printfile_error_button($order_id, $missing_file_skus);
                }elseif($would_show_quote_button && $has_drop_print_item){
                    $status_output='<button class="button drop-print-send-button button-primary" data-order-id="'.esc_attr($order_id).'" data-original-text="'.esc_attr__('Quote & Pay','drop-print').'">'.esc_html__('Quote & Pay','drop-print').'</button><span class="spinner drop-print-spinner" style="float:none; display:inline-block; vertical-align: middle; margin-left: 5px; visibility: hidden;"></span>';
                }else{
                    $status_output="<span class=\"order-status dp-status-unknown\"><span>".($status_label&&$status_label!=='Unknown'?esc_html($status_label):esc_html__('-','drop-print'))."</span></span>";
                }
                break;
        }
        echo '<div class="drop-print-status-container">' . wp_kses_post( $status_output ) . '</div>';
    }
}
add_action('manage_shop_order_posts_custom_column','drop_print_render_production_column_content_client',10,2);
add_action('manage_woocommerce_page_wc-orders_custom_column','drop_print_render_production_column_content_client',10,2);
