<?php
namespace EPWF\Includes;
defined('ABSPATH')||exit;
class FAQ_Manager {
    private $s,$ai;
    public function __construct(Settings $s,AI_Client $ai){$this->s=$s;$this->ai=$ai;}
    public function get_display_faqs($pid){$ov=$this->get_override($pid);return!empty($ov)?$ov:$this->get_generated($pid);}
    public function get_generated($pid){$r=get_post_meta($pid,EPWF_META_FAQS,true);return(is_array($r)&&!empty($r))?$r:[];}
    public function get_override($pid){$r=get_post_meta($pid,EPWF_META_OVERRIDE,true);return(is_array($r)&&!empty($r))?$r:[];}
    public function save_override($pid,$faqs){update_post_meta($pid,EPWF_META_OVERRIDE,$this->clean($faqs));}
    public function save_enabled($pid,$bool){update_post_meta($pid,EPWF_META_ENABLED,$bool?'1':'0');}
    public function is_enabled($pid){$m=get_post_meta($pid,EPWF_META_ENABLED,true);return''===$m?$this->s->is_enabled():'1'===$m;}
    public function maybe_auto_generate($pid,$post){
        if(!$this->s->is_auto_generate()||!$this->s->has_key())return;
        if(!in_array($post->post_status,['publish','draft'],true))return;
        $p=wc_get_product($pid);if(!$p instanceof \WC_Product)return;
        $t=$p->get_name();$d=$p->get_description()?:$p->get_short_description();
        $hash=md5($t.$d);
        if($hash===get_post_meta($pid,EPWF_META_HASH,true)&&!empty($this->get_generated($pid)))return;
        $this->do_generate($pid,$t,$d);
    }
    public function force_generate($pid){
        $p=wc_get_product($pid);
        if(!$p instanceof \WC_Product)return new \WP_Error('epwf_no_product',__('Product not found.','exertpro-faq-ai'));
        return $this->do_generate($pid,$p->get_name(),$p->get_description()?:$p->get_short_description());
    }
    private function do_generate($pid,$title,$desc){
        $result=$this->ai->generate($title,$desc,$this->s->get_faq_count());
        if(is_wp_error($result)){update_post_meta($pid,'_epwf_last_error',$result->get_error_message());return $result;}
        if($this->s->is_additive()){$existing=$this->get_generated($pid);$result=$this->merge($existing,$result);}
        update_post_meta($pid,EPWF_META_FAQS,$result);
        update_post_meta($pid,EPWF_META_HASH,md5($title.$desc));
        delete_post_meta($pid,'_epwf_last_error');
        return $result;
    }
    private function merge($existing,$new){
        $keys=[];foreach($existing as $i)$keys[$this->norm($i['question'])]=true;
        foreach($new as $i){$k=$this->norm($i['question']);if(!isset($keys[$k])){$existing[]=$i;$keys[$k]=true;}}
        return $existing;
    }
    private function norm($q){return strtolower(trim(preg_replace('/\s+/',' ',wp_strip_all_tags($q))?:''));}
    public function clean($faqs){
        $out=[];
        foreach($faqs as $i){if(!is_array($i))continue;$q=sanitize_text_field(isset($i['question'])?$i['question']:'');$a=sanitize_textarea_field(isset($i['answer'])?$i['answer']:'');if($q&&$a)$out[]=['question'=>$q,'answer'=>$a];}
        return $out;
    }
    public function delete_all($pid){foreach([EPWF_META_FAQS,EPWF_META_OVERRIDE,EPWF_META_ENABLED,EPWF_META_HASH,'_epwf_last_error'] as $k)delete_post_meta($pid,$k);}
}
