<?php
namespace DZQCOD\Addons;
if (!defined('ABSPATH')) exit;
if (!\DZQCOD\Modules::is_on('heatmap')) return;

class FormHeatmap {
    public static function init():void{
        add_action('wp_ajax_dzqcod_heatmap_data',[self::class,'get_data']);
        add_action('wp_ajax_nopriv_dzqcod_heatmap_track',[self::class,'track']);
        add_action('wp_ajax_dzqcod_heatmap_track',[self::class,'track']);
        add_action('dzqcod_admin_page_heatmap',[self::class,'admin_page']);
        add_action('wp_footer',[self::class,'inject_tracker']);
        add_action('admin_init',[self::class,'install'],5);
    }
    public static function install():void{
        if(get_option('dzqcod_hm_v','0')==='1.0')return;
        global $wpdb;$wpdb->query("CREATE TABLE IF NOT EXISTS {$wpdb->prefix}dz_heatmap (id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,session_id VARCHAR(64),field_name VARCHAR(100),event_type VARCHAR(20) DEFAULT 'focus',time_spent INT DEFAULT 0,dropped TINYINT(1) DEFAULT 0,page_url VARCHAR(500),created_at DATETIME DEFAULT CURRENT_TIMESTAMP,INDEX idx_f(field_name),INDEX idx_s(session_id)) ".$wpdb->get_charset_collate());
        update_option('dzqcod_hm_v','1.0');
    }
    public static function track():void{
        $fields=json_decode(stripslashes($_POST['fields']??'[]'),true);if(!is_array($fields))wp_send_json_error();
        global $wpdb;$t=$wpdb->prefix.'dz_heatmap';$sid=sanitize_text_field($_POST['session']??md5(uniqid()));$url=sanitize_url($_POST['url']??'');
        foreach($fields as $f){$wpdb->insert($t,['session_id'=>$sid,'field_name'=>sanitize_text_field($f['name']??''),'event_type'=>sanitize_text_field($f['event']??'focus'),'time_spent'=>absint($f['time']??0),'dropped'=>(int)($f['dropped']??0),'page_url'=>$url]);}
        wp_send_json_success();
    }
    public static function get_data():void{
        check_ajax_referer('dzqcod_admin','nonce');global $wpdb;$t=$wpdb->prefix.'dz_heatmap';$days=absint($_POST['days']??7);$from=gmdate('Y-m-d',strtotime("-{$days} days"));
        $fields=$wpdb->get_results($wpdb->prepare("SELECT field_name,COUNT(*) as views,SUM(CASE WHEN event_type='focus' THEN 1 ELSE 0 END) as focuses,AVG(time_spent) as avg_time,SUM(dropped) as drops FROM {$t} WHERE created_at>=%s GROUP BY field_name ORDER BY views DESC",$from),ARRAY_A);
        $sessions=(int)$wpdb->get_var($wpdb->prepare("SELECT COUNT(DISTINCT session_id) FROM {$t} WHERE created_at>=%s",$from));
        $total_drops=(int)$wpdb->get_var($wpdb->prepare("SELECT COUNT(DISTINCT session_id) FROM {$t} WHERE dropped=1 AND created_at>=%s",$from));
        wp_send_json_success(compact('fields','sessions','total_drops'));
    }
    public static function inject_tracker():void{
        if(!is_singular('product')&&!has_shortcode(get_post()->post_content??'','dzqcod_form'))return;
        ?><script>
        (function(){var sid='hm_'+Math.random().toString(36).substr(2,9),data={},active=null,startT=0;
        document.addEventListener('focusin',function(e){if(!e.target.name&&!e.target.id)return;var n=e.target.name||e.target.id;active=n;startT=Date.now();if(!data[n])data[n]={name:n,event:'focus',time:0,dropped:0}});
        document.addEventListener('focusout',function(e){if(active&&data[active])data[active].time+=Math.round((Date.now()-startT)/1000);active=null});
        window.addEventListener('beforeunload',function(){var submitted=document.querySelector('.dzqcod-success');var fields=Object.values(data);if(!submitted)fields.forEach(function(f){f.dropped=1});
            navigator.sendBeacon('<?php echo admin_url("admin-ajax.php");?>',new URLSearchParams({action:'dzqcod_heatmap_track',session:sid,url:location.href,fields:JSON.stringify(fields)}))})})();
        </script><?php
    }
    public static function admin_page():void{?>
<div class="dza-wrap" style="direction:rtl;font-family:Tajawal,sans-serif">
<h2 style="font-size:22px;margin-bottom:16px">🔥 Form Heatmap — تحليل تفاعل النموذج</h2>
<div style="display:flex;gap:8px;margin-bottom:16px;align-items:center">
<select id="hm-days" style="padding:8px;border:1px solid #ddd;border-radius:6px"><option value="1">اليوم</option><option value="7" selected>7 أيام</option><option value="30">30 يوم</option></select>
<button onclick="hmLoad()" style="padding:8px 20px;background:#EF4444;color:#fff;border:none;border-radius:8px;cursor:pointer;font-weight:700">🔥 تحليل</button></div>
<div id="hm-result" style="text-align:center;color:#aaa;padding:30px">اضغط تحليل</div></div>
<script>
function hmLoad(){jQuery('#hm-result').html('⏳');jQuery.post(dza.ajax,{action:'dzqcod_heatmap_data',nonce:dza.nonce,days:jQuery('#hm-days').val()},function(r){
    if(!r.success)return;var d=r.data,h='<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-bottom:16px">';
    h+='<div style="background:#fff;border-radius:12px;padding:16px;text-align:center;box-shadow:0 2px 8px rgba(0,0,0,.06)"><div style="font-size:11px;color:#888">جلسات</div><div style="font-size:28px;font-weight:800;color:#6366F1">'+d.sessions+'</div></div>';
    h+='<div style="background:#fff;border-radius:12px;padding:16px;text-align:center;box-shadow:0 2px 8px rgba(0,0,0,.06)"><div style="font-size:11px;color:#888">حقول متتبعة</div><div style="font-size:28px;font-weight:800;color:#10B981">'+d.fields.length+'</div></div>';
    h+='<div style="background:#fff;border-radius:12px;padding:16px;text-align:center;box-shadow:0 2px 8px rgba(0,0,0,.06)"><div style="font-size:11px;color:#888">مغادرات</div><div style="font-size:28px;font-weight:800;color:#EF4444">'+d.total_drops+'</div></div></div>';
    h+='<div style="background:#fff;border-radius:12px;padding:16px;box-shadow:0 2px 8px rgba(0,0,0,.06)"><h4 style="margin:0 0 12px">📊 تفاعل كل حقل</h4>';
    d.fields.forEach(function(f){var maxV=d.sessions||1;var pct=Math.round(f.views/maxV*100);var heat=pct>70?'#10B981':pct>40?'#F59E0B':'#EF4444';
        h+='<div style="margin-bottom:8px"><div style="display:flex;justify-content:space-between;font-size:12px;margin-bottom:2px"><span style="font-weight:700">'+f.field_name+'</span><span>'+f.views+' تفاعل | '+Math.round(f.avg_time)+'ث | '+f.drops+' مغادرة</span></div>';
        h+='<div style="background:#f1f5f9;border-radius:4px;height:20px;overflow:hidden"><div style="height:100%;background:'+heat+';width:'+Math.min(pct,100)+'%;border-radius:4px;transition:.3s"></div></div></div>'});
    h+='</div>';jQuery('#hm-result').html(h)})}
</script><?php
    }
}
FormHeatmap::init();
