';
$config=wp_json_encode(['id'=>$id,'url'=>admin_url('admin-ajax.php'),'nonce'=>wp_create_nonce('courierapp_carrier_settings'),'logoBase'=>courierapp_connect_carrier_assets(),'language'=>str_starts_with(determine_locale(),'el')?'el':'en']);
wp_add_inline_script('courierapp-carrier-settings', '(function(c){CourierAppCarriers(document.getElementById(c.id),async function(path,payload){const response=await fetch(c.url+"?action=courierapp_carrier_settings&_ajax_nonce="+encodeURIComponent(c.nonce),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({operation:path,payload:payload})});const result=await response.json();if(!response.ok||!result.success){const e=new Error(result.data&&result.data.code||"network_error");e.code=e.message;throw e;}return result.data;},c.language,c.logoBase,{platform:"woocommerce",assistantRequest:async function(payload,key,operation="drafts"){const response=await fetch(c.url+"?action=courierapp_carrier_settings&_ajax_nonce="+encodeURIComponent(c.nonce),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({operation:operation==="history"?"/assistant/history":operation==="chat"?"/assistant/chat":"/assistant",payload:payload,idempotency_key:key})});const result=await response.json();if(!response.ok||!result.success){const e=new Error(result.data&&result.data.code||"assistant_unavailable");e.code=e.message;throw e;}return result.data;}});})('.$config.');');
}
add_action('admin_menu', function(){
add_submenu_page('woocommerce',__('Courier connections','courierapp-connect'),__('Courier connections','courierapp-connect'),'manage_woocommerce','courierapp-carriers',function(){echo '
';courierapp_connect_integration_panel();echo '
';});
});
add_action('wp_ajax_courierapp_carrier_settings', function(){
if(!current_user_can('manage_woocommerce')) wp_send_json_error(['code'=>'forbidden'],403);
check_ajax_referer('courierapp_carrier_settings');
if(isset($_SERVER['CONTENT_LENGTH'])&&(int)$_SERVER['CONTENT_LENGTH']>524288) wp_send_json_error(['code'=>'payload_too_large'],413);
$raw=file_get_contents('php://input',false,null,0,524289);
if(strlen($raw)>524288) wp_send_json_error(['code'=>'payload_too_large'],413);
$input=json_decode($raw,true);$path=$input['operation']??null;
if(!is_string($path)||($path!==''&&!in_array($path,['/assistant','/assistant/chat','/assistant/history'],true)&&!preg_match('#^/(dhl|fedex|acs|speedex|couriercenter)/(credentials|verify|tariff|toggle)$#D',$path))) wp_send_json_error(['code'=>'invalid_operation'],422);
$connection=courierapp_connect_connection();
if(empty($connection['key'])) wp_send_json_error(['code'=>'account_connection_required'],409);
$assistant=$path==='/assistant';$chat=$path==='/assistant/chat';$history=$path==='/assistant/history';
if($assistant && (!is_array($input['payload']??null)||($input['payload']['task']??'')!=='setup_guidance'||!preg_match('/^[A-Za-z0-9_.:-]{8,160}$/D',$input['idempotency_key']??''))) wp_send_json_error(['code'=>'invalid_operation'],422);
if($history && (!in_array($input['payload']['platform']??'', ['woocommerce','shopify'],true)||(!empty($input['payload']['thread'])&&!preg_match('/^[a-f0-9-]{36}$/D',$input['payload']['thread'])))) wp_send_json_error(['code'=>'invalid_operation'],422);
$endpoint=$chat||$history?'https://swdjgtbhifglgnnmwthf.supabase.co/functions/v1/merchant-assistant/v1/setup/'.($chat?'chat':'history?'.http_build_query(array_intersect_key($input['payload'],array_flip(['platform','thread'])))) : ($assistant?'https://swdjgtbhifglgnnmwthf.supabase.co/functions/v1/merchant-assistant/v1/drafts':'https://swdjgtbhifglgnnmwthf.supabase.co/functions/v1/merchant-integrations/stores/self/carriers'.$path);
$headers=['Authorization'=>'Bearer '.$connection['key'],'Content-Type'=>'application/json'];
if($assistant)$headers['Idempotency-Key']=$input['idempotency_key'];
$response=wp_remote_request($endpoint,[
'method'=>$path===''||$history?'GET':'POST','headers'=>$headers,
'body'=>$path===''||$history?null:wp_json_encode($input['payload']??new stdClass()),'timeout'=>$assistant||$chat?60:30,'redirection'=>0,'sslverify'=>true,
]);
if(is_wp_error($response)) wp_send_json_error(['code'=>'network_error'],502);
$code=wp_remote_retrieve_response_code($response);$data=json_decode(wp_remote_retrieve_body($response),true);
if($code<200||$code>=300||!is_array($data)) wp_send_json_error(['code'=>sanitize_key(is_array($data['error']??null)?($data['error']['code']??'api_error'):($data['error']??'api_error'))],$code>=400&&$code<=599?$code:502);
if($path!==''&&!$assistant&&!$chat&&!$history&&class_exists('WC_Cache_Helper')) WC_Cache_Helper::get_transient_version('shipping',true);
wp_send_json_success($data);
});