<?php
if (!defined('ABSPATH')) exit;

final class PCEC_QCD_Client {
    private static function installation_id() {
        $option='pcec_qcd_installation_id';
        $id=sanitize_text_field((string)get_option($option,''));
        if($id) return $id;
        $id=wp_generate_uuid4();
        update_option($option,$id,false);
        return $id;
    }

    private static function event_id(array $payload,$installation_id) {
        $event=sanitize_key($payload['event']??'');
        $identity=$event==='estimate_milestone'
            ? (string)absint($payload['milestone']??0)
            : sanitize_text_field($payload['consent_timestamp']??'');
        $hash=hash('sha256',$installation_id.'|'.sanitize_key($payload['plugin']??'').'|'.$event.'|'.$identity);
        return substr($hash,0,8).'-'.substr($hash,8,4).'-4'.substr($hash,13,3).'-a'.substr($hash,17,3).'-'.substr($hash,20,12);
    }

    private static function enrich_payload(array $payload) {
        $installation_id=self::installation_id();
        $payload['schema_version']='1.0';
        $payload['installation_id']=$installation_id;
        $payload['core_version']=PCEC_Estimator_Core::manifest('core_version','');
        $payload['occurred_at']=sanitize_text_field($payload['timestamp']??current_time('c'));
        if(empty($payload['event_id'])) $payload['event_id']=self::event_id($payload,$installation_id);
        if(empty($payload['email'])&&!empty($payload['owner_email'])) $payload['email']=sanitize_email($payload['owner_email']);
        return $payload;
    }

    public static function tracked_url($placement, $path = '') {
        $base=trailingslashit('https://quietcitydesign.com/'.ltrim((string)$path,'/'));
        return add_query_arg(['utm_source'=>PCEC_Estimator_Core::manifest('qcd_source'),'utm_medium'=>'wordpress-plugin','utm_campaign'=>'lead-system-toolkit','utm_content'=>sanitize_key($placement)],$base);
    }

    public static function endpoint_url() {
        $default=PCEC_Estimator_Core::manifest('qcd_endpoint');
        $filter=PCEC_Estimator_Core::manifest('qcd_endpoint_filter');
        return esc_url_raw((string)apply_filters($filter,$default));
    }

    public static function post_event(array $payload) {
        $url=self::endpoint_url();
        if(!$url||strpos($url,'https://')!==0) return new WP_Error('pcec_qcd_endpoint','The Quiet City Design endpoint is not configured.');
        $payload=self::enrich_payload($payload);
        $headers=['Content-Type'=>'application/json'];
        $token=(string)get_option('pcec_qcd_installation_token','');
        if(($payload['event']??'')==='estimate_milestone'&&$token){
            $timestamp=(string)time();
            $headers['X-QCD-Timestamp']=$timestamp;
            $headers['X-QCD-Signature']='sha256='.hash_hmac('sha256',$timestamp.'.'.$payload['event_id'],$token);
        }
        $response=wp_remote_post($url,['timeout'=>8,'headers'=>$headers,'body'=>wp_json_encode($payload)]);
        if(is_wp_error($response)) return $response;
        $code=(int)wp_remote_retrieve_response_code($response);
        $response_body=wp_remote_retrieve_body($response);
        $body=json_decode($response_body,true);
        if($code<200||$code>=300) {
            $message=is_array($body)?sanitize_text_field($body['message']??$body['error']??''):'';
            return new WP_Error('pcec_qcd_endpoint_http',$message?:'Quiet City Design endpoint returned HTTP '.$code.'.');
        }
        if(is_array($body)&&isset($body['success'])&&!$body['success']) return new WP_Error('pcec_qcd_endpoint_rejected',sanitize_text_field($body['message']??'Quiet City Design endpoint rejected the request.'));
        if(is_array($body)&&!empty($body['installation_token'])) update_option('pcec_qcd_installation_token',sanitize_text_field($body['installation_token']),false);
        return is_array($body)?$body:true;
    }
}
